NewLang Project
Yet another programm language
Loading...
Searching...
No Matches
runtime.cpp
Go to the documentation of this file.
1
2#include <zip.h>
3
4#include "runtime.h"
5
6#include "parser.h"
7#include "analysis.h"
8
9#include "system.h"
10#include "builtin.h"
11
12using namespace newlang;
13
14
15std::string RunTime::ffi_file;
16void * RunTime::m_ffi_handle = nullptr;
17ffi_type * RunTime::m_ffi_type_void = nullptr;
18ffi_type * RunTime::m_ffi_type_uint8 = nullptr;
19ffi_type * RunTime::m_ffi_type_sint8 = nullptr;
20ffi_type * RunTime::m_ffi_type_uint16 = nullptr;
21ffi_type * RunTime::m_ffi_type_sint16 = nullptr;
22ffi_type * RunTime::m_ffi_type_uint32 = nullptr;
23ffi_type * RunTime::m_ffi_type_sint32 = nullptr;
24ffi_type * RunTime::m_ffi_type_uint64 = nullptr;
25ffi_type * RunTime::m_ffi_type_sint64 = nullptr;
26ffi_type * RunTime::m_ffi_type_float = nullptr;
27ffi_type * RunTime::m_ffi_type_double = nullptr;
28ffi_type * RunTime::m_ffi_type_pointer = nullptr;
29
33
35ffi_type * RunTime::m_wide_char_type_ffi = nullptr;
37
38//const char * RunTime::default_argv[RunTime::default_argc] = {"", "--nlc-no-runtime", "--nlc-no-dsl", "--nlc-no-embed-source"};
39//const TermPtr VarScope::NonameBlock = Term::Create(parser::token_type::END, TermID::NAMESPACE, "_");
40
41/*
42 *
43 *
44 *
45 *
46 *
47 *
48 */
49
50static char nlc_prinft_sub_buffer[4096 * 8];
51
52extern "C" int nlc_prinft_sub_(char const *format, ...) {
53 va_list args;
54 va_start(args, format);
55
56 int result = vsnprintf(nlc_prinft_sub_buffer, sizeof (nlc_prinft_sub_buffer), format, args);
57 STATIC_ASSERT(sizeof (nlc_prinft_sub_buffer) == 4096 * 8);
58
59 Logger *log = Logger::Instance();
60 if (log->m_func != nullptr) {
62 }
63
64 // int result = vfprintf(stdout, format, args);
65 va_end(args);
66 return result;
67}
68
69int newlang::RunMain(const int arg, const char** argv, const char** penv) {
70 printf("CALL: RunMain(const int arg, const char** argv, const char** penv)");
71 return 0;
72}
73
75 clear();
76 // m_main_ast.reset();
77 // m_main_runner.reset();
78 // m_main_module.reset();
79}
80
81/*
82 *
83 *
84 *
85 *
86 *
87 *
88 */
89
90//TermPtr RunTime::NameGet(const char *name, bool is_raise) {
91//
92// GlobName * ret = NameFind(name);
93//
94// if (ret) {
95// // if (std::holds_alternative<ObjWeak>(ret->obj)) {
96// // return std::get<ObjWeak>(ret->obj).lock();
97// // } else if (std::holds_alternative<std::vector < ObjWeak >> (ret->obj)) {
98// // return std::get<std::vector < ObjWeak >> (ret->obj)[0].lock();
99// // }
105// if (is_raise) {
106// NL_PARSER(ret->proto, "Global name not implemented! '%s'", name);
107// }
108// } else {
109// if (is_raise) {
110// LOG_RUNTIME("Global Name '%s' not found!", name);
111// }
112// }
113// return nullptr;
114//}
115
116//
117// ObjPtr result = nullptr;
118// ObjPtr temp = nullptr;
119// ObjPtr args = nullptr;
120// ObjPtr value = nullptr;
121// TermPtr field = nullptr;
122// std::string full_name;
123//
124// result = Obj::CreateNone();
125// result->m_is_reference = !!term->m_ref;
126//
127// int64_t val_int;
128// double val_dbl;
129// ObjType type;
130// bool has_error;
131// std::vector<int64_t> sizes;
132// at::Scalar torch_scalar;
133// switch (term->getTermID()) {
134// case TermID::OP_MATH:
135// case TermID::OP_BITWISE:
136// case TermID::OP_COMPARE:
137// case TermID::OP_LOGICAL:
138// return Context::Eval(ctx, term, local_vars, eval_block, int_catch);
139//
140// case TermID::INTEGER:
141//
142// val_int = parseInteger(term->getText().c_str());
143// NL_TYPECHECK(term, typeFromLimit(val_int), typeFromString(term->m_type, ctx ? ctx->m_runtime.get() : nullptr)); // Соответстствует ли тип значению?
144//
145// result = Obj::CreateValue(val_int);
146// result->m_var_type_current = typeFromLimit(val_int);
147// if (term->GetType()) {
148// result->m_var_type_fixed = typeFromString(term->m_type, ctx ? ctx->m_runtime.get() : nullptr);
149// result->m_var_type_current = result->m_var_type_fixed;
150// }
151// return result;
152//
153// case TermID::NUMBER:
154// val_dbl = parseDouble(term->getText().c_str());
155// NL_TYPECHECK(term, typeFromLimit(val_dbl), typeFromString(term->m_type, ctx ? ctx->m_runtime.get() : nullptr)); // Соответстствует ли тип значению?
156//
157// result = Obj::CreateValue(val_dbl);
158// result->m_var_type_current = typeFromLimit(val_dbl);
159// if (term->GetType()) {
160// result->m_var_type_fixed = typeFromString(term->m_type, ctx ? ctx->m_runtime.get() : nullptr);
161// result->m_var_type_current = result->m_var_type_fixed;
162// }
163// return result;
164//
165// case TermID::STRWIDE:
166// return Obj::CreateString(utf8_decode(term->getText()));
167//
168//
169// case TermID::STRCHAR:
170// return Obj::CreateString(term->getText());
171//
172// case TermID::EVAL:
173// /*
174// * subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
175// * capture_output=False, shell=False, cwd=None, timeout=None, check=False,
176// * encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)
177// */
178// /* class subprocess.Popen(args, bufsize = -1, executable = None,
179// * stdin = None, stdout = None, stderr = None,
180// * preexec_fn = None, close_fds = True, shell = False, cwd = None,
181// * env = None, universal_newlines = None, startupinfo = None,
182// * creationflags = 0, restore_signals = True, start_new_session = False,
183// * pass_fds = (), *, group = None, extra_groups = None, user = None, umask = -1
184// * , encoding = None, errors = None, text = None,
185// * pipesize = -1, process_group = None)¶
186// */
187//
188//
189//
190// // result = Obj::CreateType(ObjType::Eval, ObjType::Eval, true);
191// // result->m_value = term->getText();
192// // if (term->isCall()) {
193// LOG_RUNTIME("Not implemented!!!");
194// // }
195// // return Exec(ctx, term->getText().c_str(), nullptr);
196//
197// /* case TermID::FIELD:
198// if(module && module->HasFunc(term->GetFullName().c_str())) {
199// // Если поле является функцией и она загружена
200// result = Obj::CreateType(Obj::Type::FUNCTION,
201// term->GetFullName().c_str()); result->m_module = module;
202// result->m_is_const = term->m_is_const;
203// result->m_is_ref = term->m_is_ref;
204// return result;
205// }
206// if(!result) {
207// LOG_RUNTIME("Term '%s' not found!",
208// term->toString().c_str());
209// }
210// return result;
211// */
212//
213// //@todo Что делать с пустыми значениями? Это None ???
214// case TermID::EMPTY:
215// result->m_var_type_current = ObjType::None;
216// result->m_var_is_init = false;
217// return result;
218//
219//
220//
221// case TermID::NEWLANG:
222// case TermID::MODULE:
223// /* Prototype \\‍(file=_, filter='*', load=@true, source=_)
224// * Required argument $file or $source can be only one
225// *
226// * \\‍('name') - dynamic load module
227// * \\dir\name() - load module and
228// * \\dir\name::func() - call function from module
229// * module := \\‍('name', @false) - Check module is loaded and don't load it
230// *
231// */
232//
233// if (term->isCall() && ExtractName(term->getText()).empty()) {
234// // Load module
235//
236// return ctx->m_runtime->OpLoadModule(term);
237// }
238//
239// // if (!ctx->m_runtime->CkeckLoadModule(term)) {
240// // NL_PARSER(term, "The '%s' module must be preloaded using the '%s()' command!", term->getText().c_str(), term->getText().c_str());
241// // }
242//
243//
244//
245//
246// // if (isModule(term->GetFullName())) {
247// // if (term->isCall()) {
248// // /*
249// // * Операцию с модулем можно конкреттизировать с помощью аргумента
250// // * \module() - загрузка модуля и импорт всех его объектов
251// // * \module("filter*") - загрузка модуля и импорт всех его объектов по заданной маске в переданой строке
252// // * \module("func;ns::*;ns2::*") - несколько масок записываются через точку с запятой
253// // * \module(@true) - убедиться, что модуль загружен. Если модуль не загружен, создать ошибку
254// // * \module(@false) - проверить, загружен ли модуль без его реальной загрузки и вернуть значение
255// // * \module(_) - Выгрузка модуля
256// // *
257// // * \\dsl() - Единственный встроенный модуль
258// // */
259// //
260// // if (term->size() > 1) {
261// // NL_PARSER(term, "Only one argument can be specified for a load module!");
262// // }
263// //
264// // std::vector<std::string> filter;
265// // if (term->size()) {
266// // ASSERT(term->size() == 1);
267// // args = CreateRVal(ctx, term->at(0).second, local_vars);
268// // ASSERT(args);
269// //
270// // auto found = ctx->m_runtime->m_modules.find(term->getText());
271// // if (args->is_bool_type()) {
272// //
273// // if (args->GetValueAsBoolean() && found == ctx->m_runtime->m_modules.end()) {
274// // NL_PARSER(term, "Module %s not loaded!", term->getText().c_str());
275// // }
276// // return found == ctx->m_runtime->m_modules.end() ? Obj::Yes() : Obj::No();
277// //
278// // } else if (args->is_none_type()) {
279// //
280// // result = (found == ctx->m_runtime->m_modules.end() ? Obj::Yes() : Obj::No());
281// // if (found != ctx->m_runtime->m_modules.end()) {
282// // ctx->m_runtime->m_modules.erase(found);
283// // }
284// //
285// // ctx->CleanUp();
286// //
287// // return result;
288// //
289// // } else if (args->is_string_type()) {
290// // filter = Macro::SplitString(args->GetValueAsString().c_str(), ";");
291// // }
292// // }
293// //
294// //
295// // if (!ctx->m_runtime->CheckOrLoadModule(term->GetFullName())) {
296// // LOG_RUNTIME("Fail load module %s!", ExtractModuleName(term->GetFullName().c_str()).c_str());
297// // }
298// //
299// //
300// // size_t count = 0;
301// // auto module = ctx->m_runtime->m_modules[term->getText()];
302// //
303// // if (filter.empty()) {
304// // for (size_t i = 0; i < module->size(); i++) {
305// // ctx->push_front(module->at(i));
306// // count++;
307// // }
308// // } else {
309// //
310// // LOG_WARNING("Import of objects by mask does not work correctly!");
311// //
312// // std::vector<std::regex> regs;
313// // for (auto &elem : filter) {
314// // try {
315// // // LOG_DEBUG("From: %s", elem.c_str());
316// //
317// // // if(elem.rfind("::") != 0) {
318// // // elem.insert(0, "::");
319// // // }
320// // // elem.insert(0, term->getText());
321// //
322// // elem = std::regex_replace(elem, std::regex("@."), "@@.");
323// // elem = std::regex_replace(elem, std::regex("@*"), "(.)*");
324// // // LOG_DEBUG("To: %s", elem.c_str());
325// // regs.push_back(std::regex(elem));
326// // } catch (const std::regex_error &err) {
327// // LOG_RUNTIME("Regular expression for '%s' error '%s'!", elem.c_str(), err.what());
328// // }
329// //
330// // }
331// //
332// // for (size_t i = 0; i < module->size(); i++) {
333// // for (auto &elem : regs) {
334// // // LOG_DEBUG("Test: %s", module->at(i).first.c_str());
335// // if (std::regex_match(module->at(i).first, elem)) {
336// // // LOG_DEBUG("Mask: %s", module->at(i).first.c_str());
337// // ctx->push_front(module->at(i));
338// // count++;
339// // break;
340// // }
341// // }
342// // }
343// // }
344// //
345// // return Obj::CreateValue(count, ObjType::Integer);
346// //
347// // } else {
348// // std::string name = ExtractName(term->GetFullName());
349// // if (isSystemName(name)) {
350// // std::string module = ExtractModuleName(term->GetFullName().c_str());
351// // auto found = ctx->m_runtime->m_modules.find(module);
352// // if (found != ctx->m_runtime->m_modules.end()) {
353// // return CheckSystemField(found->second.get(), name);
354// // } else {
355// // NL_PARSER(term, "Module %s not loaded!", name.c_str());
356// // }
357// // }
358// // }
359// // }
360//
361// NL_PARSER(term, "Term '%s' !!!!!!!!!!!!!!!!!!!!!!!!!", term->GetFullName().c_str());
362//
363// // if (var_name.empty() && isModule(term->GetFullName()) && term->isCall()) {
364// //
365// // }
366//
367// case TermID::LOCAL:
368// case TermID::STATIC:
369// case TermID::NAME:
370// case TermID::ARGS:
371// case TermID::PARENT:
372// case TermID::INT_PLUS:
373// case TermID::INT_MINUS:
374//
375//
376// if (!isModuleName(term->GetFullName()) && (term->isCall() || term->isReturn())) {
377// temp = ctx->GetTerm(term->GetFullName().c_str(), term->isRef());
378//
379// if (!temp) {
380// NL_PARSER(term, "Term '%s' not found!", term->GetFullName().c_str());
381// }
382//
383// args = Obj::CreateDict();
384// ctx->CreateArgs_(args, term, local_vars);
385//
386// if (term->isReturn()) {
387// return result;
388// }
389//
390// result = temp->Call(ctx, args.get());
391// return result;
392// }
393//
394//
395// if (term->GetType()) {
396//
397// result->m_var_type_current = typeFromString(term->GetType()->m_text, ctx ? ctx->m_runtime.get() : nullptr);
398// result->m_var_type_fixed = result->m_var_type_current;
399// result->m_var_is_init = false; // Нельзя считать значение
400//
401// // Check BuildInType
402// has_error = false;
403// typeFromString(term->GetType()->m_text, nullptr, &has_error);
404// if (has_error) {
405// result->m_class_name = term->GetType()->m_text;
406// }
407//
408// return result;
409// }
410//
411// //- **\this** - Текущий объект (**$0**)
412// //- **\sys** - Системный контекст запущенной программы (**\\**)
413// //- **\current** - Текущий модуль (** \$ **)
414// //- **\cmd** - Все аргументы выполняющегося приложения из командной строки (**@\***)
415//
416// if (term->m_text.compare("_") == 0) {
417//
418// result->m_var_type_current = ObjType::None;
419// return result;
420//
421// } else if (term->m_text.compare("$$") == 0) {
422//
423// //- **\parent** - Родительский объект (**$$**)
424//
425// result->m_var_type_current = ObjType::Dictionary;
426// result->m_var_name = "$$";
427//
428// ASSERT(ctx);
429//
430// auto iter = ctx->begin();
431// while (iter != ctx->end()) {
432// if (!iter->second.expired()) {
433// result->push_back(Obj::CreateString(iter->first));
434// iter++;
435// } else {
436// iter = ctx->ListType::erase(iter);
437// }
438// }
439//
440// result->m_var_is_init = true;
441// return result;
442//
443// } else if (term->m_text.compare("$*") == 0) {
444//
445// //- **\args** - Все аргументы функции (**$\***)
446//
447// result->m_var_type_current = ObjType::Dictionary;
448// result->m_var_name = "$*";
449// result->m_var_is_init = true;
450//
451// for (int i = 0; i < term->size(); i++) {
452// if (term->name(i).empty()) {
453// result->push_back(Context::CreateRVal(ctx, (*term)[i].second, local_vars));
454// } else {
455// result->push_back(Context::CreateRVal(ctx, (*term)[i].second, local_vars), term->name(i));
456// }
457// }
458//
459// return result;
460//
461// // } else if (term->m_text.compare("@@") == 0) {
462// //
463// // if (term->m_is_call) {
464// //
465// // Obj args(ctx, term, true, local_vars);
466// //
467// // if (args.size() == 0 || !args.at(0).second->is_string_type()) {
468// // LOG_RUNTIME("Requires a filename in the first argument! %s", args.toString().c_str());
469// // }
470// //
471// // return ctx->ExecFile(args.at(0).second->GetValueAsString().c_str(), &args);
472// //
473// // } else {
474// // return ctx->m_main_module->shared();
475// // }
476// //
477// // } else if (term->m_text.compare("@$") == 0) {
478// //
479// // return ctx->m_terms->shared();
480// //
481// // } else if (term->m_text.compare("@*") == 0) {
482// // if (ctx->m_runtime) {
483// // return ctx->m_runtime->m_args;
484// // } else {
485// // return Obj::CreateType(ObjType::Dictionary, ObjType::Dictionary, true);
486// // }
487// }
488//
489//
490// // if (isModule(term->GetFullName()) && term->m_right) {
491// // bool is_call = term->m_is_call;
492// // std::string name = term->m_text;
493// // TermPtr field = term->m_right;
494// // while (field) {
495// // if (name.compare(term->m_text) == 0) {
496// // name += "::";
497// // } else {
498// // name += ".";
499// // }
500// // name += field->m_text;
501// // term = field;
502// // field = field->m_right;
503// // }
504// // term->m_text = name;
505// // term->m_is_call = is_call;
506// // }
507// //
508// // if (isModule(term->GetFullName())) { // !isVariableName(term->GetFullName())
509// // if (term->isCall()) {
510// // /*
511// // * Операцию с модулем можно конкреттизировать с помощью аргумента
512// // * @module() - загрузка модуля и импорт всех его объектов
513// // * @module("filter*") - загрузка модуля и импорт всех его объектов по заданной маске в переданой строке
514// // * @module("func;ns::*;ns2::*") - несколько масок записываются через точку с запятой
515// // * @module(\true) - убедиться, что модуль загружен. Если модуль не загружен, создать ошибку
516// // * @module(\false) - проверить, загружен ли модуль без его реальной загрузки и вернуть значение
517// // * @module(_) - Выгрузка модуля
518// // *
519// // * @dsl() - Единственный встроенный модуль
520// // */
521// //
522// // // if(term->GetFullName().compare("@dsl")==0) {
523// // // std::string str;
524// // //
525// // // for (int i = 0; i < ::newlang_dsl_size; i++) {
526// // // str += ::newlang_dsl_arr[i];
527// // // str += "\n";
528// // // }
529// // //
530// // // m_macros.clear();
531// // // Parser::ParseAllMacros(str, &m_macros);
532// // //
533// // // result->m_var_type_current = ObjType::Dictionary;
534// // // result->m_var_is_init = true;
535// // //
536// // // for (auto &elem : m_macros) {
537// // // result->push_back(Obj::CreateString(elem.first));
538// // // }
539// // // return result;
540// // // }
541// //
542// // if (term->size() > 1) {
543// // NL_PARSER(term, "Only one argument can be specified for a load module!");
544// // }
545// //
546// // std::vector<std::string> filter;
547// // if (term->size()) {
548// // ASSERT(term->size() == 1);
549// // args = CreateRVal(ctx, term->at(0).second, local_vars);
550// // ASSERT(args);
551// //
552// // auto found = ctx->m_modules.find(term->getText());
553// // if (args->is_bool_type()) {
554// //
555// // if (args->GetValueAsBoolean() && found == ctx->m_modules.end()) {
556// // NL_PARSER(term, "Module %s not loaded!", term->getText().c_str());
557// // }
558// // return found == ctx->m_modules.end() ? Obj::Yes() : Obj::No();
559// //
560// // } else if (args->is_none_type()) {
561// //
562// // result = (found == ctx->m_modules.end() ? Obj::Yes() : Obj::No());
563// // if (found != ctx->m_modules.end()) {
564// // ctx->m_modules.erase(found);
565// // }
566// //
567// // ctx->CleanUp();
568// //
569// // return result;
570// //
571// // } else if (args->is_string_type()) {
572// // filter = SplitString(args->GetValueAsString().c_str(), ";");
573// // }
574// // }
575// //
576// //
577// // if (!ctx->CheckOrLoadModule(term->GetFullName())) {
578// // LOG_RUNTIME("Fail load module %s!", ExtractModuleName(term->GetFullName().c_str()).c_str());
579// // }
580// //
581// //
582// // size_t count = 0;
583// // auto module = ctx->m_modules[term->getText()];
584// //
585// // if (filter.empty()) {
586// // for (size_t i = 0; i < module->size(); i++) {
587// // ctx->push_front(module->at(i));
588// // count++;
589// // }
590// // } else {
591// //
592// // LOG_WARNING("Import of objects by mask does not work correctly!");
593// //
594// // std::vector<std::regex> regs;
595// // for (auto &elem : filter) {
596// // try {
597// // // LOG_DEBUG("From: %s", elem.c_str());
598// //
599// // // if(elem.rfind("::") != 0) {
600// // // elem.insert(0, "::");
601// // // }
602// // // elem.insert(0, term->getText());
603// //
604// // elem = std::regex_replace(elem, std::regex("@."), "@@.");
605// // elem = std::regex_replace(elem, std::regex("@*"), "(.)*");
606// // // LOG_DEBUG("To: %s", elem.c_str());
607// // regs.push_back(std::regex(elem));
608// // } catch (const std::regex_error &err) {
609// // LOG_RUNTIME("Regular expression for '%s' error '%s'!", elem.c_str(), err.what());
610// // }
611// //
612// // }
613// //
614// // for (size_t i = 0; i < module->size(); i++) {
615// // for (auto &elem : regs) {
616// // // LOG_DEBUG("Test: %s", module->at(i).first.c_str());
617// // if (std::regex_match(module->at(i).first, elem)) {
618// // // LOG_DEBUG("Mask: %s", module->at(i).first.c_str());
619// // ctx->push_front(module->at(i));
620// // count++;
621// // break;
622// // }
623// // }
624// // }
625// // }
626// //
627// // return Obj::CreateValue(count, ObjType::Integer);
628// //
629// // } else {
630// // std::string name = ExtractName(term->GetFullName());
631// // if (isSystemName(name)) {
632// // std::string module = ExtractModuleName(term->GetFullName().c_str());
633// // auto found = ctx->m_modules.find(module);
634// // if (found != ctx->m_modules.end()) {
635// // return CheckSystemField(found->second.get(), name);
636// // } else {
637// // NL_PARSER(term, "Module %s not loaded!", name.c_str());
638// // }
639// // }
640// // }
641// // }
642//
643//
644//
645//
646// if (isLocalName(term->m_text.c_str())) {
647// full_name = MakeName(term->m_text);
648// return local_vars->at(full_name).second;
649// } else {
650// result = ctx->GetTerm(term->GetFullName().c_str(), term->isRef());
651//
652// // Типы данных обрабатываются тут, а не в вызовах функций (TermID::CALL)
653// if (!result) {
654// NL_PARSER(term, "Object '%s' not exist!", term->toString().c_str());
655// }
656// if (term->size()) {
657// Obj args(ctx, term, true, local_vars);
658// result = result->Call(ctx, &args);
659// }
660//
661// }
662// if (!result) {
663// // Делать ислкючение или возвращать объект "ошибка" ?????
664// ASSERT(term);
665// LOG_RUNTIME("Term '%s' not found!", term->GetFullName().c_str());
666// }
667//
668// field = term->m_right;
669// if (field && field->getTermID() == TermID::FIELD) {
670// while (field) {
671// if (field->m_is_call) {
672//
673// if (result->m_class_name.empty()) {
674// NL_PARSER(term, "Object '%s' not a class! %s", term->GetFullName().c_str(), result->m_class_name.c_str());
675// }
676//
677// full_name = result->m_class_name;
678// if (isTypeName(full_name)) {
679// full_name = full_name.substr(1);
680// }
681// full_name += "::";
682// full_name += field->getText();
683//
684// temp = ctx->GetTerm(full_name, true);
685// if (!temp) {
686// LOG_RUNTIME("Function '%s' not found!", full_name.c_str());
687// }
688//
689// args = Obj::CreateDict();
690// for (size_t i = 0; i < field->size(); i++) {
691// if (field->name(i).empty()) {
692// args->push_back(CreateRVal(ctx, (*field)[i].second, local_vars));
693// } else {
694// args->push_back(CreateRVal(ctx, (*field)[i].second, local_vars), field->name(i).c_str());
695// }
696// }
697//
698// result = temp->Call(ctx, args.get(), true, result);
699//
700// } else {
701// result = result->at(field->getText()).second;
702// }
703// field = field->m_right;
704// }
705// } else if (field && field->getTermID() == TermID::INDEX) {
706// while (field) {
707// result = result->index_get(MakeIndex(ctx, field, local_vars));
708// field = field->m_right;
709// ASSERT(!field); // Нужно выполнять, а не просто получать значение поля
710// }
711// } else if (field) {
712// LOG_RUNTIME("Not implemented! %s", field->toString().c_str());
713// }
714//
715// return result;
716//
717//
718//
719// case TermID::TYPE:
720//
721// result = ctx->GetTerm(term->GetFullName().c_str(), term->isRef());
722//
723//
724// has_error = false;
725// type = typeFromString(term->GetFullName(), ctx ? ctx->m_runtime.get() : nullptr, &has_error);
726// if (has_error) {
727// LOG_RUNTIME("Type name '%s' undefined!", term->GetFullName().c_str());
728// }
729// ASSERT(result);
730// ASSERT(result->m_var_type_fixed == type);
731//
732// if (result->m_var_type_fixed == ObjType::Class) {
733// //@todo Virtual
734//
735// }
736//
737// // Размерность, если указана
738// result->m_dimensions = Obj::CreateType(ObjType::Dictionary, ObjType::Dictionary, true);
739// for (size_t i = 0; i < term->m_dims.size(); i++) {
740// result->m_dimensions->push_back(CreateRVal(ctx, term->m_dims[i], local_vars, eval_block, int_catch));
741// }
742//
743// args = Obj::CreateDict();
744// for (int64_t i = 0; i < static_cast<int64_t> (term->size()); i++) {
745//
746//
747// if ((*term)[i].second->getTermID() == TermID::FILLING) {
748//
749// // Заполнение значений вызовом функции
750// // :Type(1, 2, 3, ... rand() ... );
751//
752//
753// ASSERT(!(*term)[i].second->m_left);
754// ASSERT((*term)[i].second->m_right);
755//
756//
757// ObjPtr expr = ctx->FindTerm((*term)[i].second->m_right->GetFullName());
758// ASSERT(expr);
759//
760// if (!(*term)[i].second->m_right->isCall()) {
761// LOG_RUNTIME("Operator filling supported function call only!");
762// }
763//
764// if (i + 1 != term->size()) {
765// LOG_RUNTIME("Function filling is supported for the last argument only!");
766// }
767//
768// if (!result->m_dimensions || !result->m_dimensions->size()) {
769// LOG_RUNTIME("Object has no dimensions!");
770// }
771//
772// int64_t full_size = 1;
773// for (int dim_index = 0; dim_index < result->m_dimensions->size(); dim_index++) {
774//
775// if (!(*result->m_dimensions)[dim_index].second->is_integer()) {
776// LOG_RUNTIME("Dimension index for function filling support integer value only!");
777// }
778//
779// full_size *= (*result->m_dimensions)[dim_index].second->GetValueAsInteger();
780// }
781//
782// if (full_size <= 0) {
783// LOG_RUNTIME("Items count error for all dimensions!");
784// }
785//
786//
787// if (expr->size()) {
788// LOG_RUNTIME("Argument in function for filling not implemented!");
789// }
790//
791// for (int64_t dim_index = args->size(); dim_index < full_size; dim_index++) {
792// args->push_back(expr->Call(ctx));
793// }
794//
795// break;
796//
797// } else if ((*term)[i].second->getTermID() == TermID::ELLIPSIS) {
798//
799// if (!term->name(i).empty()) {
800// LOG_RUNTIME("Named ellipsys not implemented!");
801// }
802//
803// if ((*term)[i].second->m_right) {
804//
805// bool named = ((*term)[i].second->m_left && (*term)[i].second->m_left->getTermID() == TermID::ELLIPSIS);
806// ObjPtr exp = CreateRVal(ctx, (*term)[i].second->m_right, eval_block);
807//
808// if (!exp->is_dictionary_type()) {
809// LOG_RUNTIME("Expansion operator applies to dictionary only!");
810// }
811//
812//
813// for (int index = 0; index < exp->size(); index++) {
814// if (named) {
815// args->push_back((*exp)[index].second, exp->name(index).empty() ? "" : exp->name(index));
816// } else {
817// args->push_back((*exp)[index].second);
818// }
819// }
820//
821// continue;
822// }
823// }
824//
825// if (term->name(i).empty()) {
826// args->push_back(CreateRVal(ctx, (*term)[i].second, local_vars));
827// } else {
828// args->push_back(CreateRVal(ctx, (*term)[i].second, local_vars), term->name(i).c_str());
829// }
830//
831// }
832//
833// result = result->Call(ctx, args.get());
834// ASSERT(result);
835//
836// return result;
837//
838//
839// case TermID::TENSOR:
840// case TermID::DICT:
841// result->m_var_type_current = ObjType::Dictionary;
842// ctx->CreateArgs_(result, term, local_vars);
843//
844// result->m_var_is_init = true;
845// if (term->getTermID() == TermID::TENSOR) {
846//
847// if (!term->m_type) {
848// result->m_var_type_fixed = ObjType::None;
849// } else {
850// result->m_var_type_fixed = typeFromString(term->m_type->m_text, ctx ? ctx->m_runtime.get() : nullptr);
851// }
852// type = getSummaryTensorType(result.get(), result->m_var_type_fixed);
853//
854// if (type != ObjType::None) {
855//
856//
857// sizes = TensorShapeFromDict(result.get());
858// result->toType_(type);
859//
860// if (!sizes.empty()) {
861// ASSERT(result->m_tensor->defined());
862// result->m_tensor = result->m_tensor->reshape(sizes);
863// }
864//
865//
866// } else {
867// result->m_var_is_init = false;
868// }
869// // result->resize(0, nullptr, "");
870// result->m_var_type_current = type;
871// } else {
872// result->m_class_name = term->m_class;
873// }
874// return result;
875//
876// case TermID::ARGUMENT:
877//
878// val_int = IndexArg(term);
879// if (val_int < local_vars->size()) {
880// return local_vars->at(val_int).second;
881// }
882// LOG_RUNTIME("Argument '%s' not exist!", term->toString().c_str());
883//
884// case TermID::BLOCK:
885// return CallBlock(ctx, term, local_vars, eval_block, CatchType::CATCH_AUTO, nullptr);
886//
887// case TermID::BLOCK_TRY:
888// case TermID::BLOCK_PLUS:
889// case TermID::BLOCK_MINUS:
890// return CallBlock(ctx, term, local_vars, eval_block, int_catch, nullptr);
891//
892// // case TermID::BLOCK_PLUS:
893// // return CallBlock(ctx, term, local_vars, CatchType::CATCH_PLUS);
894// //
895// // case TermID::BLOCK_MINUS:
896// // return CallBlock(ctx, term, local_vars, CatchType::CATCH_MINUS);
897//
898// case TermID::ELLIPSIS:
899// result->m_var_type_current = ObjType::Ellipsis;
900// result->m_var_type_fixed = ObjType::None;
901// result->m_var_is_init = true;
902// return result;
903//
904// case TermID::RANGE:
905//
906// result->m_var_type_current = ObjType::Dictionary;
907// for (int i = 0; i < term->size(); i++) {
908// ASSERT(!term->name(i).empty());
909// result->push_back(Eval(ctx, (*term)[i].second, local_vars, eval_block), term->name(i).c_str());
910// }
911//
912// if (result->size() == 2) {
913// result->push_back(Obj::CreateValue(1, ObjType::None), "step");
914// }
915//
916// result->m_var_type_current = ObjType::Range;
917// result->m_var_type_fixed = ObjType::Range;
918// result->m_var_is_init = true;
919//
920// return result;
921//
922// case TermID::RATIONAL:
923// return Obj::CreateRational(term->m_text);
924//
925// case TermID::ITERATOR:
926//
927// ASSERT(term->m_left);
928//
929// temp = Eval(ctx, term->m_left, local_vars, eval_block, CatchType::CATCH_AUTO);
930// if (!temp) {
931// LOG_RUNTIME("Term '%s' not found!", term->m_left->GetFullName().c_str());
932// }
933//
934// args = Obj::CreateDict();
935// ctx->CreateArgs_(args, term, local_vars);
936//
937//
938// /*
939// * Создание итератора
940// * ?, ?(), ?("Фильтр"), ?(func), ?(func, args...)
941// *
942// * Перебор элементов итератора
943// * !, !(), !(0), !(3), !(-3)
944// *
945// * dict! и dict!(0) эквивалентны
946// * dict! -> 1, dict! -> 2, dict! -> 3, dict! -> 4, dict! -> 5, dict! -> :IteratorEnd
947// *
948// * Различия отрицательного размера возвращаемого словаря для итератора
949// * dict!(-1) -> (1,), ... dict!(-1) -> (5,), dict!(-1) -> (:IteratorEnd,),
950// * dict!(1) -> (1,), ... dict!(1) -> (5,), dict!(1) -> (,),
951// * dict!(-3) -> (1, 2, 3,), dict!(-3) -> (4, 5, :IteratorEnd,)
952// * dict!(3) -> (1, 2, 3,), dict!(3) -> (4, 5,)
953// *
954// * Операторы ?! и !? эквивалентны и возвращают текущие данные без перемещения указателя итератора.
955// *
956// * Оператор ?? создает итератор и сразу его выполняет, возвращая все значения
957// * в виде элементов словаря, т.е. аналог последовательности ?(LINQ); !(:Int64.__max__);
958// *
959// * Оператор !! - сбрасывает итератор в начальное состояние и возвращает первый элемент
960// */
961//
962// if (term->m_text.compare("?") == 0) {
963// return temp->IteratorMake(args.get());
964// } else if (term->m_text.compare("!") == 0) {
965// ASSERT(!args->size() && "Argument processing not implemented");
966// return temp->IteratorNext(0);
967// } else if (term->m_text.compare("!!") == 0) {
968// ASSERT(!args->size() && "Argument processing not implemented");
969// temp->IteratorReset();
970// return temp->IteratorData();
971// } else if (term->m_text.compare("!?") == 0 || term->m_text.compare("?!") == 0) {
972// return temp->IteratorData();
973// } else if (term->m_text.compare("??") == 0) {
974//
975// val_int = std::numeric_limits<int64_t>::max();
976// if (args->empty() || (args->size() == 1 && args->at(0).second->is_integer())) {
977// result = temp->IteratorMake(nullptr, false);
978// if (args->size()) {
979// val_int = args->at(0).second->GetValueAsInteger();
980// }
981// } else if (args->size() == 1 && args->at(0).second->is_string_type()) {
982// result = temp->IteratorMake(args->at(0).second->GetValueAsString().c_str(), false);
983// } else if (args->size() == 2 && args->at(0).second->is_string_type() && args->at(1).second->is_integer()) {
984// result = temp->IteratorMake(args->at(0).second->GetValueAsString().c_str(), false);
985// val_int = args->at(1).second->GetValueAsInteger();
986// } else {
987// LOG_RUNTIME("Iterator`s args '%s' not allowed!", args->toString().c_str());
988// }
989// return result->IteratorNext(val_int);
990//
991// } else {
992// LOG_RUNTIME("Iterator '%s' not recognized in '%s'!", term->m_text.c_str(), term->toString().c_str());
993// }
994// }
995// LOG_RUNTIME("Fail create type %s from '%s'", newlang::toString(term->getTermID()), term->toString().c_str());
996//
997// return nullptr;
998
999bool RunTime::LoadModuleFromFile(const char *term, bool init) {
1000 ASSERT(term);
1001
1002 // std::string name = ExtractModuleName(term);
1003 // bool is_root = (name.find("\\\\") == 0);
1004 // if (is_root) {
1005 // LOG_WARNING("Load module from root not implemented! '%s'", name.c_str());
1006 // name = name.substr(1); // remove root marker (double back slash) i.e. \\root\dir\module
1007 // }
1008 // std::vector<std::string> split = Macro::SplitString(name.substr(1).c_str(), "\\");
1009 //
1010 // std::string path;
1011 // for (auto &elem : split) {
1012 // if (!path.empty()) {
1013 // path += llvm::sys::path::get_separator();
1014 // }
1015 // path += elem;
1016 // }
1017 //
1018 // path += ".src";
1019 //
1020 //
1021 // llvm::SmallString<1024> search_file;
1022 // if (llvm::sys::path::is_relative(path)) {
1023 // for (int i = 0; i < m_search_dir.size(); i++) {
1024 //
1025 // search_file = m_search_dir[i];
1026 // llvm::sys::path::append(search_file, path);
1027 //
1028 // std::string full_path = search_file.c_str();
1029 // if (llvm::sys::path::is_relative(full_path)) {
1030 // full_path.insert(0, llvm::sys::path::get_separator().str());
1031 // full_path.insert(0, m_work_dir);
1032 // }
1033 //
1034 // LOG_TEST("Check '%s' in file %s", name.c_str(), full_path.c_str());
1035 //
1036 // if (llvm::sys::fs::exists(full_path)) {
1037 // LOG_TEST("Module '%s' load from file '%s'!", term, full_path.c_str());
1038 //
1039 // std::string str = ReadFile(full_path.c_str());
1040 //
1041 // ParserPtr parser = GetParser();
1042 // TermPtr ast = parser->Parse(str);
1043 // Analyze(ast, ast);
1044 // if (!ast->m_module) {
1045 // ast->m_module = Term::Create(parser::token_type::END, TermID::STRCHAR, name.c_str());
1046 // }
1047 // ModulePtr module = std::make_shared<Module>(shared_from_this(), ast);
1048 //
1049 // module->m_md5 = parser->m_file_md5;
1050 // module->m_timestamp = parser->m_timestamp;
1051 // return RegisterModule(module);
1052 // }
1053 // }
1054 // }
1055
1056 LOG_ERROR("Files name"); // '%s' not found!", search_file.c_str());
1057
1058 return false;
1059
1060
1061 // ASSERT(!"Not impelmented");
1062 // std::string name(module_name ? module_name : name_str);
1063 // try {
1064 // m_modules.insert(std::pair<std::string, Module *>(name, new Module(name_str)));
1065 // void * handle = m_modules[name]->GetHandle();
1066 //
1067 // const size_t * func_list_count = static_cast<const size_t *> (dlsym(handle, NEWLANG_PREFIX "_func_list_count"));
1068 // const char ** func_list = static_cast<const char **> (dlsym(handle, NEWLANG_PREFIX "_func_list"));
1069 // m_modules[name]->m_source = static_cast<const char **> (dlsym(handle, NEWLANG_PREFIX "_module_source"));
1070 // m_modules[name]->m_main = reinterpret_cast<FunctionType*> (dlsym(handle, NEWLANG_PREFIX "_main_module_func"));
1071 //
1072 // //@todo INIT MODULE
1073 //
1074 // ObjPtr func;
1075 // if(func_list_count && func_list) {
1076 // TermPtr proto;
1077 // Parser parser(proto);
1078 // for (size_t i = 0; i < (*func_list_count); i++) {
1079 // LOG_DEBUG("Load '%s' form module '%s'.", func_list[i], name_str);
1080 //
1081 // std::string arg_name = NEWLANG_PREFIX "_";
1082 // arg_name += func_list[i];
1083 // arg_name += "_text";
1084 //
1085 // const char ** func_proto = static_cast<const char **> (dlsym(handle, arg_name.c_str()));
1086 // parser.Parse(*func_proto);
1087 // ObjType type;
1088 // switch(proto->getTermID()) {
1089 // case TermID::SIMPLE:
1090 // case TermID::PURE_USE:
1091 // type = ObjType::PUREFUNC;
1092 // break;
1093 // case TermID::FUNCTION:
1094 // type = ObjType::FUNCTION;
1095 // break;
1096 // default:
1097 // LOG_RUNTIME("Function type '%s' unknown '%s'", newlang::toString(proto->getTermID()), proto->toString().c_str());
1098 // }
1099 // func = Obj::CreateFunc(ctx, proto->m_left, type, func_list[i]);
1100 // func->m_func_ptr = reinterpret_cast<void *> (dlsym(handle, MangleName(func_list[i]).c_str()));
1101 // func->m_func_source = proto;
1102 //
1103 // //@todo call init module
1104 // if(!(func->m_func_ptr && ctx->RegisterObject(func))) {
1105 // LOG_ERROR("Fail load '%s' form module '%s'.", func_list[i], name_str);
1106 // } else {
1107 // m_modules[name]->Funcs()[func_list[i]] = func;
1108 // }
1109 // }
1110 //
1111 // return true;
1112 // }
1113 // LOG_WARNING("In module '%s' functions not found!", name_str);
1114 // return true;
1115 // } catch (std::runtime_error &e) {
1116 //
1117 // LOG_ERROR("%s", e.what());
1118 // }
1119}
1120
1121bool RunTime::UnLoadModule(const char *name_str, bool deinit) {
1122 bool result = false;
1123 bool is_error = false;
1124 // auto it = m_modules.begin();
1125 // while(it != m_modules.end()) {
1126 // if(name == nullptr || it->first.compare(name) == 0) {
1127 //
1128 // for (auto &elem : it->second->Funcs()) {
1129 // if(!ctx->RemoveObject(elem.first.c_str())) {
1130 // LOG_ERROR("Fail unregister func '%s' from module '%s'.", elem.first.c_str(), it->first.c_str());
1131 // is_error = true;
1132 // }
1133 // }
1134 // LOG_DEBUG("UnLoad module '%s'.", it->first.c_str());
1135 //
1136 // //@todo call deinit module
1137 // delete it->second;
1138 // it = m_modules.erase(it);
1139 // result = true;
1140 // } else {
1141 //
1142 // it++;
1143 // }
1144 // }
1145 return result && !is_error;
1146}
1147
1148//bool NewLang::SaveContext(const char *name) {
1149// std::ofstream file;
1150// file.open(name, std::ios::trunc);
1151// file << "#!/bin/nlc --exec\n";
1152// file << "// Global user terms\n\n";
1153// std::string temp;
1154// std::string str;
1155// for (auto &elem : * this) {
1156// temp.swap(elem.second->m_var_name);
1157//
1158// str = elem.second->toString();
1159// if(str.find("&=") == 0) {
1160// str = str.substr(2);
1161// }
1162// if(str.find("&") == 0) {
1163// str = str.substr(1);
1164// }
1165//
1166// file << "@[]." << temp << " := " << str << ";\n";
1167//
1168// temp.swap(elem.second->m_var_name);
1169// }
1170//
1171// for (auto &elem : m_global_funcs) {
1172// if((elem.second->m_func_source) && ((elem.second->m_func_source)->getTermID() == TermID::SIMPLE || (elem.second->m_func_source)->getTermID() == TermID::PURE_USE)) {
1173// TermPtr term = (elem.second->m_func_source)->m_right;
1174// if(!CheckClearFunction(term)) {
1175// LOG_DEBUG("The function '%s' cannot be saved because it is not clean!", elem.second->m_func_source->m_left->toString().c_str());
1176// }
1177// file << term->toString() << ";\n";
1178// }
1179// }
1180// file.close();
1181//
1182// return true;
1183//}
1184//
1185//bool NewLang::LoadContext(Context *ctx, const char *name) {
1186//
1187// return RunTime::Instance()->ExecModule(name, ReplaceFileExt(name, ".ctx", ".nlm").c_str(), true, ctx)->getType() != ObjType::Error;
1188//}
1189
1190ObjPtr RunTime::ExecModule(const char *mod, const char *output, bool cached, Context * ctx) {
1191 /*std::string source = ReadFile(mod);
1192 Obj args;
1193 if(cached && access(output, F_OK) != -1 && LoadModule(output, true)) {
1194 if(m_modules[output]->m_source && *(m_modules[output]->m_source) && source.compare(*(m_modules[output]->m_source)) == 0) {
1195 LOG_DEBUG("Load cached module '%s'", output);
1196 return m_modules[output]->Main(ctx, args);
1197 }
1198 LOG_DEBUG("Disabled cached module '%s'\nsource:\n%s\nmodule:\n%s", output, source.c_str(), m_modules[output]->m_source ? *(m_modules[output]->m_source) : "nullptr");
1199 UnLoadModule(ctx, output);
1200 }
1201 if(NewLang::CompileModule(module, output) && LoadModule(output)) {
1202 return m_modules[output]->Main(ctx, args);
1203 }*/
1204 LOG_RUNTIME("Fail compile module '%s' form file '%s'.", output, mod);
1205 return nullptr;
1206}
1207
1208RuntimePtr RunTime::Init(int argc, const char** argv, const char** penv) {
1209 // RuntimePtr rt = std::make_shared<RunTime>();
1210 // if (!rt->ParseArgs(argc, argv)) {
1211 // LOG_RUNTIME("Fail parse args!");
1212 // }
1213 //
1214 // if (rt->m_load_runtime) {
1215 // VERIFY(rt->RegisterBuildin(std::make_shared<newlang::runtime::Base>(rt)));
1216 // VERIFY(rt->RegisterBuildin(std::make_shared<newlang::runtime::System>(rt)));
1217 // }
1218
1219 return RunTime::Init(MakeMainArgs(argc, argv, penv));
1220}
1221
1223 return std::make_shared<RunTime>(args);
1224}
1225
1227
1228
1229 //__STAT_RUNTIME_UNITTEST__()
1230
1231 // VERIFY(RegisterSystemBuildin("::__compare__(obj1, obj2):Int8"));
1232 // VERIFY(RegisterSystemBuildin("::__equals__(obj1, obj2):Bool"));
1233 // __eq__ , __ne__ , __lt__ , __gt__ , __ge__ , __le__
1234 //__cmp__
1235 // == __eq__()
1236 // != __ne__()
1237 // > __gt__()
1238 // >= __ge__()
1239 // < __lt__()
1240 // <= __le__()
1241 // __module__, __name__, __qualname__, __doc__ and __annotations__) and have a new __wrapped__
1242
1243 // __getattr__ __getattribute__ __setattr__ __delattr__
1244 // __get__(self, instance, owner=None) __set__
1245
1246 // __call__(self[, args...])
1247 // __getitem__(), __setitem__(), __delitem__(),
1248 // __contains__
1249
1251
1252
1253 if (!ParseArgs(args)) {
1254 LOG_RUNTIME("Fail parse args!");
1255 }
1256 if (m_load_runtime) {
1257
1258 // nlc_prinft_sub_
1259 // LLVMAddSymbol("nlc_prinft_sub_", (void *) &nlc_prinft_sub_);
1260 VERIFY(RegisterSystemFunc("::print(format:FmtChar, ... ):Int32 ::= %nlc_prinft_sub_ ..."));
1261 // VERIFY(RegisterSystemFunc("::__snprintf__(buffer:Pointer, size:Int32, format:FmtChar, ... ):Int32 ::= %snprintf ..."));
1262
1263 VERIFY(RegisterSystemFunc("::srand(init:Int32):None ::= %srand ..."));
1264 VERIFY(RegisterSystemFunc("::rand():Int32 ::= %rand ..."));
1265
1266 VERIFY(RegisterSystemFunc("::sleep(init:DWord):DWord ::= %sleep ..."));
1267 VERIFY(RegisterSystemFunc("::usleep(init:DWord64):Int32 ::= %usleep ..."));
1268
1269 // VERIFY(RegisterSystemFunc("::microsec():Int64 ::= %microsec ..."));
1270 VERIFY(RegisterBuildinFunc("::len(obj):Int64", (void *) &runtime::Base::__len__));
1271 VERIFY(RegisterBuildinFunc("::size(obj):Int64", (void *) &runtime::Base::__len__));
1272
1273 VERIFY(RegisterBuildinFunc("::Base::__timeit__(...):Int64", (void *) &runtime::Base::__timeit__));
1274
1275 //#define REGISTER_BUILDIN(proto, function)
1276
1277 VERIFY(RegisterBuildinFunc("::Base::__assert_abort__(...):None", (void *) &runtime::Base::__assert_abort__));
1278
1279 VERIFY(RegisterBuildinFunc(":Thread::this_id():Integer", (void *) &runtime::Base::__thread_this_id__));
1280 VERIFY(RegisterBuildinFunc(":Thread::hardware_concurrency():Integer", (void *) &runtime::Base::__thread_hardware_concurrency__));
1281
1282 VERIFY(RegisterBuildinFunc(":Thread::get_id():Integer", (void *) &runtime::Base::__thread_get_id__));
1283 VERIFY(RegisterBuildinFunc(":Thread::start():Integer", (void *) &runtime::Base::__thread_start__));
1284 VERIFY(RegisterBuildinFunc(":Thread::join():None", (void *) &runtime::Base::__thread_join__));
1285 VERIFY(RegisterBuildinFunc(":Thread::joinable():Boolean", (void *) &runtime::Base::__thread_joinable__));
1286
1287
1288 // VERIFY(RegisterSystemBuildin("::rand():Int32 ::= %rand ..."));
1289 // VERIFY(rt->RegisterBuildin(std::make_shared<newlang::runtime::Base>(rt)));
1290 // VERIFY(rt->RegisterBuildin(std::make_shared<newlang::runtime::System>(rt)));
1291 }
1292 // return rt;
1293}
1294
1295bool RunTime::RegisterBuildinFunc(std::string text, void * func) {
1296 text += " := {}";
1297 TermPtr proto = ParseBuildin(text)->m_left;
1298 // proto->m_obj = CreateFunction(proto, func);
1299// m_buildin_pair[proto->m_normalized] = VariablePair::Create(proto, CreateFunction(proto, func));
1300 return !!RegisterObject(true, proto->m_normalized.c_str(), proto, CreateFunction(proto, func));
1301}
1302
1303TermPtr RunTime::ParseBuildin(const std::string_view src) {
1304 Parser p;
1305 TermPtr ast = p.Parse(src.begin());
1306
1307 AstAnalysis analysis(*this, m_diag.get());
1308
1310 NameLookupStack stack(*this, external);
1311
1312 if (!analysis.Analyze(ast, &stack)) {
1313 LOG_RUNTIME("Make AST fail!");
1314 }
1315 return ast;
1316}
1317
1318bool RunTime::ExpandFileName(std::string &filename) {
1319 if (std::filesystem::exists(filename)) {
1320 filename = std::filesystem::absolute(filename);
1321 return true;
1322 }
1323 return false;
1324}
1325
1326// Для теста
1327
1328extern "C" char convert(char c) {
1329 if (c == 'A') return 'C';
1330 if (c == 'C') return 'G';
1331 if (c == 'G') return 'T';
1332 if (c == 'T') return 'A';
1333 return ' ';
1334}
1335
1339
1342 VERIFY(RegisterBuildinType(ObjType::Tensor,{":Arithmetic"}));
1343
1355
1362
1366
1372
1375 VERIFY(RegisterBuildinType(ObjType::Class,{":Dictionary", ":Interface"}));
1376
1377 VERIFY(RegisterBuildinType(ObjType::Pointer,{":Any"})); // Указатели на машиннозависимую реализауию объектов
1378
1379 VERIFY(RegisterBuildinType(ObjType::Plain,{":Pointer"})); // Могут быть представленые в одном блоке памяти
1380 VERIFY(RegisterBuildinType(ObjType::Enum,{":Plain", ":Integer"}));
1381 VERIFY(RegisterBuildinType(ObjType::Union,{":Plain", ":Dictionary"}));
1382 VERIFY(RegisterBuildinType(ObjType::Struct,{":Plain", ":Class"}));
1383
1384
1385 VERIFY(RegisterBuildinType(ObjType::Eval,{":Any"})); // Может быть выполнен
1387 VERIFY(RegisterBuildinType(ObjType::NativeFunc,{":Function", ":Pointer"}));
1388
1392
1395
1397
1399 // VERIFY(RegisterBuildinType(ObjType::Return,{":Any"}));
1400 //
1401 // VERIFY(RegisterBuildinType(ObjType::Error,{":Return"}));
1402 // VERIFY(RegisterBuildinType(ObjType::Break,{":Return"})); // Синонимы прерывания последовательности выполнения для совместимости
1403 // VERIFY(RegisterBuildinType(ObjType::Continue,{":Return"})); // со стндартными алгоритмическими приемами (синтаксический сахар)
1404 //
1405 //
1406 // VERIFY(RegisterBuildinType(ObjType::ErrorParser,{":Error"}));
1407 // VERIFY(RegisterBuildinType(ObjType::ErrorRunTime,{":Error"}));
1408 // VERIFY(RegisterBuildinType(ObjType::ErrorSignal,{":Error"}));
1409
1410}
1411
1412bool RunTime::RegisterSystemFunc(const char *source) {
1413
1414 TermPtr ast = ParseBuildin(source);
1415 TermPtr term = ast->m_left;
1416 ASSERT(term);
1417 ASSERT(!term->m_normalized.empty());
1418
1419 ASSERT(ast->m_right);
1420 ASSERT(ast->m_right->m_id == TermID::NATIVE);
1421
1422 // Variable data(CreateNative(term, nullptr, false, ast->m_right->m_text.substr(1).c_str()));
1423
1424// auto found = m_buildin_pair.find(term->m_normalized);
1425// if (found != m_buildin_pair.end()) {
1426// LOG_ERROR("Fail register buildin name '%s'", term->m_normalized.c_str());
1427// return false;
1428// }
1429
1430// VariablePairPtr temp = VariablePair::Create(term, CreateNative(term, nullptr, false, ast->m_right->m_text.substr(1).c_str()));
1431// m_buildin_pair[term->m_normalized] = temp;
1432
1433 // auto last = m_buildin_vars.insert({term->m_normalized, Variable(CreateNative(term, nullptr, false, ast->m_right->m_text.substr(1).c_str()))});
1434 // ASSERT(last.second && last.first != m_buildin_vars.end());
1435 return RegisterObject(true, term->m_normalized, term, CreateNative(term, nullptr, false, ast->m_right->m_text.substr(1).c_str()));
1436}
1437
1438bool RunTime::RegisterBuildinType(ObjType type, std::vector<std::string> parents) {
1439
1440 std::string type_name(toString(type));
1441
1442 std::string func_name = NormalizeName(type_name.substr(1));
1443 func_name.insert(0, "::");
1444 type_name = NormalizeName(type_name);
1445
1446// auto base = m_buildin_pair.find(type_name);
1447// if (base != m_buildin_pair.end()) {
1448// return false;
1449// }
1450
1452 ASSERT(result->m_var_type_fixed == type);
1453 ASSERT(result->m_var_type_current == ObjType::Type);
1454 ASSERT(!type_name.empty() && result->m_class_name.compare(type_name) == 0);
1455 ASSERT(result->m_class_parents.empty());
1456
1457 ASSERT(std::holds_alternative<void *>(result->m_var));
1458 ASSERT(std::get<void *>(result->m_var));
1459
1460 // result->m_var = (void *) &Context::__make_type__;
1461
1462 for (auto &parent : parents) {
1463 auto iter = find(NormalizeName(parent));
1464 if (iter == end()) {
1465 LOG_DEBUG("Parent type '%s' as '%s' not found!", parent.c_str(), NormalizeName(parent).c_str());
1466 return false;
1467 }
1468 for (auto &elem : result->m_class_parents) {
1469 ASSERT(elem);
1470 elem->m_class_name = newlang::NormalizeName(elem->m_class_name);
1471 if (!elem->m_class_name.empty() && elem->m_class_name.compare(NormalizeName(parent)) == 0) {
1472 LOG_DEBUG("The type '%s' already exists in the parents of '%s'!", parent.c_str(), type_name.c_str());
1473 return false;
1474 }
1475 }
1476 ASSERT(iter->first.compare(NormalizeName(parent)) == 0);
1477 result->m_class_parents.push_back(iter->second.var.GetValueAsObject());
1478 }
1479
1480 TermPtr type_term = Term::Create(TermID::FUNCTION, type_name.c_str(), parser::token_type::NAME);
1481 type_term->m_normalized = type_name;
1482
1483// m_buildin[type_name] = {type_term, result};
1484
1485// VariablePairPtr temp = VariablePair::Create(type_term, result);
1486// m_buildin_pair[type_name] = temp;
1487
1488 if (type_name.compare("None:::") == 0) {
1489 VERIFY(RegisterObject(true, "_", type_term, result));
1490 }
1491 return RegisterObject(true, type_name.c_str(), type_term, result) && RegisterObject(true, type_name.insert(0, "::").c_str(), type_term, result);
1492}
1493
1494ObjPtr RunTime::GetTypeFromString(const std::string_view type, bool *has_error) {
1495 if (type.empty()) {
1496 if (has_error) {
1497 *has_error = true;
1498 return Obj::CreateNone();
1499 }
1500 LOG_RUNTIME("Type name '%s' not found!", type.begin());
1501 }
1502
1503 auto result_types = find(NormalizeName(type));
1504 if (result_types != end()) {
1505 return result_types->second.var.GetValueAsObject();
1506 }
1507
1508 // TermPtr found = NameGet(type.begin(), false);
1509 // if (found) {
1510 // return found->m_obj;
1511 // }
1512
1513 // auto result_find = find(type);
1514 // if (result_find != end()) {
1515 // return result_find->second.lock();
1516 // }
1517
1518 if (has_error) {
1519 *has_error = true;
1520 return nullptr;
1521 }
1522 LOG_RUNTIME("Type name '%s' not found!", type.begin());
1523}
1524
1525ObjType RunTime::BaseTypeFromString(RunTime * rt, const std::string_view type_name, bool *has_error) {
1526
1527 bool local_has_error = false;
1528
1529 ObjType type = GetBaseTypeFromString(type_name, &local_has_error);
1530
1531 if (!local_has_error) {
1532 return type;
1533 }
1534
1535 if (has_error) {
1536 *has_error = local_has_error;
1537 }
1538
1539 if (local_has_error && !rt) {
1540 LOG_RUNTIME("Type name '%s' is not calculated statically!", type_name.begin());
1541 }
1542
1543 ObjPtr obj_type = rt->GetTypeFromString(type_name, has_error);
1544
1545 if (obj_type == nullptr) {
1546 if (has_error) {
1547 *has_error = true;
1548 return ObjType::None;
1549 }
1550 LOG_RUNTIME("Type name '%s' not found!", type_name.begin());
1551 }
1552 return obj_type->m_var_type_fixed;
1553}
1554
1555//bool RunTime::RegisterBuildin(BuildinPtr module) {
1556//
1557// ASSERT(module);
1558// if (RegisterModule(module)) {
1560// }
1561// return false;
1562//}
1563
1564//bool RunTime::RegisterModule(ModulePtr module) {
1565// ASSERT(module);
1566//
1567// // if (module->m_var_type_current != ObjType::Module) {
1568// // LOG_RUNTIME("Object not a module '%s'!", module->toString().c_str());
1569// // return false;
1570// // }
1571//
1572// std::string name(module->m_file);
1573// // LOG_DEBUG("Load '%s'", name.c_str());
1574// // name.append(module->m_class_name);
1575//
1576// if (m_modules.find(name) != m_modules.end()) {
1577// LOG_ERROR("Module name '%s' already register!", name.c_str());
1578// return false;
1579// }
1580//
1581// for (auto &obj : *module) {
1582// if (isStaticName(obj.first)) {
1583// if (!NameRegister(true, obj.first.c_str(), obj.second.item, obj.second.obj)) {
1584// LOG_ERROR("Fail register object '%s'!", obj.first.c_str());
1585// return false;
1586// }
1587// }
1588// }
1589//
1590// m_modules[name] = module;
1591//
1592// return true;
1593//}
1594
1595std::vector<std::wstring> RunTime::SelectPredict(std::string start, size_t overage_count) {
1596
1597 std::vector<std::wstring> result;
1598
1599 bool find_local = false;
1600 bool find_global = false;
1601 bool find_types = false;
1602 bool find_macro = false;
1603
1604 std::string prefix;
1605
1606 if (isModuleName(start)) {
1607 prefix = start[0];
1608 start = start.substr(1);
1609 find_global = true;
1610 } else if (isLocalName(start)) {
1611 prefix = start[0];
1612 start = start.substr(1);
1613 find_local = true;
1614 } else if (isMacroName(start)) {
1615 find_macro = true;
1616 } else if (isTypeName(start)) {
1617 find_types = true;
1618 } else {
1619 find_local = true;
1620 find_global = true;
1621 find_types = true;
1622 find_macro = true;
1623 }
1624
1625
1626 if (find_macro) {
1627 for (auto &elem : * this) {
1628 if (pred_compare(start, elem.first)) {
1629 result.push_back(utf8_decode(prefix + elem.first));
1630 if (result.size() > overage_count + 1) {
1631 break;
1632 }
1633 }
1634 }
1635 }
1636
1637 if (find_local) {
1638 // for (int i = 0; i < size(); i++) {
1639 // if (pred_compare(start, at(i).first)) {
1640 // ObjPtr object = at(i).second.lock();
1641 // if (object && object->is_function_type()) {
1642 // result.push_back(utf8_decode(prefix + at(i).first) + L"(");
1643 // } else if (object) {
1644 // result.push_back(utf8_decode(prefix + at(i).first));
1645 // }
1646 // if (result.size() > overage_count + 1) {
1647 // break;
1648 // }
1649 // }
1650 // }
1651 }
1652
1653 if (find_global) {
1654 // for (int i = 0; i < m_terms->size(); i++) {
1655 // if (pred_compare(start, m_terms->at(i).first)) {
1656 // if (m_terms->at(i).second->is_function_type()) {
1657 // result.push_back(utf8_decode(prefix + m_terms->at(i).first) + L"(");
1658 // } else {
1659 // result.push_back(utf8_decode(prefix + m_terms->at(i).first));
1660 // }
1661 // if (result.size() > overage_count + 1) {
1662 // break;
1663 // }
1664 // }
1665 // }
1666
1667 // for (auto &elem : m_funcs) {
1668 //
1669 // if (pred_compare(start, elem.first)) {
1670 // result.push_back(utf8_decode(prefix + elem.first) + L"(");
1671 // if (result.size() > overage_count + 1) {
1672 // break;
1673 // }
1674 // }
1675 // }
1676 }
1677
1678 if (find_types) {
1679 for (auto &elem : * this) {
1680 if (pred_compare(start, elem.first)) {
1681 result.push_back(utf8_decode(elem.first));
1682 if (result.size() > overage_count + 1) {
1683 break;
1684 }
1685 }
1686 }
1687 }
1688 return result;
1689
1690}
1691
1692//bool RunTime::RegisterSystemObj(ObjPtr obj) {
1693//
1694// ASSERT(obj);
1695//
1696// // if (IsModule(obj)) {
1697// //
1698// // // 11111111111111
1699// // //
1700// // }
1701//
1702// LOG_RUNTIME("RegisterSystemObj '%s' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!", obj->toString().c_str());
1703//
1704// // ASSERT(obj->m_prototype);
1705//
1706// // std::string obj_name = obj->m_prototype->getText();
1707// std::string obj_name = obj->m_class_name; //m_prototype->getText();
1708// auto found = find(obj_name);
1709// if (found != end()) {
1710// LOG_ERROR("Object name '%s' already exist!", obj_name.c_str());
1711// return false;
1712// }
1713//
1714// m_sys_obj.push_back(obj);
1715// // push_back(std::make_shared<GlobNameInfo>(obj->m_prototype, obj), obj_name);
1716//
1717// // std::string name;
1718// // for (auto &elem : *obj) {
1719// // name = obj_name;
1720// // name.append("::");
1721// // name.append(elem.second->m_prototype->getText());
1722// //
1723// // // LOG_DEBUG("%s -> %s", name.c_str(), elem.second->m_prototype->toString().c_str());
1724// //
1725// // auto found = find(name);
1726// // if (found != end()) {
1727// // LOG_ERROR("Object name '%s' already exist!", name.c_str());
1728// // return false;
1729// // }
1730// //
1731// // push_back(std::make_shared<GlobNameInfo>(elem.second->m_prototype, elem.second), name);
1732// //
1733// //
1734// // }
1735//
1736//
1737// return true;
1738//}
1739
1742 *const_cast<TermPtr *> (&result->m_prototype) = proto;
1743 result->m_sequence = block;
1744 result->m_sequence->m_namespace = Term::CreateName(proto->m_text, TermID::NAMESPACE);
1745 return result;
1746}
1747
1750 *const_cast<TermPtr *> (&result->m_prototype) = proto;
1751 result->m_var = addr;
1752 return result;
1753}
1754
1755ObjPtr RunTime::CreateNative(const char *proto, const char *module, bool lazzy, const char *mangle_name) {
1756 TermPtr term;
1757 try {
1758 // Термин или термин + тип парсятся без ошибок
1759 Parser p;
1760 term = p.Parse(proto); //m_named);
1761 } catch (std::exception &) {
1762 try {
1763 std::string func(proto);
1764 func += ":={}";
1765 Parser p2;
1766 term = p2.Parse(func)->m_left; //m_named)->m_left;
1767 } catch (std::exception &e) {
1768
1769 LOG_RUNTIME("Fail parsing prototype '%s'!", e.what());
1770 }
1771 }
1772 return CreateNative(term, module, lazzy, mangle_name);
1773}
1774
1775ObjPtr RunTime::CreateNative(TermPtr proto, const char *module, bool lazzy, const char *mangle_name) {
1776 ASSERT(!lazzy);
1777
1778 void *addr = GetNativeAddress(nullptr, mangle_name ? mangle_name : proto->m_text.c_str());
1779 if (!addr) {
1780 NL_CHECK(addr, "Error getting address '%s' from '%s'!", proto->toString().c_str(), module);
1781 }
1782
1783 return CreateNative(proto, addr);
1784}
1785
1787
1788 NL_CHECK(proto, "Fail prototype native function!");
1789 // NL_CHECK((module == nullptr || (module && *module == '\0')) || m_runtime,
1790 // "You cannot load a module '%s' without access to the runtime context!", module);
1791
1792 ObjPtr result;
1793 ObjType type = ObjType::None;
1794 if (proto->isCall()) {
1795 type = ObjType::NativeFunc;
1796
1797 ObjType type_test;
1798 for (int i = 0; i < proto->size(); i++) {
1799
1800 TermPtr proto_arg = (*proto)[i].second;
1801 // if (!proto->name(i).empty()) {
1802 // NL_PARSER((*proto)[i].second, "Default values '%s' are not supported!", proto->name(i).c_str());
1803 // }
1804 //
1805 // if (isLocalAnyName((*proto)[i].second->m_text.c_str())) {
1806 // NL_PARSER((*proto)[i].second, "Argument name expected '%s'!", (*proto)[i].second->m_text.c_str());
1807 // }
1808
1809 if (proto_arg->getTermID() == TermID::ELLIPSIS) {
1810 if (i + 1 != proto->size()) {
1811 NL_PARSER(proto_arg, "Ellipsys must end of argument!");
1812 }
1813 } else {
1814 if (!proto_arg->m_type) {
1815 NL_PARSER(proto_arg, "Argument type must be specified!");
1816 }
1817
1818 type_test = GetBaseTypeFromString(proto_arg->m_type->m_text.c_str());
1819 if (!isNativeType(type_test)) {
1820 NL_PARSER(proto_arg->GetType(), "Argument must be machine type! Creating a variable with type '%s' is not supported!", proto_arg->m_type->m_text.c_str());
1821 }
1822 }
1823 }
1824
1825
1826 } else {
1827 if (!proto->m_type) {
1828 // NL_PARSER(proto, "Cannot create native variable without specifying the type!");
1829 type = ObjType::Pointer;
1830 } else {
1831 type = GetBaseTypeFromString(proto->m_type->m_text); //, this);
1832 if (!isNativeType(type)) {
1833 NL_PARSER(proto, "Creating a variable with type '%s' is not supported!", proto->m_type->m_text.c_str());
1834 }
1835 }
1836 }
1837
1838 result = Obj::CreateType(type);
1839 result->m_var_type_fixed = ObjType::None; // Тип определен и не может измениться в дальнейшем
1840
1841 *const_cast<TermPtr *> (&result->m_prototype) = proto;
1842 // result->m_func_abi = abi;
1843
1844 // if (mangle_name) {
1845 // result->m_func_mangle_name = mangle_name;
1846 // }
1847 // if (module) {
1848 // result->m_module_name = module;
1849 // }
1850 void * ptr = nullptr;
1851 // if (lazzy) {
1852 // result->m_var = static_cast<void *> (nullptr);
1853 // } else {
1854 ASSERT(std::holds_alternative<std::monostate>(result->m_var));
1855
1856 ptr = addr; //GetNativeAddr(result->m_func_mangle_name.empty() ? proto->m_text.c_str() : result->m_func_mangle_name.c_str(), module);
1857
1858 switch (type) {
1859 case ObjType::Bool:
1860 result->m_var = static_cast<bool *> (ptr);
1861 result->m_var_is_init = true;
1862 break;
1863 case ObjType::Int8:
1864 case ObjType::Char:
1865 case ObjType::Byte:
1866 result->m_var = static_cast<int8_t *> (ptr);
1867 result->m_var_is_init = true;
1868 break;
1869 case ObjType::Int16:
1870 case ObjType::Word:
1871 result->m_var = static_cast<int16_t *> (ptr);
1872 result->m_var_is_init = true;
1873 break;
1874 case ObjType::Int32:
1875 case ObjType::DWord:
1876 result->m_var = static_cast<int32_t *> (ptr);
1877 result->m_var_is_init = true;
1878 break;
1879 case ObjType::Int64:
1880 case ObjType::DWord64:
1881 result->m_var = static_cast<int64_t *> (ptr);
1882 result->m_var_is_init = true;
1883 break;
1884 case ObjType::Float32:
1885 case ObjType::Single:
1886 result->m_var = static_cast<float *> (ptr);
1887 result->m_var_is_init = true;
1888 break;
1889 case ObjType::Float64:
1890 case ObjType::Double:
1891 result->m_var = static_cast<double *> (ptr);
1892 result->m_var_is_init = true;
1893 break;
1894
1896 default:
1897 result->m_var = ptr;
1898 // }
1899 // result->m_var = m_runtime->GetNativeAddr(
1900 // result->m_func_mangle_name.empty() ? proto->m_text.c_str() : result->m_func_mangle_name.c_str(), module);
1901
1902 if (result->is_function_type() || type == ObjType::Pointer) {
1903 NL_CHECK(std::get<void *>(result->m_var), "Error getting address '%s'!", proto->toString().c_str());
1904 } else if (ptr && result->is_tensor_type()) {
1905 // result->m_tensor = torch::from_blob(std::get<void *>(result->m_var),{
1906 // }, toTorchType(type));
1907 result->m_var_is_init = true;
1908 } else {
1909 NL_PARSER(proto, "Fail CreateNative object");
1910 }
1911 }
1912 result->m_var_is_init = true;
1913
1914 return result;
1915}
1916
1917std::string newlang::GetFileExt(const char *str) {
1918 std::string filename(str);
1919 std::string::size_type idx = filename.rfind('.');
1920 if (idx != std::string::npos) {
1921
1922 return filename.substr(idx);
1923 }
1924 return std::string("");
1925}
1926
1927std::string newlang::AddDefaultFileExt(const char *str, const char *ext_default) {
1928 std::string filename(str);
1929 std::string file_ext = GetFileExt(str);
1930 if (file_ext.empty() && !filename.empty() && filename.compare(".") != 0) {
1931
1932 filename.append(ext_default);
1933 }
1934 return filename;
1935}
1936
1937std::string newlang::ReplaceFileExt(const char *str, const char *ext_old, const char *ext_new) {
1938 std::string filename(str);
1939 std::string file_ext = GetFileExt(str);
1940 if (file_ext.compare(ext_old) == 0) {
1941 filename = filename.substr(0, filename.length() - file_ext.length());
1942 }
1943 file_ext = GetFileExt(filename.c_str());
1944 if (file_ext.compare(".") != 0 && file_ext.compare(ext_new) != 0 && !filename.empty() &&
1945 filename.compare(".") != 0) {
1946
1947 filename.append(ext_new);
1948 }
1949 return filename;
1950}
1951
1952std::string newlang::ReadFile(const char *fileName) {
1953 std::ifstream f(fileName);
1954 std::stringstream ss;
1955 ss << f.rdbuf();
1956 // if(f.fail()) {
1957 // std::cout << "Current path is " << std::filesystem::current_path() << '\n';
1958 // std::cerr << strerror(errno);
1959 // }
1960 f.close();
1961
1962 return ss.str();
1963}
1964
1966 ASSERT(isModuleName(term->m_text));
1967 ASSERT(term->isCall());
1968
1969
1970 ASSERT(isModuleName(term->m_text));
1971 std::string name = ExtractModuleName(term->m_text.c_str());
1972 for (auto &elem : m_module_loader) {
1973 if (elem.compare(name) == 0) {
1974 NL_PARSER(term, "Load module '%s' recursion!", term->m_text.c_str());
1975 }
1976 }
1977 m_module_loader.push_back(name);
1978
1979
1980
1981
1982 // if (term->size()) {
1983 // NL_PARSER(term->at(0).second, "Load module from options not implemented!");
1984 // }
1985 //
1986 // if(CheckLoadModule(term)){
1987 // NL_PARSER(term->at(0).second, "Load module from options not implemented!");
1988 // }
1989 //
1990 // std::string name = ExtractModuleName(term->m_text.c_str());
1991 // if (m_modules.find(name) == m_modules.end()) {
1992 //
1993 // ModulePtr module = LoadModuleFromFile(str.c_str(), true);
1994 // if (module) {
1995 // m_modules[name] = std::move(module);
1996 // }
1997 // }
1998 // return m_modules.find(name) != m_modules.end();
1999
2000 return nullptr;
2001}
2002
2003//ModulePtr RunTime::CheckLoadModule(TermPtr &term) {
2004// ASSERT(isModuleName(term->m_text));
2005// std::string name = ExtractModuleName(term->m_text.c_str());
2006//
2007// if (m_modules.find(name) == m_modules.end()) {
2008// if (!LoadModuleFromFile(name.c_str(), true)) {
2009// NL_PARSER(term, "Load module '%s' fail!", term->m_text.c_str());
2010// }
2011// }
2012// return m_modules[name];
2013//}
2014
2015static void zip_save(zip_t *zipper, const std::string_view file, const std::string &data) {
2016 zip_error_t error;
2017 zip_source_t *zip_data = nullptr;
2018 if ((zip_data = zip_source_buffer_create(data.data(), data.size(), ZIP_CREATE | ZIP_TRUNCATE, &error)) == NULL) {
2019 LOG_RUNTIME("can't create source: %s", zip_error_strerror(&error));
2020 }
2021
2022 if (zip_file_add(zipper, file.begin(), zip_data, ZIP_FL_ENC_UTF_8) < 0) {
2023
2024 zip_source_free(zip_data);
2025 LOG_RUNTIME("Failed to add file '%s' to zip: %s", file.begin(), zip_strerror(zipper));
2026 }
2027 // zip_source_commit_write(zip_data);
2028 // zip_source_free(zip_data);
2029 zip_source_keep(zip_data);
2030}
2031
2032bool RunTime::ModuleSave(const FileModule &data, const std::string_view filepath, const std::string_view name) {
2033 int errorp;
2034 zip_t *zipper = zip_open(filepath.begin(), ZIP_CREATE | ZIP_EXCL, &errorp);
2035 if (zipper == nullptr) {
2036 zip_error_t ziperror;
2037 zip_error_init_with_code(&ziperror, errorp);
2038 LOG_RUNTIME("Failed to open output file '%s': %s", filepath.begin(), zip_error_strerror(&ziperror));
2039 }
2040
2041 std::string module_name(name);
2042 if (module_name.empty()) {
2043 module_name = RemoveFileExtension(BaseFileName(filepath));
2044 }
2045
2046 std::string temp_name;
2047 temp_name = module_name;
2048 temp_name += ".inc";
2049
2050 zip_save(zipper, temp_name, data.include);
2051
2052 if (!data.source.empty()) {
2053 temp_name = module_name;
2054 temp_name += ".src";
2055 zip_save(zipper, temp_name, data.source);
2056 }
2057
2058
2059 if (!data.bytecode.empty()) {
2060 temp_name = module_name;
2061 temp_name += ".bc";
2062 zip_save(zipper, temp_name, data.bytecode);
2063 }
2064
2065 zip_close(zipper);
2066
2067 return true;
2068}
2069
2070static bool zip_read(zip* z, const std::string_view name, std::string &data) {
2071 //Search for the file of given name
2072 struct zip_stat st;
2073 zip_stat_init(&st);
2074 zip_stat(z, name.begin(), 0, &st);
2075
2076 if (!st.valid) {
2077 return false;
2078 }
2079
2080 data.resize(st.size);
2081
2082 //Read the compressed file
2083 zip_file* f = zip_fopen(z, name.begin(), 0);
2084 zip_fread(f, data.data(), st.size);
2085 zip_fclose(f);
2086
2087 return true;
2088}
2089
2090bool RunTime::ModuleRead(FileModule &data, const std::string_view filepath, const std::string_view modulename) {
2091 data.bytecode.clear();
2092 data.include.clear();
2093 data.source.clear();
2094 // data.name.clear();
2095
2096 int errorp;
2097 zip* z = zip_open(filepath.begin(), 0, &errorp);
2098 if (z == nullptr) {
2099 zip_error_t ziperror;
2100 zip_error_init_with_code(&ziperror, errorp);
2101 LOG_RUNTIME("Failed to open file '%s': %s", filepath.begin(), zip_error_strerror(&ziperror));
2102 }
2103
2104 data.name.assign(modulename);
2105 if (data.name.empty()) {
2106 data.name = RemoveFileExtension(BaseFileName(filepath));
2107 }
2108
2109 std::string temp_name = data.name;
2110
2111 temp_name = data.name;
2112 temp_name += ".inc";
2113
2114 if (!zip_read(z, temp_name, data.include)) {
2115 LOG_RUNTIME("Name '%s' in file module '%s' not exist!", temp_name.c_str(), filepath.begin());
2116 }
2117
2118 temp_name = data.name;
2119 temp_name += ".src";
2120
2121 if (!zip_read(z, temp_name, data.source)) {
2122 LOG_INFO("Name '%s' in file module '%s' not exist!", temp_name.c_str(), filepath.begin());
2123 }
2124
2125 temp_name = data.name;
2126 temp_name += ".bc";
2127
2128 if (!zip_read(z, temp_name, data.bytecode)) {
2129 LOG_INFO("Name '%s' in file module '%s' not exist!", temp_name.c_str(), filepath.begin());
2130 }
2131
2132 if (data.bytecode.empty() && data.source.empty()) {
2133 LOG_RUNTIME("In file module '%s' not source and bytecode not exist!", filepath.begin());
2134 }
2135
2136 //And close the archive
2137 zip_close(z);
2138
2139 return true;
2140}
2141
2143// * Построчное выполнение не изменяет AST, а только добавляет к нему новые строки.
2144// * Констекст выполнения (m_main_runner) тоже остается не изменным.
2145// */
2146//ObjPtr RunTime::Run(const std::string_view str, Obj* args) {
2147// if (!m_main_ast || m_main_ast->m_id != TermID::BLOCK) {
2148// m_main_ast = Term::Create(parser::token_type::END, TermID::BLOCK, "");
2149// m_main_runner.reset();
2150// }
2151//
2152// TermPtr ast = GetParser()->Parse(str.begin());
2153//
2154// m_main_ast->m_block.push_back(ast);
2155//
2156// if (!m_main_runner) {
2157// m_main_runner = std::make_shared<Context>(m_main_ast->m_int_vars, shared_from_this());
2158// }
2159// try {
2160// m_diag->m_error_count = 0;
2161//
2162// AstAnalysis analysis(*this, m_diag.get());
2163//
2164// analysis.CheckError(analysis.Analyze(ast, m_main_ast));
2165// // AstCheckError(AstAnalyze(ast, m_main_ast));
2166// if (m_diag->m_error_count) {
2167// LOG_PARSER("fatal error: %d generated. ", m_diag->m_error_count);
2168// }
2169//
2170// return Context::Run(m_main_ast->m_block.back(), m_main_runner.get());
2171// } catch (...) {
2172// m_main_ast->m_block.pop_back();
2173// throw;
2174// }
2175//}
2176//
2178// * Выполенение целого AST создает полностью новый контекст выполнения.
2179// */
2180//ObjPtr RunTime::Run(TermPtr ast, Obj* args) {
2181// m_main_ast = ast;
2182// m_main_runner = std::make_shared<Context>(m_main_ast->m_int_vars, shared_from_this());
2183// return Context::Run(m_main_ast, m_main_runner.get());
2184//}
2185
2186std::string RunTime::Escape(const std::string_view str) {
2187 std::string result;
2188 for (auto &c : str) {
2189 if (c == '\n') {
2190 result += "\\n";
2191 } else if (c == '\t') {
2192 result += "\\t";
2193 } else if (c == '\r') {
2194 result += "\\r";
2195 } else {
2196
2197 result += c;
2198 }
2199 }
2200 return result;
2201}
2202
2203//std::string RunTime::NativeNameMangling(const Term *term, RunTime *rt) {
2204// ASSERT(term);
2205// // ASSERT(isNativeName(term->m_text));
2206// // if (!isStaticName(term->m_text)) {
2207// // // extern "C"
2208// // return term->m_text.substr(1);
2209// // } else {
2210// // // C++ mangling
2211// // ObjType type_var = typeFromString(term->m_type, rt);
2212// // if (!isNativeType(type_var)) {
2213// // NL_PARSER(term->m_type, "Type name '%s' not native type!", term->m_type->m_text.c_str());
2214// // }
2215// // if (term->isCall()) {
2216// // // Function
2217// // for (auto &arg : *term) {
2218// // ObjType type_arg = typeFromString(arg->m_type, rt);
2219// // if (!isNativeType(type_arg)) {
2220// // NL_PARSER(arg->m_type, "Type name '%s' not native type!", arg->m_type->m_text.c_str());
2221// // }
2222// //
2223// // }
2224// //
2225// // } else {
2226// // // Dict, Struct, Union, Enum
2227// // }
2228// // }
2229// return "";
2230//}
2231
2232__attribute__ ((weak)) void * RunTime::GetNativeAddress(void * handle, const std::string_view name) {
2233
2234 return dlsym(handle, name.begin());
2235}
2236
2237std::string RunTime::NativeNameMangling(std::string_view name) {
2238 ASSERT(isNativeName(name));
2239
2240 return std::string(name.begin() + 1);
2241}
2242
2243ObjType newlang::typeFromString(TermPtr &term, RunTime *rt, bool *has_error) {
2244 if (term) {
2245
2246 return RunTime::BaseTypeFromString(rt, term->m_text, has_error);
2247 }
2248 return RunTime::BaseTypeFromString(rt, ":Any", has_error);
2249}
2250
2251std::string newlang::GetDoc(std::string name) {
2252
2253 return "Help system not implemented!!!!!";
2254}
2255
2256std::string newlang::MakeConstructorName(std::string name) {
2257 ASSERT(isTypeName(name));
2258 std::string result(name.substr(1));
2259 result += ":";
2260 result += name.substr(name.rfind(":"));
2261
2262 return result;
2263}
2264
2265//std::string newlang::MakeLocalName(std::string name) {
2266// return MangleName(MakeName(name).c_str());
2267//}
2268
2270#ifndef _MSC_VER
2271 return std::string(strerror(errno));
2272#else
2273 wchar_t buffer[256];
2274 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
2275 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, sizeof (buffer), NULL);
2276
2277 return utf8_encode(buffer);
2278#endif
2279}
2280
2281//void * RunTime::GetNativeAddr(const char *name, void * handle) {
2282// return GetDirectAddressFromLibrary(handle, name);
2283//}
2284
2286 if (m_ffi_handle) {
2287
2288 dlclose(m_ffi_handle);
2289 }
2290 m_ffi_handle = nullptr;
2291}
2292
2294//m_llvm_builder(LLVMCreateBuilder()),
2295m_diag(std::make_shared<Diag>()) {
2296
2297 m_assert_enable = true;
2298 m_load_dsl = true;
2299 m_embed_source = false;
2300 m_import_module = true;
2301 m_import_native = true;
2302 m_eval_enable = true;
2303 m_load_runtime = true;
2304 m_link_rt = true;
2305 m_link_jit = true;
2306 // m_error_limit = 10;
2307 m_typedef_limit = 0;
2308 m_ffi_handle = nullptr;
2309
2310 m_cache_dir = ".";
2311 m_work_dir = std::filesystem::current_path();
2312 m_temp_dir = std::filesystem::temp_directory_path();
2313 m_user_dir = getenv("HOME");
2314
2315 // m_cmd_args = Obj::CreateType(ObjType::Dictionary, ObjType::Dictionary, true);
2316 // m_main_args = Obj::CreateType(ObjType::Dictionary, ObjType::Dictionary, true);
2317
2318 // m_main_module = std::make_shared<Module>();
2319
2320 // LLVMLoadLibraryPermanently(nullptr);
2321 // LLVMAddSymbol("convert", (void *) &convert); // Для теста
2322
2323
2324#ifdef _MSC_VER
2325
2326 std::wstring sys_file;
2327 std::string sys_init;
2328
2329 //#define CYGWIN
2330#ifdef CYGWIN
2331 sys_file = L"cygwin1.dll";
2332 sys_init = "cygwin_dll_init";
2333 ffi_file = "cygffi-6.dll";
2334#else
2335 //sys_file = L"msys-2.0.dll";
2336 //sys_init = "msys_dll_init";
2337 ffi_file = "libffi-6.dll";
2338#endif
2339
2340 //m_msys = LoadLibrary(sys_file.c_str());
2341 //if(!m_msys) {
2342 // LOG_RUNTIME("Fail LoadLibrary %s: %s", sys_file.c_str(), RunTime::GetLastErrorMessage().c_str());
2343 //}
2344
2345 // typedef void init_type();
2346 // init_type *init = (init_type *) GetProcAddress((HMODULE) m_msys, sys_init.c_str());
2347 // if(m_msys && !init) {
2348 // FreeLibrary((HMODULE) m_msys);
2349 // LOG_RUNTIME("Func %s not found! %s", sys_init.c_str(), RunTime::GetLastErrorMessage().c_str());
2350 // (*init)();
2351 // }
2352
2353
2354 if (!m_ffi_handle) {
2355 m_ffi_handle = LoadLibrary(utf8_decode(ffi_file).c_str());
2356 }
2357 if (!m_ffi_handle) {
2358 LOG_RUNTIME("Fail load %s!", ffi_file.c_str());
2359 }
2360
2361 m_ffi_type_void = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_void"));
2362 m_ffi_type_uint8 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_uint8"));
2363 m_ffi_type_sint8 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_sint8"));
2364 m_ffi_type_uint16 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_uint16"));
2365 m_ffi_type_sint16 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_sint16"));
2366 m_ffi_type_uint32 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_uint32"));
2367 m_ffi_type_sint32 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_sint32"));
2368 m_ffi_type_uint64 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_uint64"));
2369 m_ffi_type_sint64 = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_sint64"));
2370 m_ffi_type_float = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_float"));
2371 m_ffi_type_double = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_double"));
2372 m_ffi_type_pointer = reinterpret_cast<ffi_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_type_pointer"));
2373
2374 m_ffi_prep_cif = reinterpret_cast<ffi_prep_cif_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_prep_cif"));
2375 m_ffi_prep_cif_var = reinterpret_cast<ffi_prep_cif_var_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_prep_cif_var"));
2376 m_ffi_call = reinterpret_cast<ffi_call_type *> (GetProcAddress((HMODULE) m_ffi_handle, "ffi_call"));
2377
2379 STATIC_ASSERT(sizeof (wchar_t) == 2);
2380
2381#else
2382
2383
2384 // if ((m_ffi_handle = dlopen("ffi", RTLD_NOW)) == nullptr) {
2385 // LOG_RUNTIME("Fail load library libffi!");
2386 // }
2387
2388 m_ffi_type_void = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_void"));
2389 m_ffi_type_uint8 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_uint8"));
2390 m_ffi_type_sint8 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_sint8"));
2391 m_ffi_type_uint16 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_uint16"));
2392 m_ffi_type_sint16 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_sint16"));
2393 m_ffi_type_uint32 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_uint32"));
2394 m_ffi_type_sint32 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_sint32"));
2395 m_ffi_type_uint64 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_uint64"));
2396 m_ffi_type_sint64 = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_sint64"));
2397 m_ffi_type_float = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_float"));
2398 m_ffi_type_double = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_double"));
2399 m_ffi_type_pointer = static_cast<ffi_type *> (GetNativeAddress(m_ffi_handle, "ffi_type_pointer"));
2400
2401 m_ffi_prep_cif = reinterpret_cast<ffi_prep_cif_type *> (GetNativeAddress(m_ffi_handle, "ffi_prep_cif"));
2402 m_ffi_prep_cif_var = reinterpret_cast<ffi_prep_cif_var_type *> (GetNativeAddress(m_ffi_handle, "ffi_prep_cif_var"));
2403 m_ffi_call = reinterpret_cast<ffi_call_type *> (GetNativeAddress(m_ffi_handle, "ffi_call"));
2404
2406 STATIC_ASSERT(sizeof (wchar_t) == 4);
2407
2408#endif
2409
2414 LOG_RUNTIME("Fail init data from libffi!");
2415 }
2416
2417#ifdef _MSC_VER
2419 STATIC_ASSERT(sizeof (wchar_t) == 2);
2420#else
2422 STATIC_ASSERT(sizeof (wchar_t) == 4);
2423#endif
2424
2425#if defined(__x86_64__) || defined(_M_X64) || defined(__amd64__) || defined(__amd64)
2427 STATIC_ASSERT(sizeof (size_t) == 8);
2428#elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
2430 STATIC_ASSERT(sizeof (size_t) == 4);
2431#else
2432#error Target architecture not defined!
2433#endif
2434
2435 InitInternal(args);
2436}
bool Analyze(TermPtr term, NameLookupStack *stack_ptr=nullptr)
bool RegisterObject(bool only_new, const std::string_view name, TermPtr term, Variable var)
Definition types.cpp:239
FuncCallback * m_func
Definition logger.h:399
static Logger * Instance()
Definition logger.h:377
void * m_func_param
Definition logger.h:400
static ObjPtr CreateBaseType(ObjType type)
Definition object.cpp:2554
static ObjPtr CreateNone(Sync *sync=nullptr)
Definition object.h:1510
static ObjPtr CreateType(ObjType type, ObjType fixed=ObjType::None, bool is_init=false, Sync *sync=nullptr)
Definition object.h:1376
TermPtr Parse(const std::string str, bool expand_module=false)
Definition parser.cpp:44
static ffi_type * m_ffi_type_uint64
Definition runtime.h:279
bool m_embed_source
Definition runtime.h:390
std::string m_cache_dir
Definition runtime.h:384
static StringArray MakeMainArgs(int argc, const char **argv, const char **penv)
Definition runtime.h:418
static ffi_type * m_ffi_type_float
Definition runtime.h:281
std::string m_user_dir
Definition runtime.h:386
static ffi_prep_cif_type * m_ffi_prep_cif
Definition runtime.h:285
ObjPtr GetTypeFromString(const std::string_view type, bool *has_error=nullptr)
Definition runtime.cpp:1494
static ffi_prep_cif_var_type * m_ffi_prep_cif_var
Definition runtime.h:286
DiagPtr m_diag
Definition runtime.h:402
bool RegisterBuildinType(ObjType type, std::vector< std::string > parents)
Definition runtime.cpp:1438
static std::string Escape(const std::string_view str)
Definition runtime.cpp:2186
static ObjType BaseTypeFromString(RunTime *rt, const std::string_view text, bool *has_error=nullptr)
Definition runtime.cpp:1525
static ffi_type * m_ffi_type_uint32
Definition runtime.h:277
static ffi_type * m_wide_char_type_ffi
Definition runtime.h:290
static std::string GetLastErrorMessage()
Definition runtime.cpp:2269
static ffi_call_type * m_ffi_call
Definition runtime.h:287
void GlobalNameBuildinRegister()
Definition runtime.cpp:1336
static ffi_type * m_ffi_type_sint64
Definition runtime.h:280
static ffi_type * m_ffi_type_pointer
Definition runtime.h:283
bool m_import_native
Definition runtime.h:392
static ffi_type * m_ffi_type_sint8
Definition runtime.h:274
ObjPtr ExecModule(const char *module, const char *output, bool cached, Context *ctx)
Definition runtime.cpp:1190
static ffi_type * m_ffi_type_uint16
Definition runtime.h:275
static ObjType m_integer_type
Definition runtime.h:291
bool ParseArgs(StringArray args)
Definition runtime.h:479
void ffi_call_type(ffi_cif *cif, void(*fn)(void), void *rvalue, void **avalue)
Definition runtime.h:268
static ffi_type * m_ffi_type_void
Definition runtime.h:272
static void * GetNativeAddress(void *handle, const std::string_view name)
Definition jit.cpp:2796
ObjPtr CreateFunction(TermPtr proto, TermPtr block)
Definition runtime.cpp:1740
static bool pred_compare(const std::string &find, const std::string &str)
Definition runtime.h:345
static ObjType m_wide_char_type
Definition runtime.h:289
bool RegisterSystemFunc(const char *source)
Definition runtime.cpp:1412
static ffi_type * m_ffi_type_uint8
Definition runtime.h:273
virtual ~RunTime()
Definition runtime.cpp:2285
TermPtr ParseBuildin(const std::string_view src)
Definition runtime.cpp:1303
bool LoadModuleFromFile(const char *name_str, bool init)
Definition runtime.cpp:999
static void * m_ffi_handle
Definition runtime.h:271
ffi_status ffi_prep_cif_var_type(ffi_cif *cif, ffi_abi abi, unsigned int nfixedargs, unsigned int ntotalargs, ffi_type *rtype, ffi_type **atypes)
Definition runtime.h:267
static bool ModuleRead(FileModule &data, const std::string_view filename, const std::string_view modulename="")
Definition runtime.cpp:2090
bool m_import_module
Definition runtime.h:391
ObjPtr OpLoadModule(TermPtr term)
Definition runtime.cpp:1965
static ffi_type * m_ffi_type_double
Definition runtime.h:282
bool m_assert_enable
Definition runtime.h:388
bool m_load_runtime
Definition runtime.h:394
StringArray m_module_loader
Definition runtime.h:378
static std::string NativeNameMangling(const Term *term, RunTime *rt)
std::string m_temp_dir
Definition runtime.h:385
static RuntimePtr Init(StringArray args)
Definition runtime.cpp:1222
static ObjPtr CreateNative(const char *proto, const char *module=nullptr, bool lazzy=false, const char *mangle_name=nullptr)
Definition runtime.cpp:1755
static std::string ffi_file
Definition runtime.h:270
RunTime(const StringArray &args={})
Definition runtime.cpp:2293
std::string m_work_dir
Definition runtime.h:382
static bool ExpandFileName(std::string &filename)
Definition runtime.cpp:1318
void InitInternal(const StringArray args)
Definition runtime.cpp:1226
virtual void Clear()
Definition runtime.cpp:74
static bool ModuleSave(const FileModule &data, const std::string_view filename, const std::string_view module_name="")
Definition runtime.cpp:2032
ffi_status ffi_prep_cif_type(ffi_cif *cif, ffi_abi abi, unsigned int nargs, ffi_type *rtype, ffi_type **atypes)
Definition runtime.h:266
static ffi_type * m_ffi_type_sint32
Definition runtime.h:278
static ffi_type * m_ffi_type_sint16
Definition runtime.h:276
bool RegisterBuildinFunc(std::string proto, void *func)
Definition runtime.cpp:1295
bool UnLoadModule(const char *name_str, bool deinit)
Definition runtime.cpp:1121
std::vector< std::wstring > SelectPredict(std::wstring wstart, size_t overage_count=0)
Definition runtime.h:357
std::map< std::string, StorageTerm > ModuleMapType
Definition term.h:172
static TermPtr Create(TermID id, const char *text, parser::token_type lex_type=parser::token_type::END, size_t len=std::string::npos, location *loc=nullptr, std::shared_ptr< std::string > source=nullptr)
Definition term.h:335
static TermPtr CreateName(std::string name, TermID id=TermID::NAME)
Definition term.cpp:44
static newlang::ObjPtr __len__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:95
static newlang::ObjPtr __assert_abort__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:79
static newlang::ObjPtr __thread_get_id__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:136
static newlang::ObjPtr __timeit__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:102
static newlang::ObjPtr __thread_hardware_concurrency__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:132
static newlang::ObjPtr __thread_join__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:145
static newlang::ObjPtr __thread_this_id__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:128
static newlang::ObjPtr __thread_joinable__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:149
static newlang::ObjPtr __thread_start__(newlang::Context *ctx, newlang::Obj &in)
Definition system.cpp:141
int result
Definition lexer.l:367
buffer clear()
__attribute__((weak)) std
Definition logger.cpp:264
#define LOG_RUNTIME(format,...)
Definition logger.h:26
#define LOG_LEVEL_INFO
Definition logger.h:87
#define LOG_INFO(...)
Definition logger.h:120
#define VERIFY(exp)
Definition logger.h:65
#define LOG_DEBUG(...)
Definition logger.h:119
#define STATIC_ASSERT(expr)
Definition logger.h:55
#define ASSERT(condition)
Definition logger.h:60
#define LOG_ERROR(...)
Definition logger.h:122
Definition nlc.h:59
bool isTypeName(ObjType t)
Definition types.h:804
std::wstring utf8_decode(const std::string str)
Definition variable.cpp:22
std::string GetDoc(std::string name)
Definition runtime.cpp:2251
bool isLocalName(const std::string_view name)
Definition types.h:1074
bool isNativeType(ObjType t)
Definition types.h:646
bool isModuleName(const std::string_view name)
Definition types.h:1057
std::shared_ptr< Term > TermPtr
Definition variable.h:33
std::shared_ptr< Obj > ObjPtr
Definition variable.h:28
T BaseFileName(T const &path, T const &delims="/\\")
Definition types.h:137
std::shared_ptr< RunTime > RuntimePtr
Definition types.h:242
T RemoveFileExtension(T const &filename)
Definition types.h:142
std::vector< std::string > StringArray
Definition types.h:148
std::string ExtractModuleName(const std::string_view name)
Definition types.h:1188
ObjType GetBaseTypeFromString(const std::string_view type_arg, bool *has_error=nullptr)
Definition parser.cpp:1102
std::string ReadFile(const char *fileName)
Definition runtime.cpp:1952
bool isNativeName(const std::string_view name)
Definition types.h:1102
ObjType typeFromString(TermPtr &term, RunTime *rt, bool *has_error)
Definition runtime.cpp:2243
std::string ReplaceFileExt(const char *str, const char *ext_old, const char *ext_new)
Definition runtime.cpp:1937
ObjType
Definition types.h:524
int RunMain(const int arg, const char **argv, const char **penv)
Definition runtime.cpp:69
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
std::string GetFileExt(const char *str)
Definition runtime.cpp:1917
std::string utf8_encode(const std::wstring wstr)
Definition variable.cpp:10
std::string MakeConstructorName(std::string name)
Definition runtime.cpp:2256
std::string AddDefaultFileExt(const char *str, const char *ext_default)
Definition runtime.cpp:1927
char convert(char c)
Definition runtime.cpp:1328
static void zip_save(zip_t *zipper, const std::string_view file, const std::string &data)
Definition runtime.cpp:2015
static bool zip_read(zip *z, const std::string_view name, std::string &data)
Definition runtime.cpp:2070
static char nlc_prinft_sub_buffer[4096 *8]
Definition runtime.cpp:50
int nlc_prinft_sub_(char const *format,...)
Definition runtime.cpp:52
std::string include
Definition runtime.h:136
std::string bytecode
Definition runtime.h:138
std::string name
Definition runtime.h:135
std::string source
Definition runtime.h:137
#define NL_PARSER(term, format,...)
Definition types.h:310
#define NL_CHECK(cond, format,...)
Definition types.h:326