diff --git a/CMakeLists.txt b/CMakeLists.txt index 48626e854e..3770cb5e29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1063,6 +1063,7 @@ include/daScript/misc/uric.h include/daScript/misc/lexer_alloc_track.h include/daScript/misc/env_cfg.h include/daScript/misc/dep_recorder.h +include/daScript/misc/jobserver.h src/misc/env_cfg.cpp src/misc/das_common.cpp src/misc/gc_node.cpp @@ -1073,6 +1074,7 @@ src/misc/string_writer.cpp src/misc/luau_float2string.cpp src/misc/memory_model.cpp src/misc/job_que.cpp +src/misc/jobserver.cpp src/misc/handle_registry.cpp src/misc/free_list.cpp src/misc/alloc_tracker.cpp diff --git a/daslib/rst_comment.das b/daslib/rst_comment.das index de621177de..4f5a5fc2bb 100644 --- a/daslib/rst_comment.das +++ b/daslib/rst_comment.das @@ -5,7 +5,7 @@ options indenting = 4 options no_aot = true options strict_smart_pointers = true -module rst_comment shared private +module rst_comment shared private !inscope //! Documentation comment extractor. //! diff --git a/doc/reflections/das2rst.das b/doc/reflections/das2rst.das index 8563333447..a6758e735a 100644 --- a/doc/reflections/das2rst.das +++ b/doc/reflections/das2rst.das @@ -713,7 +713,8 @@ def document_module_jobque(_root : string) { group_by_regex("Internal invocations", mod, %regex~(new_job_invoke|new_thread_invoke|new_thread_loop_invoke|is_thread_loop_capture|new_debugger_thread|set_jobque_fork_pool|get_jobque_fork_pool|get_jobque_fork_skip_init|set_jobque_fork_skip_heap_reset|set_jobque_worker_spin|set_jobque_batch_dispatch|set_jobque_join_spin|set_jobque_team_mode|get_jobque_team_mode|set_jobque_thread_team_mode|get_jobque_thread_team_mode|set_current_thread_priority|get_current_processor|set_current_thread_affinity|set_jobque_threads_cap|set_jobque_threads|get_jobque_threads|set_jobque_affinity|get_jobque_affinity|set_jobque_worker_limit|get_jobque_worker_limit|set_jobque_team_rank_gate|get_jobque_team_rank_gate|set_jobque_team_prof|reset_jobque_team_prof|get_jobque_team_prof|get_jobque_team_prof_counts|get_jobque_team_prof_react|team_parallel_for_invoke|team_parallel_for_indexed_invoke|team_parallel_stages_invoke|flush_jobque_batch|jobque_try_run_one|_builtin_seq_box_publish|_builtin_seq_box_read)$%%), group_by_regex("Construction", mod, %regex~(with_channel|with_stream|with_job_status|with_job_que|with_lock_box|with_seq_box|create_job_que|destroy_job_que)$%%), group_by_regex("SeqBox operations", mod, %regex~(clear)$%%), - group_by_regex("Atomic", mod, %regex~(atomic32_create|atomic32_remove|with_atomic32|atomic64_create|atomic64_remove|with_atomic64|get|set|inc|dec)$%%) + group_by_regex("Atomic", mod, %regex~(atomic32_create|atomic32_remove|with_atomic32|atomic64_create|atomic64_remove|with_atomic64|get|set|inc|dec)$%%), + group_by_regex("Jobserver", mod, %regex~(with_jobserver|with_jobserver_token)$%%) ) document("Jobs and threads", mod, "jobque.rst", groups) } diff --git a/doc/source/reference/language/modules.rst b/doc/source/reference/language/modules.rst index aeb72078a9..eb09cb662e 100644 --- a/doc/source/reference/language/modules.rst +++ b/doc/source/reference/language/modules.rst @@ -206,6 +206,9 @@ Module can be made visible to all modules in the project via the ``!inscope`` mo module Foo !inscope +A module that installs a comment reader has to be ``!inscope``: the reader reads the comments of +every module compiled after it, so those modules wait for it. + --------------- Builtin modules --------------- diff --git a/doc/source/stdlib/handmade/function-jobque-with_jobserver-0x2a9f004ac7eed57b.rst b/doc/source/stdlib/handmade/function-jobque-with_jobserver-0x2a9f004ac7eed57b.rst new file mode 100644 index 0000000000..8f4bcb039e --- /dev/null +++ b/doc/source/stdlib/handmade/function-jobque-with_jobserver-0x2a9f004ac7eed57b.rst @@ -0,0 +1 @@ +Opens the GNU make jobserver pool the build advertises in ``MAKEFLAGS`` and runs the block with it inside a job queue, as ``with_job_que`` does; at most ``limit`` tokens are held at once when ``limit`` is positive, the process's own free token included. diff --git a/doc/source/stdlib/handmade/function-jobque-with_jobserver_token-0xdd496946205f0b8e.rst b/doc/source/stdlib/handmade/function-jobque-with_jobserver_token-0xdd496946205f0b8e.rst new file mode 100644 index 0000000000..f9cb487d9c --- /dev/null +++ b/doc/source/stdlib/handmade/function-jobque-with_jobserver_token-0xdd496946205f0b8e.rst @@ -0,0 +1 @@ +Runs the block while holding one token of the jobserver, waiting until one is free; the token goes back when the block ends. diff --git a/doc/source/stdlib/handmade/structure_annotation-jobque-Jobserver.rst b/doc/source/stdlib/handmade/structure_annotation-jobque-Jobserver.rst new file mode 100644 index 0000000000..f89c7cdcf1 --- /dev/null +++ b/doc/source/stdlib/handmade/structure_annotation-jobque-Jobserver.rst @@ -0,0 +1 @@ +The GNU make jobserver pool of a ``with_jobserver`` block. diff --git a/include/daScript/ast/ast_const_visitor.h b/include/daScript/ast/ast_const_visitor.h index 1b544696c0..28e1f025d7 100644 --- a/include/daScript/ast/ast_const_visitor.h +++ b/include/daScript/ast/ast_const_visitor.h @@ -137,6 +137,43 @@ namespace das { virtual bool canVisitLooksLikeCall ( const ExprLooksLikeCall * expr ) { return true; } virtual bool canVisitLabel ( const ExprLabel * ) { return true; } virtual bool canVisitReader ( const ExprReader * ) { return true; } + virtual bool canVisitStructure ( const Structure * ) { return true; } + virtual bool canVisitGlobalVariable ( const Variable * ) { return true; } + virtual bool canVisitFunction ( const Function * ) { return true; } + virtual bool canVisitEnumeration ( const Enumeration * ) { return true; } + virtual bool canVisitStructureFieldInit ( const Structure * ) { return true; } + virtual bool canVisitArgumentInit ( const Function *, const Variable *, const Expression * ) { return true; } + virtual void preVisitProgram ( const Program * ) {} + virtual void visitProgram ( const Program * ) {} + virtual void preVisitModule ( const Module * ) {} + virtual void visitModule ( const Module * ) {} + virtual void preVisitProgramBody ( const Program *, const Module * ) {} + virtual void preVisitGlobalLetBody ( const Program * ) {} + virtual void visitGlobalLetBody ( const Program * ) {} + virtual void preVisitAlias ( const TypeDecl *, const string & ) {} + virtual void visitAlias ( const TypeDecl *, const string & ) {} + virtual void preVisit ( const Enumeration * ) {} + virtual void preVisitEnumerationValue ( const Enumeration *, const string &, const Expression *, bool ) {} + virtual void visitEnumerationValue ( const Enumeration *, const string &, const Expression *, bool ) {} + virtual void visit ( const Enumeration * ) {} + virtual void preVisit ( const Structure * ) {} + virtual void preVisitStructureAlias ( const Structure *, const string &, const TypeDecl * ) {} + virtual void visitStructureAlias ( const Structure *, const string &, const TypeDecl * ) {} + virtual void preVisitStructureField ( const Structure *, const Structure::FieldDeclaration &, bool ) {} + virtual void visitStructureField ( const Structure *, const Structure::FieldDeclaration &, bool ) {} + virtual void visit ( const Structure * ) {} + virtual void preVisit ( const Function * ) {} + virtual void preVisitArgument ( const Function *, const Variable *, bool ) {} + virtual void visitArgument ( const Function *, const Variable *, bool ) {} + virtual void preVisitArgumentInit ( const Function *, const Variable *, const Expression * ) {} + virtual void visitArgumentInit ( const Function *, const Variable *, const Expression * ) {} + virtual void preVisitFunctionBody ( const Function *, const Expression * ) {} + virtual void visitFunctionBody ( const Function *, const Expression * ) {} + virtual void visit ( const Function * ) {} + virtual void preVisitGlobalLet ( const Variable * ) {} + virtual void visitGlobalLet ( const Variable * ) {} + virtual void preVisitGlobalLetInit ( const Variable *, const Expression * ) {} + virtual void visitGlobalLetInit ( const Variable *, const Expression * ) {} virtual void preVisit ( const TypeDecl * td ) {} virtual void visit ( const TypeDecl * td ) {} virtual void preVisitExpression ( const Expression * expr ) {} @@ -224,6 +261,9 @@ namespace das { #pragma clang diagnostic pop #endif + DAS_API void constVisitFunction ( ConstVisitor & vis, const Function * fn ); + DAS_API void constVisitProgram ( ConstVisitor & vis, const Program * prog, bool visitGenerics ); + template void ExprLikeCall::visit ( ConstVisitor & vis ) const { vis.preVisit(static_cast(this)); diff --git a/include/daScript/misc/jobserver.h b/include/daScript/misc/jobserver.h new file mode 100644 index 0000000000..5ff199d446 --- /dev/null +++ b/include/daScript/misc/jobserver.h @@ -0,0 +1,36 @@ +#pragma once + +#include "daScript/misc/platform.h" + +#include + +namespace das { + + class JobserverState; + + class DAS_API JobserverToken { + public: + JobserverToken ( JobserverToken && other ) noexcept; + JobserverToken & operator = ( JobserverToken && other ) noexcept; + ~JobserverToken (); + private: + friend class Jobserver; + JobserverToken ( JobserverState * s, bool i, char b ) : state(s), implicitToken(i), byte(b) {} + JobserverState * state = nullptr; + bool implicitToken = false; + char byte = 0; + }; + + // src/misc/ARCHITECTURE_JOBSERVER.md#jobserver-client + class DAS_API Jobserver { + public: + explicit Jobserver ( int32_t limit = 0 ); + Jobserver ( int32_t limit, const char * makeflags ); + ~Jobserver (); + Jobserver ( const Jobserver & ) = delete; + Jobserver & operator = ( const Jobserver & ) = delete; + JobserverToken acquire (); + private: + std::unique_ptr state; + }; +} diff --git a/include/daScript/simulate/aot_builtin_jobque.h b/include/daScript/simulate/aot_builtin_jobque.h index 763588e68b..f860c55aa6 100644 --- a/include/daScript/simulate/aot_builtin_jobque.h +++ b/include/daScript/simulate/aot_builtin_jobque.h @@ -340,6 +340,9 @@ namespace das { DAS_API bool channelTryPop ( Channel * ch, const TBlock & blk, Context * context, LineInfoArg * at ); DAS_API bool channelPopWithTimeout ( Channel * ch, int32_t timeoutMs, const TBlock & blk, Context * context, LineInfoArg * at ); DAS_API int jobAppend ( JobStatus * ch, int size, Context * context, LineInfoArg * at ); + class Jobserver; + DAS_API void withJobserver ( int32_t limit, const TBlock & blk, Context * context, LineInfoArg * lineinfo ); + DAS_API void withJobserverToken ( Jobserver * jobserver, const TBlock & blk, Context * context, LineInfoArg * lineinfo ); DAS_API void withChannel ( const TBlock & blk, Context * context, LineInfoArg * lineinfo ); DAS_API void withChannelEx ( int32_t count, const TBlock & blk, Context * context, LineInfoArg * lineinfo ); DAS_API Channel* channelCreate( Context * context, LineInfoArg * at); diff --git a/modules/dasLLVM/ARCHITECTURE.md b/modules/dasLLVM/ARCHITECTURE.md index 42b7f49ff3..4a7e3d8df6 100644 --- a/modules/dasLLVM/ARCHITECTURE.md +++ b/modules/dasLLVM/ARCHITECTURE.md @@ -40,10 +40,10 @@ label silently absorbing new sub-steps breaks the contract the same way an untim Under `--jit-split-modules` (`run_split_codegen` in `llvm_jit_run.das`) the same labels map differently: **declare** reads ~zero (declaration moves inside the partition loop), **irgen** covers partitioning plus every partition's declare/irgen/ctor work, **optimize** carries the -`jit_par_emit_run` pool wall - per-job passes AND object emission interleave on the workers - +`run_split_emit` wall - per-job passes AND object emission interleave on the jobque jobs - plus the post-optimize verifies and the partition teardown, and **emit+link** is the `link_from_objects` link plus the DLL reopen only. The finer steps print per the contract: -one `LLVM JIT time: job {obj} passes ... emit ...` line per partition (from the pool, under the +one `LLVM JIT time: job {obj} passes ... emit ...` line per partition (from `run_split_emit`, under the same log option) and the `link ... (N objects)` line under emit+link. With the obj cache on (`--jit-obj-cache`, default under split), cached partitions skip declare/irgen/optimize entirely: the key fold and probe cost lands in **irgen**, the `obj cache - K/N partitions diff --git a/modules/dasLLVM/daslib/llvm_jit_run.das b/modules/dasLLVM/daslib/llvm_jit_run.das index 8524fd9c7c..3c3e1453f0 100644 --- a/modules/dasLLVM/daslib/llvm_jit_run.das +++ b/modules/dasLLVM/daslib/llvm_jit_run.das @@ -23,6 +23,9 @@ require daslib/strings_boost require daslib/defer require daslib/fio +require daslib/jobque_boost +require daslib/safe_addr +require math require daslib/option require daslib/result require jit @@ -38,7 +41,7 @@ var LINK_WHOLE_LIB = false // when true, standalone exe links against the whole // Read by tests-cpp/small/test_jit_emitter_pin.cpp: FNV-1a64 of the emitter sources // (normalized to LF; file list in the test) -let LLVM_JIT_EMITTER_HASH : uint64 = 0xb6ad06f91d81b170ul +let LLVM_JIT_EMITTER_HASH : uint64 = 0x670ce6130f2bcf5eul [arch(at = "../ARCHITECTURE_FAST_MATH.md#never-fast-math")] def private apply_fast_math_to_module(m : LLVMOpaqueModule?) { @@ -443,13 +446,109 @@ def private remove_split_link_files(objs : array; output_path : string) remove(split_link_rsp_path(output_path), err) } +//! the LLVM handles travel as integers: a channel clones the job +//! into the worker's context, and a pointer field would be cloned +//! as a pointer to own +struct private SplitEmitJob { + mod : uint64 + tm : uint64 + pbo : uint64 + pipeline : string + obj : string +} + +struct private SplitEmitResult { + obj : string + error : string + passes_usec : int + emit_usec : int +} + +def private run_split_emit_job(job : SplitEmitJob implicit) : SplitEmitResult { + var res = SplitEmitResult(obj = job.obj) + let mod = unsafe(reinterpret(job.mod)) + let tm = unsafe(reinterpret(job.tm)) + let pbo = unsafe(reinterpret(job.pbo)) + let t0 = ref_time_ticks() + if (!empty(job.pipeline)) { + let err = LLVMRunPasses(mod, job.pipeline, tm, pbo) + if (err != null) { + let msg = LLVMGetErrorMessage(err) + res.error = "pass run failed: {msg}" + LLVMDisposeErrorMessage(msg) + return <- res + } + } + var verify_msg : string + let verify_action = LLVMVerifierFailureAction.LLVMReturnStatusAction + if (LLVMVerifyModule(mod, verify_action, safe_addr(verify_msg)) != 0) { + res.error = "post-optimize verify failed for {job.obj}: {verify_msg}" + } + LLVMDisposeMessage(verify_msg) + res.passes_usec = get_time_usec(t0) + return <- res if (!empty(res.error) || empty(job.obj)) + let t1 = ref_time_ticks() + var emit_msg : string + let file_type = LLVMCodeGenFileType.LLVMObjectFile + if (LLVMTargetMachineEmitToFile(tm, mod, job.obj, file_type, safe_addr(emit_msg)) != 0) { + res.error = "emit failed for {job.obj}: {emit_msg}" + LLVMDisposeMessage(emit_msg) + } + res.emit_usec = get_time_usec(t1) + return <- res +} + +def private report_split_emit(res : SplitEmitResult implicit; log_jit_time : bool) : bool { + if (!empty(res.error)) { + to_log(LOG_ERROR, "LLVM JIT: parallel emit: {res.error}\n") + return false + } + if (log_jit_time) { + let passes = double(res.passes_usec) / 1000000.0lf + let emit = double(res.emit_usec) / 1000000.0lf + to_log(LOG_INFO, "LLVM JIT time: job {res.obj} passes {passes} emit {emit}\n") + } + return true +} + +//! optimize+emit each job on its own jobque job, at most `threads` +//! at once (<= 0: the job queue decides); results come back through +//! a channel; false on any failure +def private run_split_emit(jobs : array; threads : int; log_jit_time : bool) : bool { + return true if (empty(jobs)) + var ok = true + if (threads == 1 || length(jobs) == 1) { + for (job in jobs) { + ok = report_split_emit(run_split_emit_job(job), log_jit_time) && ok + } + return ok + } + with_jobserver(max(threads, 0)) $(jobserver) { + with_channel(length(jobs)) $(done) { + for (job in jobs) { + new_job() @() { + with_jobserver_token(jobserver) { + done |> push_clone(run_split_emit_job(job)) + } + done |> notify_and_release + } + } + done |> for_each_clone() $(res : SplitEmitResult#) { + ok = report_split_emit(res, log_jit_time) && ok + } + } + } + return ok +} + // nolint:STYLE014 // --jit-split-modules driver, three phases. A (serial das): partition `funcs` by owning das-module // (program order), codegen each partition into its OWN (context, module, engine) emitter state - // stashed in g_split_parts, the LAST left ambient for the shared install/finalize path. B: the -// jit_par_emit_run C++ pool optimizes + emits every partition on K threads (K=1 = serial bring-up; +// run_split_emit optimizes + emits every partition on K jobque jobs +// (K=1 = serial bring-up; // one LLVMContext per job is LLVM's threading contract; the SAME LLVMRunPasses/EmitToFile calls as -// the monolith path, entry points resolved through dasbind - libDaScript never links LLVM). C +// the monolith path). C // (serial das): post-optimize verify per partition, then dispose everything but the ambient state. [macro_function, arch(at="../ARCHITECTURE_EXE.md#split-exe-lto")] def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array; // nolint:STYLE037,STYLE038 - the split orchestration is one linear pipeline (the cache probe adds its branches); the phases share the re-pointed g_* state @@ -477,7 +576,7 @@ def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array one {target.gen_exe ? "exe" : "DLL"}\n") // the dir must exist before the FIRST emit (a missing dir crashes LLVMTargetMachineEmitToFile) mkdir_rec(dir_name(output_path)) - jit_par_emit_begin() + var emit_jobs : array g_split_parts |> reserve(length(order)) // empty pipeline = pool skips optimization (the LLVM_ENABLE_OPT_PASS / LLVM_DEBUG_EVERYTHING rail) let pipeline = LLVM_ENABLE_OPT_PASS ? opt_pipeline_string(opt_level |> uint, size_level |> uint, sanitize) : "" @@ -623,36 +722,23 @@ def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array reserve(length(g_split_parts)) for (p in g_split_parts) { // optimize only: LTO leaves as bitcode, a hide run emits in round two - jit_par_emit_add(p.mod, p.tm, p.pbo, pipeline, (lto_run || hide_run) ? "" : p.obj) + let obj = (lto_run || hide_run) ? "" : p.obj + emit_jobs |> push(SplitEmitJob( + mod = intptr(p.mod), tm = intptr(p.tm), pbo = intptr(p.pbo), + pipeline = pipeline, obj = obj)) } } let tIr = get_time_usec(phase_tm) phase_tm = ref_time_ticks() // phase B - per-job walls logged by the pool under log_compile_time; all partitions cached -> zero jobs, skip the pool (and the LLVM symbol resolution) outright if (main_ok && !empty(g_split_parts)) { - let llvm_lib = __dasbind_get_library("llvm") - if (llvm_lib == null) { - reset_jit_globals_after_failure() - panic("LLVM JIT: split emit - can't resolve the LLVM library handle") - } - // resolve once + validate ALL entry points - a mismatched LLVM.dll names its missing symbol here - let lfn_names = ["LLVMRunPasses", "LLVMVerifyModule", "LLVMTargetMachineEmitToFile", - "LLVMGetErrorMessage", "LLVMDisposeErrorMessage", "LLVMDisposeMessage"] - var lfns : array - lfns |> reserve(length(lfn_names)) - for (nm in lfn_names) { - let p = llvm_lib |> get_function_address(nm) - if (p == null) { - reset_jit_globals_after_failure() - panic("LLVM JIT: split emit - can't resolve {nm} in the LLVM library") - } - lfns |> push(p) - } - var ok = jit_par_emit_run(split_threads, int(LLVMCodeGenFileType.LLVMObjectFile), - lfns[0], lfns[1], lfns[2], lfns[3], lfns[4], lfns[5], log_jit_time) + var ok = run_split_emit(emit_jobs, split_threads, log_jit_time) if (ok && hide_run) { + emit_jobs |> clear() + emit_jobs |> reserve(length(g_split_parts)) for (p in g_split_parts) { if (p.solid) { hide_solid_array_bases(p.mod, p.ctx) @@ -660,10 +746,11 @@ def private run_split_codegen(prog : Program?; ctx : Context?; funcs : array push(SplitEmitJob( + mod = intptr(p.mod), tm = intptr(p.tm), pbo = intptr(p.pbo), + pipeline = "", obj = p.obj)) } - ok = jit_par_emit_run(split_threads, int(LLVMCodeGenFileType.LLVMObjectFile), - lfns[0], lfns[1], lfns[2], lfns[3], lfns[4], lfns[5], log_jit_time) + ok = run_split_emit(emit_jobs, split_threads, log_jit_time) } if (!ok) { reset_jit_globals_after_failure() diff --git a/modules/dasLLVM/daslib/llvm_macro.das b/modules/dasLLVM/daslib/llvm_macro.das index 3adcbe2c0c..08f5c16234 100644 --- a/modules/dasLLVM/daslib/llvm_macro.das +++ b/modules/dasLLVM/daslib/llvm_macro.das @@ -24,8 +24,12 @@ def public run_jit_codegen(prog : Program?; var ctx : Context?; var ok : bool?) *ok = run_jit(prog, ctx).ok } +//! a jobque or thread clone of this context dies while LLVM is +//! still in use - only the context itself shuts LLVM down [finalize(late)] def private shutdown_llvm { + let category = this_context().category + return if (category.job_clone || category.thread_clone) LLVMShutdown() } diff --git a/modules/dasLLVM/tests/llvm_tune.das b/modules/dasLLVM/tests/llvm_tune.das index b5644bac9f..223de8d292 100644 --- a/modules/dasLLVM/tests/llvm_tune.das +++ b/modules/dasLLVM/tests/llvm_tune.das @@ -653,7 +653,8 @@ def test_llvm_tune_carry_into_per_annotation(t : T?) { let args <- get_command_line_arguments() var lines : array let client = "{get_this_module_dir()}/_llvm_tune_carry_client.das" - let rc = spawn_child("\"{args[0]}\" -no-module-cache \"{client}\"", lines) + let child = "\"{args[0]}\" -no-module-cache \"{client}\"" + let rc = spawn_child(get_platform_name() == "windows" ? "\"{child}\"" : child, lines) t |> equal(rc, 0, "the carry client compiles and runs\n{join(lines, "\n")}") t |> success(lines |> has("CARRY never_fast_math 1 hint 1 never_inline true"), "one never_fast_math, one hint, never-inline set, after two passes\n{join(lines, "\n")}") diff --git a/skills/daslang/references/everything.md b/skills/daslang/references/everything.md index 6732c82cea..feb87097a6 100644 --- a/skills/daslang/references/everything.md +++ b/skills/daslang/references/everything.md @@ -4686,6 +4686,7 @@ The JOBQUE module provides low-level job queue and threading primitives. It incl - `Stream` - FIFO pipe of opaque byte buffers shared between contexts and threads. - `SeqBox.hasValue` - Returns true when a snapshot has been published and not since cleared. - `SeqBox` - Wait-free snapshot box. +- `Jobserver` - The GNU make jobserver pool of a `with_jobserver` block. - `Atomic64` - Atomic 64 bit integer. - `Atomic32` - Atomic 32 bit integer. - `JobStatus.isReady` - Whether the job has completed execution. @@ -4805,6 +4806,11 @@ The JOBQUE module provides low-level job queue and threading primitives. It incl - `with_atomic32` - Creates an `Atomic32` scoped to the given block and automatically destroys it afterward. - `with_atomic64` - Creates an `Atomic64` scoped to the given block and automatically destroys it afterward. +### Jobserver + +- `with_jobserver` - Opens the GNU make jobserver pool the build advertises in `MAKEFLAGS` and runs the block with it inside a job queue, as `with_job_que` does; at most `limit` tokens are held at once when `limit` is positive, the process's own free token included. +- `with_jobserver_token` - Runs the block while holding one token of the jobserver, waiting until one is free; the token goes back when the block ends. + ## algorithm The ALGORITHM module provides array and collection manipulation algorithms including sorting, searching, set operations, element removal, and more. diff --git a/skills/internal/environment_variables.md b/skills/internal/environment_variables.md index 7dc52bfa8d..f2eafc92f2 100644 --- a/skills/internal/environment_variables.md +++ b/skills/internal/environment_variables.md @@ -119,8 +119,9 @@ never what is compiled. `NO_COLOR` and `TERM` gate ANSI output (`daslib/ansi_colors`). `TMPDIR`, `HOME`, `XDG_CONFIG_HOME`, `APPDATA` and `LOCALAPPDATA` are used for scratch and config paths in the usual platform way. On Windows, `OS`, `PROCESSOR_ARCHITECTURE` and `NUMBER_OF_PROCESSORS` are read for -platform detection. Setting any of these changes daslang's behaviour only as far as the platform -convention implies. +platform detection. `MAKEFLAGS` (and `CARGO_MAKEFLAGS`, `MFLAGS`) carry a GNU make jobserver's +`--jobserver-auth`, whose pool a parallel compile joins (`src/misc/ARCHITECTURE_JOBSERVER.md`). +Setting any of these changes daslang's behaviour only as far as the platform convention implies. ## Adding one diff --git a/src/ast/ARCHITECTURE_COMPILE_MODULES.md b/src/ast/ARCHITECTURE_COMPILE_MODULES.md index b10af3a29b..a27049015b 100644 --- a/src/ast/ARCHITECTURE_COMPILE_MODULES.md +++ b/src/ast/ARCHITECTURE_COMPILE_MODULES.md @@ -6,11 +6,15 @@ Companion to `ARCHITECTURE.md` in this folder. `compileModules` compiles every module the prerequisite walk found; every caller goes through it, and it returns the errors of the module that failed. The walk lists modules in post-order, so -dependencies come first. A module's edges are the `require`s in its file. +dependencies come first. A module's edges are the `require`s in its file, and every `!inscope` +module before it in walk order (`#comment-readers`). With `compile_threads` above 1 the modules run as `JobQue` jobs: a module starts once its dependencies are done, longest remaining chain first. No job waits for another, so the queue cannot deadlock. +`compile_threads` 0 is the `JobQue` thread count. A build with no threads - wasm without +`-pthread` - compiles in walk order whatever the count, since it cannot start a worker. + `options log_compile_dag` prints the graph with measured times and the best possible schedule. ## Compile workers {#compile-workers} @@ -20,7 +24,12 @@ When all jobs finish, the main thread registers the modules in walk order, so sh writer. Jobs share the compile's `FileAccess`: it is locked, since the walk already loaded every file, and jobs only borrow the pointer, since its reference count is not atomic. A locked access loads no new file, and a `.das_project` access runs its project context under that context's lock. -A frozen module is read-only: a job reads its globals' access flags but never stamps them. +A frozen module is read-only: a job reads its globals' access flags but never stamps them. A +`Visitor` stores every child it passes back into its node, so a walk that only reads - the printer, +the inliner's clone shape - is a `ConstVisitor`, and the printer keeps the levels that place its +brackets in a table of its own: walking or printing a frozen module's AST writes nothing. A dynamic module loaded on demand by the walk freezes like the ones +loaded at startup, since iterating an unfrozen table stamps its lock, and a module freezes with the +alias cache of every type on its root filled, since a type fills it on first read. ## The cached prefix {#cache-prefix} @@ -35,6 +44,25 @@ A macro call holds its context's lock. A macro that calls `compile`, `require_mo threads could wait for each other. Such builtins are marked `nestsCompile` where they are registered; a function that calls one gets -the flag too, and a macro module holding such a function is `macroNestsCompile`. -A nesting module builds its macro context on the main thread after the jobs, and the modules that -use it compile after that, in walk order. +the flag too, and a macro module holding such a function is `macroNestsCompile`. A job never +builds such a module's macro context: the module and every module after it in walk order +compile on the main thread after the jobs (`#walk-order-tail`), where no other macro runs. + +## Comment readers {#comment-readers} + +A comment reader is one object per module, and every parse takes the readers of every built-in +module and of every module in its group, required or not: a reader sees every module parsed after +it in walk order, and holds that parse's state between its callbacks. So a module that installs a +reader is declared `!inscope`, which the require scan reads from its `module` line, and every +module after it in walk order depends on it in the DAG: each of them is parsed after the reader +exists, as in the sequential compile, while they still run in parallel with each other. A parse +that takes a reader holds one lock for the whole parse, so parses with readers take turns while +inference and macros stay parallel; the lock is recursive, for a parse nested on the same thread. + +## The walk-order tail {#walk-order-tail} + +A job learns that its module is nesting only when that module's compile ends. From then on no job +at or after that position starts, and the results of later modules that finished without it are +dropped. The main thread then compiles every module not yet registered in walk order, each +through the whole sequential pipeline, so from that position on the compile is the sequential +one: no module's macro context is built later than in it. diff --git a/src/ast/ast_compile_modules.cpp b/src/ast/ast_compile_modules.cpp index 9df238a99a..70e6e7f516 100644 --- a/src/ast/ast_compile_modules.cpp +++ b/src/ast/ast_compile_modules.cpp @@ -5,6 +5,7 @@ #include "ast_compile_modules.h" #include "ast_parse.h" #include "daScript/misc/job_que.h" +#include "daScript/misc/jobserver.h" #include "daScript/misc/performance_time.h" #include "daScript/simulate/das_qsort_r.h" @@ -30,6 +31,7 @@ namespace das { for ( auto & mod : modules ) { auto node = int32_t(deps.size()); deps.push_back(extraDeps); + bool visibleEverywhere = false; publicDeps.emplace_back(); sourceBytes.push_back(1); if ( FileInfo * fi = access->getFileInfo(mod.fileName) ) { @@ -39,7 +41,7 @@ namespace das { sourceBytes[node] = das::max(len, 1u); string modName; vector chain; - for ( auto & rec : getAllRequire(fi, modName, chain, access) ) { + for ( auto & rec : getAllRequire(fi, modName, chain, access, &visibleEverywhere) ) { auto it = nodeByFile.find(access->getModuleInfo(rec.name, mod.fileName).fileName); if ( it == nodeByFile.end() ) continue; auto & nodeDeps = deps[node]; @@ -49,7 +51,8 @@ namespace das { } } nodeByFile[mod.fileName] = node; - if ( mod.extraDepModule ) extraDeps.push_back(node); + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#comment-readers + if ( mod.extraDepModule || visibleEverywhere ) extraDeps.push_back(node); } dependents.resize(deps.size()); for ( int32_t node = 0; node != int32_t(deps.size()); ++node ) { @@ -68,29 +71,6 @@ namespace das { } // src/ast/ARCHITECTURE_COMPILE_MODULES.md#deadlock-prevention - vector macroUsers ( int32_t macroModule ) const { - vector exports(deps.size(), false); - exports[macroModule] = true; - for ( size_t i = macroModule + 1; i < deps.size(); ++i ) { - for ( auto p : publicDeps[i] ) { - if ( exports[p] ) { - exports[i] = true; - break; - } - } - } - vector users; - for ( size_t i = macroModule + 1; i < deps.size(); ++i ) { - for ( auto d : deps[i] ) { - if ( exports[d] ) { - users.push_back(int32_t(i)); - break; - } - } - } - return users; - } - struct ReadyQueue { const ModuleDag & dag; const vector & exclusive; @@ -207,15 +187,13 @@ namespace das { void log ( const vector & modules, const vector & usec, ModuleGroup & libGroup, TextWriter & logs ) const { auto count = deps.size(); - vector nesting; - vector exclusive(count, false); - for ( size_t i = 0; i != count; ++i ) { + size_t sequential = count; + for ( size_t i = 0; i != count && sequential == count; ++i ) { auto mod = libGroup.findModule(modules[i].moduleName); - if ( mod && mod->macroNestsCompile ) { - nesting.push_back(int32_t(i)); - for ( auto u : macroUsers(int32_t(i)) ) exclusive[u] = true; - } + if ( mod && mod->macroNestsCompile ) sequential = i; } + vector exclusive(count, false); + for ( size_t i = sequential; i < count; ++i ) exclusive[i] = true; uint64_t total = 0; size_t edges = 0; for ( size_t i = 0; i != count; ++i ) { @@ -239,10 +217,8 @@ namespace das { for ( auto n : path ) pathUsec += usec[n]; logs << "compile DAG: " << count << " modules, " << edges << " edges, total " << (total / 1000000.) << ", critical path " << (pathUsec / 1000000.) << "\n"; - for ( auto m : nesting ) { - logs << "\tnesting macro module " << modules[m].moduleName << ", users compile alone:"; - for ( auto u : macroUsers(m) ) logs << " " << modules[u].moduleName; - logs << "\n"; + if ( sequential < count ) { + logs << "\tfrom " << modules[sequential].moduleName << " on, the modules compile in walk order\n"; } vector ones(count, 1); for ( int32_t workers : { 2, 4, 8, 16, 32 } ) { @@ -307,7 +283,8 @@ namespace das { // src/ast/ARCHITECTURE_COMPILE_MODULES.md#cache-prefix InOrderResult compileModulesInOrder ( const vector & modules, size_t from, const FileAccessPtr & access, TextWriter & logs, ModuleGroup & libGroup, CodeOfPolicies & policies, bool promoteShared, - const ModuleCacheStream & stream, bool untilCutoff, vector & usec ) { + const ModuleCacheStream & stream, bool untilCutoff, vector & usec, + vector * compiled = nullptr ) { InOrderResult result; for ( result.next = from; result.next != modules.size(); ++result.next ) { if ( untilCutoff && (!stream.read || stream.read->seenNewModule) ) break; @@ -323,6 +300,7 @@ namespace das { result.failed = program; break; } + if ( compiled && !compiled->empty() ) (*compiled)[result.next] = program; } return result; } @@ -401,6 +379,8 @@ namespace das { vector results; vector> remaining; std::atomic finished{0}; + std::atomic firstSequential{INT32_MAX}; + Jobserver jobserver; ModuleJobs ( const vector & mods, const ModuleDag & d, const FileAccessPtr & acc, const CodeOfPolicies & pol, ModuleGroup & libGroup ) @@ -437,7 +417,16 @@ namespace das { deps.push_back(&results[i]); for ( auto dep : dag.deps[i] ) reach[dep] = true; } - results[node] = compileModuleJob(modules[node], prepared[node], access, policies, initialModules, deps); + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#walk-order-tail + if ( node >= firstSequential ) { + results[node].skipped = true; + } else { + auto token = jobserver.acquire(); + results[node] = compileModuleJob(modules[node], prepared[node], access, policies, initialModules, deps); + if ( results[node].deferred ) { + for ( auto seen = firstSequential.load(); node < seen && !firstSequential.compare_exchange_weak(seen, node); ) {} + } + } daScriptEnvironment::setBound(bound); vector ready; for ( auto dependent : dag.dependents[node] ) { @@ -481,18 +470,17 @@ namespace das { libGroup.findModule(mod.moduleName)->fromExtraDependency &= mod.extraDepModule; continue; } - if ( failed || result.skipped ) continue; + if ( failed || result.skipped || node >= jobs.firstSequential ) continue; logs << result.logs; if ( result.root ) { while ( auto gcNode = result.root->gc_first ) gcNode->gc_assign(&target); } - if ( result.deferred ) buildDeferredMacroModule(result.program, libGroup, logs); if ( !compiled.empty() ) compiled[node] = result.program; if ( !registerCompiledModule(result.program, mod, access, libGroup, policies, promoteShared) ) failed = result.program; } if ( failed ) return failed; return compileModulesInOrder(modules, 0, access, logs, libGroup, policies, promoteShared, ModuleCacheStream(), false, - usec).failed; + usec, &compiled).failed; } bool loadedModuleNests ( ModuleGroup & libGroup ) { @@ -510,7 +498,11 @@ namespace das { // src/ast/ARCHITECTURE_COMPILE_MODULES.md#cache-prefix auto prefix = compileModulesInOrder(modules, 0, access, logs, libGroup, policies, promoteShared, stream, true, usec); if ( prefix.failed ) return prefix.failed->errors; +#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__) + int32_t threads = 1; +#else auto threads = policies.compile_threads == 0 ? JobQue::get_num_threads() : policies.compile_threads; +#endif bool parallel = threads > 1 && modules.size() - prefix.next > 1 && !loadedModuleNests(libGroup); ModuleDag dag; if ( parallel || logDag ) dag = ModuleDag(modules, access); diff --git a/src/ast/ast_const_folding.cpp b/src/ast/ast_const_folding.cpp index 652e6c5b58..a0f4fdcc4d 100644 --- a/src/ast/ast_const_folding.cpp +++ b/src/ast/ast_const_folding.cpp @@ -609,7 +609,7 @@ namespace das { !var->argument && !var->block ) { if ( variable->init->rtti_isConstant() ) { - if ( recordConstAccess ) variable->access_fold = true; + if ( recordConstAccess && !isFrozenGlobal(variable) ) variable->access_fold = true; auto folded = variable->init->clone(); // a C++-registered constant has no location of its own, so the folded // value reports where it was used @@ -623,7 +623,7 @@ namespace das { // always a fresh clone, since a node has exactly one parent auto memo = constExprFolded.find(variable); if ( memo != constExprFolded.end() ) { - if ( recordConstAccess ) variable->access_fold = true; + if ( recordConstAccess && !isFrozenGlobal(variable) ) variable->access_fold = true; auto folded = memo->second->clone(); stampMissingAt(folded, expr->at); return folded; @@ -635,7 +635,7 @@ namespace das { auto folded = foldConstInit(variable->init); constExprFolding.erase(variable); if ( folded ) { - if ( recordConstAccess ) variable->access_fold = true; + if ( recordConstAccess && !isFrozenGlobal(variable) ) variable->access_fold = true; constExprFolded[variable] = folded->clone(); return folded; } diff --git a/src/ast/ast_const_visitor.cpp b/src/ast/ast_const_visitor.cpp index 939d6b8f03..545ceebeb9 100644 --- a/src/ast/ast_const_visitor.cpp +++ b/src/ast/ast_const_visitor.cpp @@ -649,4 +649,98 @@ namespace das { } vis.visit(this); } + + void constVisitFunction ( ConstVisitor & vis, const Function * fn ) { + vis.preVisit(fn); + for ( auto arg : fn->arguments ) { + vis.preVisitArgument(fn, arg, arg==fn->arguments.back()); + if ( arg->type ) constVisitTypeFull(vis, arg->type); + if ( arg->init && vis.canVisitArgumentInit(fn, arg, arg->init) ) { + vis.preVisitArgumentInit(fn, arg, arg->init); + arg->init->visit(vis); + vis.visitArgumentInit(fn, arg, arg->init); + } + vis.visitArgument(fn, arg, arg==fn->arguments.back()); + } + if ( fn->result ) constVisitTypeFull(vis, fn->result); + if ( fn->body ) { + vis.preVisitFunctionBody(fn, fn->body); + fn->body->visit(vis); + vis.visitFunctionBody(fn, fn->body); + } + vis.visit(fn); + } + + static void constVisitStructure ( ConstVisitor & vis, const Structure * st ) { + vis.preVisit(st); + st->aliases.foreach([&](auto & alias){ + vis.preVisitStructureAlias(st, alias->alias, alias); + constVisitTypeFull(vis, alias); + vis.visitStructureAlias(st, alias->alias, alias); + }); + for ( auto & fi : st->fields ) { + vis.preVisitStructureField(st, fi, &fi==&st->fields.back()); + if ( fi.type ) constVisitTypeFull(vis, fi.type); + if ( fi.init && vis.canVisitStructureFieldInit(st) ) fi.init->visit(vis); + vis.visitStructureField(st, fi, &fi==&st->fields.back()); + } + vis.visit(st); + } + + static void constVisitEnumeration ( ConstVisitor & vis, const Enumeration * en ) { + vis.preVisit(en); + size_t count = 0; + size_t total = en->list.size(); + for ( auto & itf : en->list ) { + vis.preVisitEnumerationValue(en, itf.name, itf.value, count==total); + if ( itf.value ) itf.value->visit(vis); + vis.visitEnumerationValue(en, itf.name, itf.value, count==total); + count ++; + } + vis.visit(en); + } + + static void constVisitGlobal ( ConstVisitor & vis, const Variable * var ) { + vis.preVisitGlobalLet(var); + if ( var->type ) constVisitTypeFull(vis, var->type); + if ( var->init ) { + vis.preVisitGlobalLetInit(var, var->init); + var->init->visit(vis); + vis.visitGlobalLetInit(var, var->init); + } + vis.visitGlobalLet(var); + } + + void constVisitProgram ( ConstVisitor & vis, const Program * prog, bool visitGenerics ) { + vis.preVisitProgram(prog); + auto mod = prog->thisModule.get(); + vis.preVisitModule(mod); + mod->enumerations.foreach([&](auto & en){ + if ( vis.canVisitEnumeration(en) ) constVisitEnumeration(vis, en); + }); + mod->structures.foreach([&](auto & st){ + if ( vis.canVisitStructure(st) ) constVisitStructure(vis, st); + }); + mod->aliasTypes.foreach([&](auto & alias){ + vis.preVisitAlias(alias, alias->alias); + constVisitTypeFull(vis, alias); + vis.visitAlias(alias, alias->alias); + }); + vis.preVisitProgramBody(prog, mod); + vis.preVisitGlobalLetBody(prog); + mod->globals.foreach([&](auto & var){ + if ( vis.canVisitGlobalVariable(var) ) constVisitGlobal(vis, var); + }); + vis.visitGlobalLetBody(prog); + if ( visitGenerics ) { + mod->generics.foreach([&](auto & fn){ + if ( !fn->builtIn || prog->visitBuiltinFunctions ) constVisitFunction(vis, fn); + }); + } + mod->functions.foreach([&](auto & fn){ + if ( (!fn->builtIn || prog->visitBuiltinFunctions) && vis.canVisitFunction(fn) ) constVisitFunction(vis, fn); + }); + vis.visitModule(mod); + vis.visitProgram(prog); + } } diff --git a/src/ast/ast_effects.h b/src/ast/ast_effects.h index 78a91eaa97..827f5a364c 100644 --- a/src/ast/ast_effects.h +++ b/src/ast/ast_effects.h @@ -6,4 +6,9 @@ namespace das { bool nodeRaises ( Expression * expr ); bool callRaises ( Function * fn ); bool droppable ( Expression * expr ); + // a global of a frozen (already compiled) module is read-only: module jobs that require it + // must not stamp its flags. src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers + inline bool isFrozenGlobal ( const Variable * var ) { + return var->module && var->module->frozen; + } } diff --git a/src/ast/ast_inline.cpp b/src/ast/ast_inline.cpp index d5f7535a02..46740c020c 100644 --- a/src/ast/ast_inline.cpp +++ b/src/ast/ast_inline.cpp @@ -327,27 +327,24 @@ namespace das { // ----- cloned-body fixup: rename locals, substitute parameter reads ----- - class CloneShape : public Visitor { + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers + class CloneShape : public ConstVisitor { public: vector nodes; vector vars; protected: - virtual bool canVisitQuoteSubexpression ( ExprQuote * ) override { return false; } - virtual void preVisitExpression ( Expression * expr ) override { - Visitor::preVisitExpression(expr); - nodes.push_back(expr); + virtual void preVisitExpression ( const Expression * expr ) override { + nodes.push_back(const_cast(expr)); } - virtual void preVisitLet ( ExprLet * let, const VariablePtr & var, bool last ) override { - Visitor::preVisitLet(let, var, last); - vars.push_back(var); + virtual void preVisitLet ( const ExprLet *, const Variable * var, bool ) override { + vars.push_back(const_cast(var)); } - virtual void preVisit ( ExprFor * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprFor * expr ) override { + ConstVisitor::preVisit(expr); for ( auto & var : expr->iteratorVariables ) vars.push_back(var); } - virtual void preVisitBlockArgument ( ExprBlock * block, const VariablePtr & var, bool lastArg ) override { - Visitor::preVisitBlockArgument(block, var, lastArg); - vars.push_back(var); + virtual void preVisitBlockArgument ( const ExprBlock *, const Variable * var, bool ) override { + vars.push_back(const_cast(var)); } }; diff --git a/src/ast/ast_module.cpp b/src/ast/ast_module.cpp index 93ebf19f59..15ab9294f8 100644 --- a/src/ast/ast_module.cpp +++ b/src/ast/ast_module.cpp @@ -433,8 +433,16 @@ namespace das { isPublic = true; } + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers + static void fillAliasCaches ( Module * mod ) { + for ( auto node = mod->module_gc_root->gc_first; node; node = node->gc_next ) { + if ( node->gc_magic == GC_MAGIC_TYPEDECL ) static_cast(node)->computeAliasCache(); + } + } + void Module::freeze() { fillGcFlags(this); + fillAliasCaches(this); frozen = true; aliasTypes.freeze(); for ( auto & st : structures.each() ) st->aliases.freeze(); diff --git a/src/ast/ast_parse.cpp b/src/ast/ast_parse.cpp index abb053fe4d..7267c794cd 100644 --- a/src/ast/ast_parse.cpp +++ b/src/ast/ast_parse.cpp @@ -68,6 +68,8 @@ DAS_CC_API das::smart_ptr get_file_access( char * pak ) { namespace das { + static recursive_mutex g_commentReadersMutex; + void applyPostRewriteMacros ( Program * program ) { program->library.foreach([&](Module * mod) -> bool { for ( const auto & pm : mod->postRewriteMacros ) { @@ -137,7 +139,7 @@ namespace das { vector & chain; }; - void getAllRequireReq ( FileInfo * fi, const FileAccessPtr & access, string& modName, vector & req, vector & chain, das_set & collected ) { + static void scanRequires ( FileInfo * fi, const FileAccessPtr & access, string& modName, vector & req, vector & chain, das_set & collected, bool * visibleEverywhere ) { ChainGuard guard(chain,fi); const char * src = nullptr; uint32_t length = 0; @@ -219,7 +221,7 @@ namespace das { if ( incInfo != fi && incInfo ) { if ( collected.find(incInfo)==collected.end() ) { collected.insert(incInfo); - getAllRequireReq(incInfo, access, incModName, req, chain, collected); + scanRequires(incInfo, access, incModName, req, chain, collected, nullptr); } } continue; @@ -316,7 +318,7 @@ namespace das { if ( info ) { if ( collected.find(info)==collected.end() ) { collected.insert(info); - getAllRequireReq(info, access, incModName, req, chain, collected); + scanRequires(info, access, incModName, req, chain, collected, nullptr); } } } @@ -352,6 +354,29 @@ namespace das { if ( !mod.empty() ) { modName = mod; // override default module name } + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#comment-readers + auto skipSpace = [&]() { + while ( src < src_end && isspaceE(src[0]) ) { + if ( src[0]=='\n' ) line ++; + src ++; + } + }; + auto takeWord = [&]( const char * word ) { + skipSpace(); + auto n = strlen(word); + if ( src + n > src_end || memcmp(src, word, n) != 0 ) return false; + if ( src + n < src_end && (isalnumE(src[n]) || src[n]=='_') ) return false; + src += n; + return true; + }; + takeWord("shared"); + if ( !takeWord("public") ) takeWord("private"); + skipSpace(); + if ( src < src_end && src[0]=='!' ) { + src ++; + if ( takeWord("inscope") && visibleEverywhere ) *visibleEverywhere = true; + } + wb = true; continue; } else { wb = true; @@ -374,10 +399,15 @@ namespace das { } } - vector getAllRequire ( FileInfo * fi, string &modName, vector & chain, const FileAccessPtr & access ) { + void getAllRequireReq ( FileInfo * fi, const FileAccessPtr & access, string& modName, vector & req, vector & chain, das_set & collected ) { + scanRequires(fi, access, modName, req, chain, collected, nullptr); + } + + vector getAllRequire ( FileInfo * fi, string &modName, vector & chain, const FileAccessPtr & access, + bool * visibleEverywhere ) { das_set collected; vector req; - getAllRequireReq(fi, access, modName, req, chain, collected); + scanRequires(fi, access, modName, req, chain, collected, visibleEverywhere); return req; } @@ -1395,6 +1425,9 @@ namespace das { for ( auto cr : commentReaders ) { parserState.g_CommentReaders.push_back(cr); } + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#comment-readers + unique_lock readersLock(g_commentReadersMutex, std::defer_lock); + if ( !commentReaders.empty() ) readersLock.lock(); if ( gen2 ) { err = das2_yyparse(scanner); das2_yylex_destroy(scanner); @@ -1816,14 +1849,6 @@ namespace das { return false; } - void buildDeferredMacroModule ( const ProgramPtr & program, ModuleGroup & libGroup, TextWriter & logs ) { - CompileEnvScope envScope(daScriptEnvironment::getBound()); - gc_active_scope gcScope(program->thisModule->module_gc_root.get()); - daScriptEnvironment::getBound()->g_Program = program; - program->thisModuleGroup = &libGroup; - program->makeMacroModule(logs); - } - void addNewModules ( ModuleGroup & libGroup, ProgramPtr program ) { program->thisModule->freeze(); libGroup.addModule(program->thisModule.release()); diff --git a/src/ast/ast_parse.h b/src/ast/ast_parse.h index 1572844023..b882bd030b 100644 --- a/src/ast/ast_parse.h +++ b/src/ast/ast_parse.h @@ -2,7 +2,8 @@ namespace das { - vector getAllRequire ( FileInfo * fi, string & modName, vector & chain, const FileAccessPtr & access ); + vector getAllRequire ( FileInfo * fi, string & modName, vector & chain, const FileAccessPtr & access, + bool * visibleEverywhere = nullptr ); ProgramPtr parseDaScriptEx ( const string & fileName, const string & moduleName, const FileAccessPtr & access, TextWriter & logs, ModuleGroup & libGroup, bool exportAll, bool isDep, CodeOfPolicies policies, bool inferAfterParse, const ModuleCacheStream & stream = ModuleCacheStream(), const ProgramPtr & prepared = nullptr, @@ -10,7 +11,6 @@ namespace das { bool aotModuleHasName ( ProgramPtr program, const ModuleInfo & mod ); bool canShareModule ( ProgramPtr program ); void addNewModules ( ModuleGroup & libGroup, ProgramPtr program ); - void buildDeferredMacroModule ( const ProgramPtr & program, ModuleGroup & libGroup, TextWriter & logs ); void recordCompiledModule ( AstSerializer * write, const FileAccessPtr & access, const string & fileName, const ProgramPtr & program, Module * module ); } diff --git a/src/ast/ast_print.cpp b/src/ast/ast_print.cpp index 54c5b32001..9c16a58d17 100644 --- a/src/ast/ast_print.cpp +++ b/src/ast/ast_print.cpp @@ -1,6 +1,7 @@ #include "daScript/misc/platform.h" #include "daScript/ast/ast.h" +#include "daScript/ast/ast_const_visitor.h" #include "daScript/ast/ast_visitor.h" #if defined(STANDALONE_MODE) @@ -22,77 +23,88 @@ namespace das { } }; - class SetPrinterFlags : public Visitor { + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers + struct PrintLevels { + bool top = false; + bool arg = false; + bool bottom = false; + }; + typedef das_hash_map PrintLevelMap; + + class SetPrinterFlags : public ConstVisitor { + public: + PrintLevelMap levels; + protected: // ExprBlock - virtual void preVisitBlockExpression ( ExprBlock * block, Expression * expr ) override { - Visitor::preVisitBlockExpression(block, expr); - expr->topLevel = true; + virtual void preVisitBlockExpression ( const ExprBlock * block, const Expression * expr ) override { + ConstVisitor::preVisitBlockExpression(block, expr); + levels[expr].top = true; } // ExprNew - virtual void preVisitNewArg ( ExprNew * call, Expression * expr , bool last ) override { - Visitor::preVisitNewArg(call,expr,last); - expr->argLevel = true; + virtual void preVisitNewArg ( const ExprNew * call, const Expression * expr , bool last ) override { + ConstVisitor::preVisitNewArg(call,expr,last); + levels[expr].arg = true; } // ExprCall - virtual void preVisitCallArg ( ExprCall * call, Expression * expr , bool last ) override { - Visitor::preVisitCallArg(call,expr,last); - expr->argLevel = true; + virtual void preVisitCallArg ( const ExprCall * call, const Expression * expr , bool last ) override { + ConstVisitor::preVisitCallArg(call,expr,last); + levels[expr].arg = true; } // ExprLooksLikeCall - virtual void preVisitLooksLikeCallArg ( ExprLooksLikeCall * call, Expression * expr , bool last ) override { - Visitor::preVisitLooksLikeCallArg(call,expr,last); - expr->argLevel = true; + virtual void preVisitLooksLikeCallArg ( const ExprLooksLikeCall * call, const Expression * expr , bool last ) override { + ConstVisitor::preVisitLooksLikeCallArg(call,expr,last); + levels[expr].arg = true; } // ExprIfThenElse - virtual void preVisit ( ExprIfThenElse * expr ) override { - Visitor::preVisit(expr); - expr->cond->argLevel = true; + virtual void preVisit ( const ExprIfThenElse * expr ) override { + ConstVisitor::preVisit(expr); + levels[expr->cond].arg = true; } // ExprWhile - virtual void preVisit ( ExprWhile * expr ) override { - Visitor::preVisit(expr); - expr->cond->argLevel = true; + virtual void preVisit ( const ExprWhile * expr ) override { + ConstVisitor::preVisit(expr); + levels[expr->cond].arg = true; } // ExprReturn - virtual void preVisit ( ExprReturn * expr ) override { - Visitor::preVisit(expr); - if ( expr->subexpr ) expr->subexpr->argLevel = true; + virtual void preVisit ( const ExprReturn * expr ) override { + ConstVisitor::preVisit(expr); + if ( expr->subexpr ) levels[expr->subexpr].arg = true; } // ExprCopy - virtual void preVisit ( ExprCopy * expr ) override { - Visitor::preVisit(expr); - if ( expr->topLevel || expr->argLevel ) - expr->right->argLevel = true; + virtual void preVisit ( const ExprCopy * expr ) override { + ConstVisitor::preVisit(expr); + if ( topOrArg(expr) ) levels[expr->right].arg = true; } // ExprClone - virtual void preVisit ( ExprClone * expr ) override { - Visitor::preVisit(expr); - if ( expr->topLevel || expr->argLevel ) - expr->right->argLevel = true; + virtual void preVisit ( const ExprClone * expr ) override { + ConstVisitor::preVisit(expr); + if ( topOrArg(expr) ) levels[expr->right].arg = true; } // ExprVar - virtual void preVisit ( ExprVar * expr ) override { - Visitor::preVisit(expr); - expr->bottomLevel = true; + virtual void preVisit ( const ExprVar * expr ) override { + ConstVisitor::preVisit(expr); + levels[expr].bottom = true; } // ExprTypeInfo - virtual void preVisit ( ExprTypeInfo * expr ) override { - Visitor::preVisit(expr); - if ( expr->subexpr ) { - expr->subexpr->argLevel = true; - } + virtual void preVisit ( const ExprTypeInfo * expr ) override { + ConstVisitor::preVisit(expr); + if ( expr->subexpr ) levels[expr->subexpr].arg = true; } // ExprArrayComprehension - virtual void preVisit ( ExprArrayComprehension * expr ) override { - Visitor::preVisit(expr); - expr->subexpr->argLevel = true; - if ( expr->exprWhere ) expr->exprWhere->argLevel = true; + virtual void preVisit ( const ExprArrayComprehension * expr ) override { + ConstVisitor::preVisit(expr); + levels[expr->subexpr].arg = true; + if ( expr->exprWhere ) levels[expr->exprWhere].arg = true; + } + bool topOrArg ( const Expression * expr ) const { + auto it = levels.find(expr); + return it != levels.end() && (it->second.top || it->second.arg); } }; - class Printer : public Visitor { + class Printer : public ConstVisitor { public: - Printer ( const Program * program = nullptr ) { + Printer ( const PrintLevelMap & lv, const Program * program = nullptr ) : levels(lv) { if ( program ) { printRef = program->options.getBoolOption("print_ref"); printVarAccess = program->options.getBoolOption("print_var_access"); @@ -120,49 +132,55 @@ namespace das { lastNewLine = ss.tellp(); } } - __forceinline static bool noBracket ( Expression * expr ) { - return expr->topLevel || expr->bottomLevel || expr->argLevel; + const PrintLevelMap & levels; + PrintLevels level ( const Expression * expr ) const { + auto it = levels.find(expr); + return it != levels.end() ? it->second : PrintLevels(); + } + bool noBracket ( const Expression * expr ) const { + auto lv = level(expr); + return lv.top || lv.bottom || lv.arg; } // can we see inside quote - virtual bool canVisitQuoteSubexpression ( ExprQuote * ) override { return true; } + virtual bool canVisitQuoteSubexpression ( const ExprQuote * ) override { return true; } // TYPE bool ET = false; - virtual void preVisit ( TypeDecl * td ) override { - Visitor::preVisit(td); + virtual void preVisit ( const TypeDecl * td ) override { + ConstVisitor::preVisit(td); ET = td->isExprType(); if ( ET ) ss << "/*["; } - virtual TypeDeclPtr visit ( TypeDecl * td ) override { + virtual void visit ( const TypeDecl * td ) override { if ( ET ) ss << "]*/"; - return Visitor::visit(td); + return ConstVisitor::visit(td); } // enumeration - virtual void preVisit ( Enumeration * enu ) override { - Visitor::preVisit(enu); + virtual void preVisit ( const Enumeration * enu ) override { + ConstVisitor::preVisit(enu); ss << "enum "; ss << (enu->isPrivate ? "private " : "public ") << enu->name << " : " << das_to_string(enu->baseType) << "\n"; if ( gen2 ) { ss << "{\n"; } } - virtual void preVisitEnumerationValue ( Enumeration * enu, const string & name, Expression * value, bool last ) override { - Visitor::preVisitEnumerationValue(enu, name, value, last); + virtual void preVisitEnumerationValue ( const Enumeration * enu, const string & name, const Expression * value, bool last ) override { + ConstVisitor::preVisitEnumerationValue(enu, name, value, last); ss << "\t" << name << " = "; } - virtual ExpressionPtr visitEnumerationValue ( Enumeration * enu, const string & name, Expression * value, bool last ) override { + virtual void visitEnumerationValue ( const Enumeration * enu, const string & name, const Expression * value, bool last ) override { if ( gen2 ) { if ( !last ) ss << ","; ss << "\n"; } else { ss << "\n"; } - return Visitor::visitEnumerationValue(enu, name, value, last); + return ConstVisitor::visitEnumerationValue(enu, name, value, last); } - virtual EnumerationPtr visit ( Enumeration * enu ) override { + virtual void visit ( const Enumeration * enu ) override { if ( gen2 ) ss << "}\n"; ss << "\n"; - return Visitor::visit(enu); + return ConstVisitor::visit(enu); } // strcuture void logAnnotationArguments(const AnnotationArgumentList & arguments) { @@ -195,8 +213,8 @@ namespace das { ss << "]\n"; } } - virtual void preVisit ( Structure * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const Structure * that ) override { + ConstVisitor::preVisit(that); logAnnotations(that->annotations); if ( that->hasDefaultInitializer ) ss << "// has default initializer " << that->name << "()\n"; if ( that->macroInterface ) ss << "[macro_interface]\n"; @@ -229,15 +247,15 @@ namespace das { ss << "] "; } } - virtual void preVisitStructureAlias ( Structure * var, const string & name, TypeDecl * at ) override { - Visitor::preVisitStructureAlias(var, name, at); + virtual void preVisitStructureAlias ( const Structure * var, const string & name, const TypeDecl * at ) override { + ConstVisitor::preVisitStructureAlias(var, name, at); ss << "\ttypedef " << name << " = " << at->describe(); if ( gen2 ) ss << ";"; ss << "\n"; } - virtual void preVisitStructureField ( Structure * that, Structure::FieldDeclaration & decl, bool last ) override { - Visitor::preVisitStructureField(that, decl, last); + virtual void preVisitStructureField ( const Structure * that, const Structure::FieldDeclaration & decl, bool last ) override { + ConstVisitor::preVisitStructureField(that, decl, last); ss << "\t"; outputVariableAnnotation(decl.annotation); if ( decl.privateField ) ss << "private "; @@ -249,27 +267,27 @@ namespace das { ss << (decl.moveSemantics ? " <- " : " = "); } } - virtual void visitStructureField ( Structure * var, Structure::FieldDeclaration & decl, bool last ) override { + virtual void visitStructureField ( const Structure * var, const Structure::FieldDeclaration & decl, bool last ) override { if ( decl.capturedConstant ) ss << " // captured constant"; if ( gen2 ) ss << ";"; ss << "\n"; - Visitor::visitStructureField(var, decl, last); + ConstVisitor::visitStructureField(var, decl, last); } - virtual StructurePtr visit ( Structure * that ) override { + virtual void visit ( const Structure * that ) override { if ( gen2 ) ss << "}\n"; ss << "\n"; - return Visitor::visit(that); + return ConstVisitor::visit(that); } // alias - virtual void preVisitAlias ( TypeDecl * td, const string & name ) override { - Visitor::preVisitAlias(td,name); + virtual void preVisitAlias ( const TypeDecl * td, const string & name ) override { + ConstVisitor::preVisitAlias(td,name); ss << "typedef " << name << " = " << td->describe(); if ( gen2 ) ss << ";"; ss << "\n\n"; } // global - virtual void preVisitGlobalLet ( const VariablePtr & var ) override { - Visitor::preVisitGlobalLet(var); + virtual void preVisitGlobalLet ( const Variable * var ) override { + ConstVisitor::preVisitGlobalLet(var); if ( printUse ) { if ( var->useFunctions.size() ) { ss << "// use functions"; @@ -298,19 +316,19 @@ namespace das { if ( printVarAccess && var->access_info_pass_mutable ) ss << "/*pass_mut*/"; ss << var->name << " : " << var->type->describe(); } - virtual VariablePtr visitGlobalLet ( const VariablePtr & var ) override { + virtual void visitGlobalLet ( const Variable * var ) override { ss << "\n\n"; - return Visitor::visitGlobalLet(var); + return ConstVisitor::visitGlobalLet(var); } - virtual void preVisitGlobalLetInit ( const VariablePtr & var, Expression * init ) override { - Visitor::preVisitGlobalLetInit(var, init); + virtual void preVisitGlobalLetInit ( const Variable * var, const Expression * init ) override { + ConstVisitor::preVisitGlobalLetInit(var, init); if ( var->init_via_move ) ss << " <- "; else if ( var->init_via_clone ) ss << " := "; else ss << " = "; } // function - virtual void preVisit ( Function * fn) override { - Visitor::preVisit(fn); + virtual void preVisit ( const Function * fn) override { + ConstVisitor::preVisit(fn); if ( fn->isFullyInferred ) { ss << "/*FULLY INFERRED*/\n"; } @@ -407,14 +425,14 @@ namespace das { ss << "def " << (fn->privateFunction ? "private " : "public ") << fn->name; if ( fn->arguments.size() ) ss << "("; } - virtual void preVisitFunctionBody ( Function * fn,Expression * expr ) override { - Visitor::preVisitFunctionBody(fn,expr); + virtual void preVisitFunctionBody ( const Function * fn,const Expression * expr ) override { + ConstVisitor::preVisitFunctionBody(fn,expr); if ( fn->arguments.size() ) ss << ")"; if ( fn->result ) ss << " : " << fn->result->describe(); if ( !gen2 ) ss << "\n"; } - virtual void preVisitArgument ( Function * fn, const VariablePtr & arg, bool last ) override { - Visitor::preVisitArgument(fn,arg,last); + virtual void preVisitArgument ( const Function * fn, const Variable * arg, bool last ) override { + ConstVisitor::preVisitArgument(fn,arg,last); if (!arg->annotation.empty()) { ss << "["; logAnnotationArguments(arg->annotation); @@ -431,26 +449,26 @@ namespace das { if ( !arg->aka.empty() ) ss << " aka " << arg->aka; ss << ":" << arg->type->describe(); } - virtual void preVisitArgumentInit ( Function * fn, const VariablePtr & arg, Expression * expr ) override { - Visitor::preVisitArgumentInit(fn,arg,expr); + virtual void preVisitArgumentInit ( const Function * fn, const Variable * arg, const Expression * expr ) override { + ConstVisitor::preVisitArgumentInit(fn,arg,expr); ss << " = "; } - virtual VariablePtr visitArgument ( Function * fn, const VariablePtr & that, bool last ) override { + virtual void visitArgument ( const Function * fn, const Variable * that, bool last ) override { if ( !last ) ss << "; "; - return Visitor::visitArgument(fn, that, last); + return ConstVisitor::visitArgument(fn, that, last); } - virtual FunctionPtr visit ( Function * fn ) override { + virtual void visit ( const Function * fn ) override { ss << "\n\n"; - return Visitor::visit(fn); + return ConstVisitor::visit(fn); } // Ref2Value - virtual void preVisit ( ExprRef2Value * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprRef2Value * expr ) override { + ConstVisitor::preVisit(expr); if ( printRef ) ss << "r2v("; } - virtual ExpressionPtr visit ( ExprRef2Value * expr ) override { + virtual void visit ( const ExprRef2Value * expr ) override { if ( printRef ) ss << ")"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // make block void describeCapture ( const vector & capture ) { @@ -471,19 +489,19 @@ namespace das { ss << "]] "; } } - virtual void preVisit ( ExprMakeBlock * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprMakeBlock * expr ) override { + ConstVisitor::preVisit(expr); if ( expr->isLambda ) ss << "@"; else if ( expr->isLocalFunction ) ss << "@@"; else ss << "$"; describeCapture(expr->capture); } // block - virtual void preVisitBlockExpression ( ExprBlock * block, Expression * expr ) override { - Visitor::preVisitBlockExpression(block, expr); + virtual void preVisitBlockExpression ( const ExprBlock * block, const Expression * expr ) override { + ConstVisitor::preVisitBlockExpression(block, expr); ss << string(tab,'\t'); } - bool needsTrailingSemicolumn ( Expression * that ) { + bool needsTrailingSemicolumn ( const Expression * that ) { if ( that->rtti_isIfThenElse() ) return false; if ( that->rtti_isFor() ) return false; if ( that->rtti_isWhile() ) return false; @@ -495,17 +513,17 @@ namespace das { } return true; } - virtual ExpressionPtr visitBlockExpression ( ExprBlock * block, Expression * that ) override { + virtual void visitBlockExpression ( const ExprBlock * block, const Expression * that ) override { if ( printCStyle || block->isClosure ) { if ( needsTrailingSemicolumn(that) ) { ss << ";"; } } newLine(); - return Visitor::visitBlockExpression(block, that); + return ConstVisitor::visitBlockExpression(block, that); } - virtual void preVisit ( ExprBlock * block ) override { - Visitor::preVisit(block); + virtual void preVisit ( const ExprBlock * block ) override { + ConstVisitor::preVisit(block); if ( block->isClosure ) { logAnnotations(block->annotations); if ( block->returnType || block->arguments.size() ) { @@ -537,7 +555,7 @@ namespace das { } else { ss << string(tab,'\t') << "{\n"; } - } else if ( block->topLevel ) { + } else if ( level(block).top ) { ss << "{\n"; } else if ( gen2 ) { ss << " {\n"; @@ -547,71 +565,71 @@ namespace das { } tab ++; } - virtual ExpressionPtr visit ( ExprBlock * block ) override { + virtual void visit ( const ExprBlock * block ) override { tab --; if ( printCStyle || block->isClosure ) ss << string(tab,'\t') << "}"; - return Visitor::visit(block); + return ConstVisitor::visit(block); } - virtual void preVisitBlockFinal ( ExprBlock * block ) override { - Visitor::preVisitBlockFinal(block); + virtual void preVisitBlockFinal ( const ExprBlock * block ) override { + ConstVisitor::preVisitBlockFinal(block); if ( printCStyle || block->isClosure ) { ss << string(tab-1,'\t') << "} finally {\n"; } else { ss << string(tab-1,'\t') << "finally\n"; } } - virtual void preVisitBlockFinalExpression ( ExprBlock * block, Expression * expr ) override { - Visitor::preVisitBlockFinalExpression(block, expr); + virtual void preVisitBlockFinalExpression ( const ExprBlock * block, const Expression * expr ) override { + ConstVisitor::preVisitBlockFinalExpression(block, expr); ss << string(tab,'\t'); } - virtual ExpressionPtr visitBlockFinalExpression ( ExprBlock * block, Expression * that ) override { + virtual void visitBlockFinalExpression ( const ExprBlock * block, const Expression * that ) override { if ( printCStyle || block->isClosure ) { if ( needsTrailingSemicolumn(that) ) { ss << ";"; } } newLine(); - return Visitor::visitBlockFinalExpression(block, that); + return ConstVisitor::visitBlockFinalExpression(block, that); } // string builder - virtual void preVisit ( ExprStringBuilder * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprStringBuilder * expr ) override { + ConstVisitor::preVisit(expr); ss << "string_builder"; if ( expr->isTempString ) ss << "_temp"; ss << "("; } - virtual ExpressionPtr visitStringBuilderElement ( ExprStringBuilder * sb, Expression * expr, bool last ) override { + virtual void visitStringBuilderElement ( const ExprStringBuilder * sb, const Expression * expr, bool last ) override { if ( !last ) ss << ", "; - return Visitor::visitStringBuilderElement(sb, expr, last); + return ConstVisitor::visitStringBuilderElement(sb, expr, last); } - virtual ExpressionPtr visit ( ExprStringBuilder * expr ) override { + virtual void visit ( const ExprStringBuilder * expr ) override { ss << ")"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // label - virtual void preVisit ( ExprReader * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprReader * expr ) override { + ConstVisitor::preVisit(expr); ss << "#" << expr->macro->name << " " << expr->sequence << " "; } // label - virtual void preVisit ( ExprLabel * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprLabel * expr ) override { + ConstVisitor::preVisit(expr); ss << "label " << expr->label << ":"; if ( !expr->comment.empty() ) { ss << " /*" << expr->comment << "*/"; } } // goto - virtual void preVisit ( ExprGoto * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprGoto * expr ) override { + ConstVisitor::preVisit(expr); ss << "goto "; if ( !expr->subexpr ) ss << "label " << expr->label; } // let - virtual void preVisit ( ExprLet * let ) override { - Visitor::preVisit(let); + virtual void preVisit ( const ExprLet * let ) override { + ConstVisitor::preVisit(let); bool isLet = true; if ( let->variables.size() ) { auto pVar = let->variables.back(); @@ -621,8 +639,8 @@ namespace das { } ss << (isLet ? "let " : "var ") << (let->inScope ? "inscope " : ""); } - virtual void preVisitLet ( ExprLet * let, const VariablePtr & var, bool last ) override { - Visitor::preVisitLet(let, var, last); + virtual void preVisitLet ( const ExprLet * let, const Variable * var, bool last ) override { + ConstVisitor::preVisitLet(let, var, last); if ( printUse && var->isAccessUnused() ) ss << " /*unused*/ "; if ( printVarAccess && var->access_ref ) ss << "/*ref*/"; if ( printVarAccess && var->access_pass ) ss << "/*pass*/"; @@ -638,29 +656,29 @@ namespace das { if ( var->single_return_via_move ) ss << "/*single_return_via_move*/"; ss << ":" << var->type->describe(); } - virtual VariablePtr visitLet ( ExprLet * let, const VariablePtr & var, bool last ) override { + virtual void visitLet ( const ExprLet * let, const Variable * var, bool last ) override { if ( !last ) ss << "; "; - return Visitor::visitLet(let, var, last); + return ConstVisitor::visitLet(let, var, last); } - virtual void preVisitLetInit ( ExprLet * let, const VariablePtr & var, Expression * expr ) override { - Visitor::preVisitLetInit(let,var,expr); + virtual void preVisitLetInit ( const ExprLet * let, const Variable * var, const Expression * expr ) override { + ConstVisitor::preVisitLetInit(let,var,expr); if ( var->init_via_move ) ss << " <- "; else if ( var->init_via_clone ) ss << " := "; else ss << " = "; } // if then else - virtual void preVisit ( ExprIfThenElse * ifte ) override { - Visitor::preVisit(ifte); + virtual void preVisit ( const ExprIfThenElse * ifte ) override { + ConstVisitor::preVisit(ifte); ss << (ifte->isStatic ? "static_if " : "if "); if ( gen2 ) ss << "( "; } - virtual void preVisitIfBlock ( ExprIfThenElse * ifte, Expression * block ) override { - Visitor::preVisitIfBlock(ifte,block); + virtual void preVisitIfBlock ( const ExprIfThenElse * ifte, const Expression * block ) override { + ConstVisitor::preVisitIfBlock(ifte,block); if ( gen2 ) ss << " )"; if ( !gen2 ) ss << "\n"; } - virtual void preVisitElseBlock ( ExprIfThenElse * ifte, Expression * block ) override { - Visitor::preVisitElseBlock(ifte, block); + virtual void preVisitElseBlock ( const ExprIfThenElse * ifte, const Expression * block ) override { + ConstVisitor::preVisitElseBlock(ifte, block); if ( gen2 ) { ss << " "; } else { @@ -674,13 +692,13 @@ namespace das { } } // try-catch - virtual void preVisit ( ExprTryCatch * tc ) override { - Visitor::preVisit(tc); + virtual void preVisit ( const ExprTryCatch * tc ) override { + ConstVisitor::preVisit(tc); ss << "try"; if ( !gen2 ) ss << "\n"; } - virtual void preVisitCatch ( ExprTryCatch * tc, Expression * block ) override { - Visitor::preVisitCatch(tc, block); + virtual void preVisitCatch ( const ExprTryCatch * tc, const Expression * block ) override { + ConstVisitor::preVisitCatch(tc, block); if ( gen2 ) { ss << " recover"; } else { @@ -688,8 +706,8 @@ namespace das { } } // for - virtual void preVisit ( ExprFor * ffor ) override { - Visitor::preVisit(ffor); + virtual void preVisit ( const ExprFor * ffor ) override { + ConstVisitor::preVisit(ffor); ss << "for "; if ( gen2 ) ss << "( "; bool first = true; @@ -699,126 +717,126 @@ namespace das { } ss << " in "; } - virtual void preVisitForBody ( ExprFor * ffor, Expression * body ) override { - Visitor::preVisitForBody(ffor, body); + virtual void preVisitForBody ( const ExprFor * ffor, const Expression * body ) override { + ConstVisitor::preVisitForBody(ffor, body); if ( gen2 ) ss << " )"; if ( !gen2 ) ss << "\n"; } - virtual ExpressionPtr visitForSource ( ExprFor * ffor, Expression * that , bool last ) override { + virtual void visitForSource ( const ExprFor * ffor, const Expression * that , bool last ) override { if ( !last ) ss << ","; - return Visitor::visitForSource(ffor, that, last); + return ConstVisitor::visitForSource(ffor, that, last); } // with - virtual void preVisit ( ExprWith * wh ) override { - Visitor::preVisit(wh); + virtual void preVisit ( const ExprWith * wh ) override { + ConstVisitor::preVisit(wh); ss << "with "; // module flavor is gen2-only surface, but generated nodes can land in a // gen1 program (the inliner's scope wraps) - always parenthesize it if ( gen2 || wh->isModuleWith() ) ss << "( "; if ( wh->isModuleWith() ) ss << "module " << wh->moduleName; } - virtual void preVisitWithBody ( ExprWith * wh, Expression * body ) override { - Visitor::preVisitWithBody(wh,body); + virtual void preVisitWithBody ( const ExprWith * wh, const Expression * body ) override { + ConstVisitor::preVisitWithBody(wh,body); if ( gen2 || wh->isModuleWith() ) ss << " )"; if ( !gen2 && !wh->isModuleWith() ) ss << "\n"; } // with alias - virtual bool canVisitWithAliasSubexpression ( ExprAssume * ) override { + virtual bool canVisitWithAliasSubexpression ( const ExprAssume * ) override { return true; } - virtual void preVisit ( ExprAssume * wh ) override { - Visitor::preVisit(wh); + virtual void preVisit ( const ExprAssume * wh ) override { + ConstVisitor::preVisit(wh); ss << "assume "; if ( wh->assumeType ) ss << "type "; ss << wh->alias << " = "; if ( wh->assumeType ) ss << wh->assumeType->describe(); } // tag - virtual void preVisit ( ExprTag * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprTag * expr ) override { + ConstVisitor::preVisit(expr); if ( expr->name=="...") { ss << "..."; } else { ss << "$" << expr->name << "("; } } - virtual void preVisitTagValue ( ExprTag * expr, Expression * value ) override { - Visitor::preVisitTagValue(expr,value); + virtual void preVisitTagValue ( const ExprTag * expr, const Expression * value ) override { + ConstVisitor::preVisitTagValue(expr,value); if ( expr->name!="...") { ss << ")("; } } - virtual ExpressionPtr visit ( ExprTag * expr ) override { + virtual void visit ( const ExprTag * expr ) override { if ( expr->name!="...") { ss << ")"; } - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // while - virtual void preVisit ( ExprWhile * wh ) override { - Visitor::preVisit(wh); + virtual void preVisit ( const ExprWhile * wh ) override { + ConstVisitor::preVisit(wh); ss << "while "; if ( gen2 ) ss << "( "; } - virtual void preVisitWhileBody ( ExprWhile * wh, Expression * body ) override { - Visitor::preVisitWhileBody(wh,body); + virtual void preVisitWhileBody ( const ExprWhile * wh, const Expression * body ) override { + ConstVisitor::preVisitWhileBody(wh,body); if ( gen2 ) ss << " )"; if ( !gen2 ) ss << "\n"; } // while - virtual void preVisit ( ExprUnsafe * wh ) override { - Visitor::preVisit(wh); + virtual void preVisit ( const ExprUnsafe * wh ) override { + ConstVisitor::preVisit(wh); ss << "unsafe"; if ( !gen2 ) ss << "\n"; } // call - virtual void preVisit ( ExprCall * call ) override { - Visitor::preVisit(call); + virtual void preVisit ( const ExprCall * call ) override { + ConstVisitor::preVisit(call); ss << call->name; if ( printAliases && call->doesNotNeedSp ) ss << " /*no_sp*/ "; ss << "("; } - virtual ExpressionPtr visitCallArg ( ExprCall * call, Expression * arg, bool last ) override { + virtual void visitCallArg ( const ExprCall * call, const Expression * arg, bool last ) override { if ( !last ) ss << ","; - return Visitor::visitCallArg(call, arg, last); + return ConstVisitor::visitCallArg(call, arg, last); } - virtual ExpressionPtr visit ( ExprCall * c ) override { + virtual void visit ( const ExprCall * c ) override { ss << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } // named call - virtual void preVisit ( ExprNamedCall * call ) override { - Visitor::preVisit(call); + virtual void preVisit ( const ExprNamedCall * call ) override { + ConstVisitor::preVisit(call); ss << call->name << "("; } - virtual void preVisitNamedCallArg ( ExprNamedCall * call, MakeFieldDecl * arg, bool last ) override { + virtual void preVisitNamedCallArg ( const ExprNamedCall * call, const MakeFieldDecl * arg, bool last ) override { if ((*call->arguments)[0] == arg) { if (call->nonNamedArguments.size() > 0) ss << ","; ss << "["; } - Visitor::preVisitNamedCallArg(call, arg, last); + ConstVisitor::preVisitNamedCallArg(call, arg, last); ss << arg->name << (arg->moveSemantics ? "<-" : "=" ); } - virtual MakeFieldDeclPtr visitNamedCallArg ( ExprNamedCall * call, MakeFieldDecl * arg, bool last ) override { + virtual void visitNamedCallArg ( const ExprNamedCall * call, const MakeFieldDecl * arg, bool last ) override { if ( !last ) ss << ","; - return Visitor::visitNamedCallArg(call, arg, last); + return ConstVisitor::visitNamedCallArg(call, arg, last); } - virtual ExpressionPtr visit ( ExprNamedCall * c ) override { + virtual void visit ( const ExprNamedCall * c ) override { ss << "])"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } // looks like call - virtual void preVisit ( ExprCallMacro * call ) override { - Visitor::preVisit(call); + virtual void preVisit ( const ExprCallMacro * call ) override { + ConstVisitor::preVisit(call); ss << call->name << "("; } - virtual ExpressionPtr visit ( ExprCallMacro * c ) override { + virtual void visit ( const ExprCallMacro * c ) override { ss << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } // looks like call - virtual void preVisit ( ExprLooksLikeCall * call ) override { - Visitor::preVisit(call); + virtual void preVisit ( const ExprLooksLikeCall * call ) override { + ConstVisitor::preVisit(call); ss << call->name; if ( call->rtti_isInvoke() ) { auto * inv = (ExprInvoke *) call; @@ -827,24 +845,24 @@ namespace das { } ss << "("; } - virtual ExpressionPtr visitLooksLikeCallArg ( ExprLooksLikeCall * call, Expression * arg, bool last ) override { + virtual void visitLooksLikeCallArg ( const ExprLooksLikeCall * call, const Expression * arg, bool last ) override { if ( !last ) ss << ","; - return Visitor::visitLooksLikeCallArg(call, arg, last); + return ConstVisitor::visitLooksLikeCallArg(call, arg, last); } - virtual ExpressionPtr visit ( ExprLooksLikeCall * c ) override { + virtual void visit ( const ExprLooksLikeCall * c ) override { ss << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } // const - virtual ExpressionPtr visit(ExprFakeContext * c) override { + virtual void visit(const ExprFakeContext * c) override { ss << "__context__"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit(ExprFakeLineInfo * c) override { + virtual void visit(const ExprFakeLineInfo * c) override { ss << "__lineinfo__"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstPtr * c ) override { + virtual void visit ( const ExprConstPtr * c ) override { if ( c->ptrType ) { ss << "const_pointer<" << c->ptrType->describe() << ">("; } @@ -856,48 +874,48 @@ namespace das { if ( c->ptrType ) { ss << ")"; } - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstEnumeration * c ) override { + virtual void visit ( const ExprConstEnumeration * c ) override { if ( c->enumType->module && !c->enumType->module->name.empty() ) { ss << c->enumType->module->name << "::"; } ss << c->enumType->name << "." << c->text; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt * c ) override { + virtual void visit ( const ExprConstInt * c ) override { ss << c->getValue(); - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt8 * c ) override { + virtual void visit ( const ExprConstInt8 * c ) override { ss << int32_t(c->getValue()) << "/*i8*/"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt8 * c ) override { + virtual void visit ( const ExprConstUInt8 * c ) override { ss << "0x" << HEX << uint32_t(c->getValue()) << DEC << "u8"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt16 * c ) override { + virtual void visit ( const ExprConstInt16 * c ) override { ss << int32_t(c->getValue()) << "/*i16*/"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt16 * c ) override { + virtual void visit ( const ExprConstUInt16 * c ) override { ss << "0x" << HEX << uint32_t(c->getValue()) << DEC << "/*u16*/"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt64 * c ) override { + virtual void visit ( const ExprConstInt64 * c ) override { ss << c->getValue(); - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt64 * c ) override { + virtual void visit ( const ExprConstUInt64 * c ) override { ss << "0x" << HEX << c->getValue() << DEC; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt * c ) override { + virtual void visit ( const ExprConstUInt * c ) override { ss << "0x" << HEX << c->getValue() << DEC; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstBitfield * c ) override { + virtual void visit ( const ExprConstBitfield * c ) override { string name; if ( c->bitfieldType && !c->bitfieldType->alias.empty() ) { name = c->bitfieldType->findBitfieldName(c->getValue()); @@ -914,103 +932,103 @@ namespace das { } ss << "(0x" << HEX << c->getValue() << DEC << ")"; } - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstBool * c ) override { + virtual void visit ( const ExprConstBool * c ) override { ss << (c->getValue() ? "true" : "false"); - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstDouble * c ) override { + virtual void visit ( const ExprConstDouble * c ) override { ss << c->getValue() << "lf"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstFloat * c ) override { + virtual void visit ( const ExprConstFloat * c ) override { ss << c->getValue() << "f"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstFloat16 * c ) override { + virtual void visit ( const ExprConstFloat16 * c ) override { ss << c->getValue().toFloat() << "h"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstString * c ) override { + virtual void visit ( const ExprConstString * c ) override { ss << "\"" << escapeString(c->text) << "\""; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt2 * c ) override { + virtual void visit ( const ExprConstInt2 * c ) override { auto val = c->getValue(); ss << "int2(" << val.x << "," << val.y << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstRange * c ) override { + virtual void visit ( const ExprConstRange * c ) override { auto val = c->getValue(); ss << "range(" << val.from << "," << val.to << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstRange64 * c ) override { + virtual void visit ( const ExprConstRange64 * c ) override { auto val = c->getValue(); ss << "range64(" << val.from << "," << val.to << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt3 * c ) override { + virtual void visit ( const ExprConstInt3 * c ) override { auto val = c->getValue(); ss << "int3(" << val.x << "," << val.y << "," << val.z << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstInt4 * c ) override { + virtual void visit ( const ExprConstInt4 * c ) override { auto val = c->getValue(); ss << "int4(" << val.x << "," << val.y << "," << val.z << "," << val.w << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt2 * c ) override { + virtual void visit ( const ExprConstUInt2 * c ) override { auto val = c->getValue(); ss << "uint2(" << val.x << "," << val.y << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstURange * c ) override { + virtual void visit ( const ExprConstURange * c ) override { auto val = c->getValue(); ss << "urange(" << val.from << "," << val.to << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstURange64 * c ) override { + virtual void visit ( const ExprConstURange64 * c ) override { auto val = c->getValue(); ss << "urange64(" << val.from << "," << val.to << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt3 * c ) override { + virtual void visit ( const ExprConstUInt3 * c ) override { auto val = c->getValue(); ss << "uint3(" << val.x << "," << val.y << "," << val.z << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstUInt4 * c ) override { + virtual void visit ( const ExprConstUInt4 * c ) override { auto val = c->getValue(); ss << "uint4(" << val.x << "," << val.y << "," << val.z << "," << val.w << ")"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstFloat2 * c ) override { + virtual void visit ( const ExprConstFloat2 * c ) override { auto val = c->getValue(); ss << "float2(" << val.x << "f," << val.y << "f)"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstFloat3 * c ) override { + virtual void visit ( const ExprConstFloat3 * c ) override { auto val = c->getValue(); ss << "float3(" << val.x << "f," << val.y << "f," << val.z << "f)"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } - virtual ExpressionPtr visit ( ExprConstFloat4 * c ) override { + virtual void visit ( const ExprConstFloat4 * c ) override { auto val = c->getValue(); ss << "float4(" << val.x << "f," << val.y << "f," << val.z << "f," << val.w << "f)"; - return Visitor::visit(c); + return ConstVisitor::visit(c); } // var - virtual ExpressionPtr visit ( ExprVar * var ) override { + virtual void visit ( const ExprVar * var ) override { if ( printRef && var->r2v ) ss << "@"; if ( printRef && var->r2cr ) ss << "$"; if ( printRef && var->write ) ss << "#"; ss << var->name; - return Visitor::visit(var); + return ConstVisitor::visit(var); } // swizzle - virtual ExpressionPtr visit ( ExprSwizzle * expr ) override { + virtual void visit ( const ExprSwizzle * expr ) override { ss << (expr->no_promotion ? "!." : "."); if ( printRef && expr->r2v ) ss << "@"; if ( printRef && expr->r2cr ) ss << "$"; @@ -1032,50 +1050,50 @@ namespace das { vector dummy; if ( !TypeDecl::buildSwizzleMask(expr->mask, dim, dummy) ) { ss << "/*invalid swizzle*/"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } } } - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // field - virtual ExpressionPtr visit ( ExprField * field ) override { + virtual void visit ( const ExprField * field ) override { if ( printRef && field->r2v ) ss << "@"; if ( printRef && field->r2cr ) ss << "$"; if ( printRef && field->write ) ss << "#"; ss << (field->no_promotion ? "!." : ".") << field->name; - return Visitor::visit(field); + return ConstVisitor::visit(field); } - virtual ExpressionPtr visit ( ExprSafeField * field ) override { + virtual void visit ( const ExprSafeField * field ) override { if ( printRef && field->r2v ) ss << "@"; if ( printRef && field->r2cr ) ss << "$"; if ( printRef && field->write ) ss << "#"; ss << (field->no_promotion ? "!?." : ".?") << field->name; - return Visitor::visit(field); + return ConstVisitor::visit(field); } - virtual ExpressionPtr visit ( ExprIsVariant * field ) override { + virtual void visit ( const ExprIsVariant * field ) override { if ( printRef && field->r2v ) ss << "@"; if ( printRef && field->r2cr ) ss << "$"; if ( printRef && field->write ) ss << "#"; ss << (field->no_promotion ? " !is " : " is ") << field->name; - return Visitor::visit(field); + return ConstVisitor::visit(field); } - virtual ExpressionPtr visit ( ExprAsVariant * field ) override { + virtual void visit ( const ExprAsVariant * field ) override { if ( printRef && field->r2v ) ss << "@"; if ( printRef && field->r2cr ) ss << "$"; if ( printRef && field->write ) ss << "#"; ss << (field->no_promotion ? " !as " : " as ") << field->name; - return Visitor::visit(field); + return ConstVisitor::visit(field); } - virtual ExpressionPtr visit ( ExprSafeAsVariant * field ) override { + virtual void visit ( const ExprSafeAsVariant * field ) override { if ( printRef && field->r2v ) ss << "@"; if ( printRef && field->r2cr ) ss << "$"; if ( printRef && field->write ) ss << "#"; ss << (field->no_promotion ? " !?as " : " ?as ") << field->name; - return Visitor::visit(field); + return ConstVisitor::visit(field); } // addr - virtual void preVisit ( ExprAddr * expr ) override { + virtual void preVisit ( const ExprAddr * expr ) override { ss << "@@"; if ( expr->funcType ) { ss << "<" << expr->funcType->describe() << ">"; @@ -1083,35 +1101,35 @@ namespace das { ss << expr->target; } // ptr2ref - virtual void preVisit ( ExprPtr2Ref * ptr2ref ) override { - Visitor::preVisit(ptr2ref); + virtual void preVisit ( const ExprPtr2Ref * ptr2ref ) override { + ConstVisitor::preVisit(ptr2ref); ss << "deref("; } - virtual ExpressionPtr visit ( ExprPtr2Ref * ptr2ref ) override { + virtual void visit ( const ExprPtr2Ref * ptr2ref ) override { ss << ")"; - return Visitor::visit(ptr2ref); + return ConstVisitor::visit(ptr2ref); } // ref2ptr - virtual void preVisit ( ExprRef2Ptr * ptr2ref ) override { - Visitor::preVisit(ptr2ref); + virtual void preVisit ( const ExprRef2Ptr * ptr2ref ) override { + ConstVisitor::preVisit(ptr2ref); ss << "addr("; } - virtual ExpressionPtr visit ( ExprRef2Ptr * ptr2ref ) override { + virtual void visit ( const ExprRef2Ptr * ptr2ref ) override { ss << ")"; - return Visitor::visit(ptr2ref); + return ConstVisitor::visit(ptr2ref); } // delete - virtual void preVisit ( ExprDelete * edel ) override { - Visitor::preVisit(edel); + virtual void preVisit ( const ExprDelete * edel ) override { + ConstVisitor::preVisit(edel); ss << "delete "; if ( edel->native ) ss << "/*native*/ "; } - virtual void preVisitDeleteSizeExpression ( ExprDelete *, Expression * ) override { + virtual void preVisitDeleteSizeExpression ( const ExprDelete *, const Expression * ) override { ss << ", rtti.size = "; } // cast - virtual void preVisit ( ExprCast * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprCast * expr ) override { + ConstVisitor::preVisit(expr); if ( expr->reinterpret ) { ss << "reinterpret"; } else if ( expr->upcast ) { @@ -1122,8 +1140,8 @@ namespace das { ss << "<" << expr->castType->describe() << "> "; } // ascend - virtual void preVisit ( ExprAscend * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprAscend * expr ) override { + ConstVisitor::preVisit(expr); if ( expr->ascType ) { ss << "new<" << expr->ascType->describe() << "> "; } else { @@ -1131,8 +1149,8 @@ namespace das { } } // new - virtual void preVisit ( ExprNew * enew ) override { - Visitor::preVisit(enew); + virtual void preVisit ( const ExprNew * enew ) override { + ConstVisitor::preVisit(enew); if ( enew->typeexpr ) { ss << "new " << enew->typeexpr->describe(); } else { @@ -1140,171 +1158,171 @@ namespace das { } if ( enew->initializer ) ss << "("; } - virtual ExpressionPtr visitNewArg ( ExprNew * call, Expression * arg, bool last ) override { + virtual void visitNewArg ( const ExprNew * call, const Expression * arg, bool last ) override { if ( !last ) ss << ","; - return Visitor::visitNewArg(call, arg, last); + return ConstVisitor::visitNewArg(call, arg, last); } - virtual ExpressionPtr visit ( ExprNew * enew ) override { + virtual void visit ( const ExprNew * enew ) override { if ( enew->initializer ) ss << ")"; - return Visitor::visit(enew); + return ConstVisitor::visit(enew); } // null coaelescing - virtual void preVisitNullCoaelescingDefault ( ExprNullCoalescing * nc, Expression * expr ) override { - Visitor::preVisitNullCoaelescingDefault(nc,expr); + virtual void preVisitNullCoaelescingDefault ( const ExprNullCoalescing * nc, const Expression * expr ) override { + ConstVisitor::preVisitNullCoaelescingDefault(nc,expr); ss << (nc->no_promotion ? " !?? " : " ?? "); } // at - virtual void preVisitAtIndex ( ExprAt * expr, Expression * index ) override { - Visitor::preVisitAtIndex(expr, index); + virtual void preVisitAtIndex ( const ExprAt * expr, const Expression * index ) override { + ConstVisitor::preVisitAtIndex(expr, index); if ( printRef && expr->r2v ) ss << "@"; if ( printRef && expr->r2cr ) ss << "$"; if ( printRef && expr->write ) ss << "#"; ss << (expr->no_promotion ? "![" : "["); } - virtual ExpressionPtr visit ( ExprAt * that ) override { + virtual void visit ( const ExprAt * that ) override { ss << "]"; - return Visitor::visit(that); + return ConstVisitor::visit(that); } // safe at - virtual void preVisitSafeAtIndex ( ExprSafeAt * expr, Expression * index ) override { - Visitor::preVisitAtIndex(expr, index); + virtual void preVisitSafeAtIndex ( const ExprSafeAt * expr, const Expression * index ) override { + ConstVisitor::preVisitAtIndex(expr, index); if ( printRef && expr->r2v ) ss << "@"; if ( printRef && expr->r2cr ) ss << "$"; if ( printRef && expr->write ) ss << "#"; ss << (expr->no_promotion ? "!?[" : "?["); } - virtual ExpressionPtr visit ( ExprSafeAt * that ) override { + virtual void visit ( const ExprSafeAt * that ) override { ss << "]"; - return Visitor::visit(that); + return ConstVisitor::visit(that); } // op1 - virtual void preVisit ( ExprOp1 * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const ExprOp1 * that ) override { + ConstVisitor::preVisit(that); if ( that->op!="+++" && that->op!="---" ) { ss << that->op; } - if ( !noBracket(that) && !that->subexpr->bottomLevel ) ss << "("; + if ( !noBracket(that) && !level(that->subexpr).bottom ) ss << "("; } - virtual ExpressionPtr visit ( ExprOp1 * that ) override { + virtual void visit ( const ExprOp1 * that ) override { if ( that->op=="+++" || that->op=="---" ) { ss << that->op[0] << that->op[1]; } - if ( !noBracket(that) && !that->subexpr->bottomLevel ) ss << ")"; - return Visitor::visit(that); + if ( !noBracket(that) && !level(that->subexpr).bottom ) ss << ")"; + return ConstVisitor::visit(that); } // op2 - virtual void preVisit ( ExprOp2 * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const ExprOp2 * that ) override { + ConstVisitor::preVisit(that); if ( !noBracket(that) ) ss << "("; } - virtual void preVisitRight ( ExprOp2 * op2, Expression * right ) override { - Visitor::preVisitRight(op2,right); + virtual void preVisitRight ( const ExprOp2 * op2, const Expression * right ) override { + ConstVisitor::preVisitRight(op2,right); ss << " " << op2->op << " "; } - virtual ExpressionPtr visit ( ExprOp2 * that ) override { + virtual void visit ( const ExprOp2 * that ) override { if ( !noBracket(that) ) ss << ")"; - return Visitor::visit(that); + return ConstVisitor::visit(that); } // op3 - virtual void preVisit ( ExprOp3 * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const ExprOp3 * that ) override { + ConstVisitor::preVisit(that); if ( !noBracket(that) ) ss << "("; } - virtual void preVisitLeft ( ExprOp3 * that, Expression * left ) override { - Visitor::preVisitLeft(that,left); + virtual void preVisitLeft ( const ExprOp3 * that, const Expression * left ) override { + ConstVisitor::preVisitLeft(that,left); ss << " ? "; } - virtual void preVisitRight ( ExprOp3 * that, Expression * right ) override { - Visitor::preVisitRight(that,right); + virtual void preVisitRight ( const ExprOp3 * that, const Expression * right ) override { + ConstVisitor::preVisitRight(that,right); ss << " : "; } - virtual ExpressionPtr visit ( ExprOp3 * that ) override { + virtual void visit ( const ExprOp3 * that ) override { if ( !noBracket(that) ) ss << ")"; - return Visitor::visit(that); + return ConstVisitor::visit(that); } // copy & move, clone - virtual void preVisitRight ( ExprCopy * that, Expression * right ) override { - Visitor::preVisitRight(that,right); + virtual void preVisitRight ( const ExprCopy * that, const Expression * right ) override { + ConstVisitor::preVisitRight(that,right); ss << (that->no_promotion ? " !== " : " = "); } - virtual void preVisitRight ( ExprMove * that, Expression * right ) override { - Visitor::preVisitRight(that,right); + virtual void preVisitRight ( const ExprMove * that, const Expression * right ) override { + ConstVisitor::preVisitRight(that,right); ss << (that->no_promotion ? " !<- " : " <- "); } - virtual void preVisitRight ( ExprClone * that, Expression * right ) override { - Visitor::preVisitRight(that,right); + virtual void preVisitRight ( const ExprClone * that, const Expression * right ) override { + ConstVisitor::preVisitRight(that,right); ss << (that->no_promotion ? " !:= " : " := "); } // return - virtual void preVisit ( ExprReturn * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprReturn * expr ) override { + ConstVisitor::preVisit(expr); ss << "return "; if ( expr->fromYield ) ss << "/*yield*/ "; if ( expr->moveSemantics ) ss << "<- "; } // yield - virtual void preVisit ( ExprYield * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprYield * expr ) override { + ConstVisitor::preVisit(expr); ss << "yield "; if ( expr->moveSemantics ) ss << "<- "; } // break - virtual void preVisit ( ExprBreak * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const ExprBreak * that ) override { + ConstVisitor::preVisit(that); ss << "break"; } // continue - virtual void preVisit ( ExprContinue * that ) override { - Visitor::preVisit(that); + virtual void preVisit ( const ExprContinue * that ) override { + ConstVisitor::preVisit(that); ss << "continue"; } // typedecl - virtual void preVisit ( ExprTypeDecl * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprTypeDecl * expr ) override { + ConstVisitor::preVisit(expr); ss << "type<" << *expr->typeexpr << ">"; } // typeinfo - virtual void preVisit ( ExprTypeInfo * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprTypeInfo * expr ) override { + ConstVisitor::preVisit(expr); ss << "typeinfo(" << expr->trait << " "; if ( !expr->subexpr ) { ss << "type<" << *expr->typeexpr << ">"; } } - virtual ExpressionPtr visit ( ExprTypeInfo * expr ) override { + virtual void visit ( const ExprTypeInfo * expr ) override { ss << ")"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // is - virtual void preVisitType ( ExprIs * expr, TypeDecl * decl ) override { - Visitor::preVisit(expr); + virtual void preVisitType ( const ExprIs * expr, const TypeDecl * decl ) override { + ConstVisitor::preVisit(expr); ss << (expr->no_promotion ? " !is type<" : " is type<") << decl->describe(TypeDecl::DescribeExtra::no, TypeDecl::DescribeContracts::yes) << ">"; } // make variant - virtual void preVisit ( ExprMakeVariant * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprMakeVariant * expr ) override { + ConstVisitor::preVisit(expr); ss << "[["; if ( expr->type ) { ss << expr->type->describe() << " "; } } - virtual void preVisitMakeVariantField ( ExprMakeVariant * expr, int index, MakeFieldDecl * decl, bool last ) override { - Visitor::preVisitMakeVariantField(expr,index,decl,last); + virtual void preVisitMakeVariantField ( const ExprMakeVariant * expr, int index, const MakeFieldDecl * decl, bool last ) override { + ConstVisitor::preVisitMakeVariantField(expr,index,decl,last); ss << decl->name << (decl->moveSemantics ? " <- " : " = "); } - virtual MakeFieldDeclPtr visitMakeVariantField ( ExprMakeVariant * expr, int index, MakeFieldDecl * decl, bool last ) override { + virtual void visitMakeVariantField ( const ExprMakeVariant * expr, int index, const MakeFieldDecl * decl, bool last ) override { if (!last) ss << "; "; - return Visitor::visitMakeVariantField(expr,index,decl,last); + return ConstVisitor::visitMakeVariantField(expr,index,decl,last); } - virtual ExpressionPtr visit ( ExprMakeVariant * expr ) override { + virtual void visit ( const ExprMakeVariant * expr ) override { ss << "]]"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // make structure - virtual void preVisit ( ExprMakeStruct * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprMakeStruct * expr ) override { + ConstVisitor::preVisit(expr); if ( gen2 ) { if ( expr->structs.empty() ) { ss << "default<"; @@ -1340,22 +1358,22 @@ namespace das { } } } - virtual void preVisitMakeStructureField ( ExprMakeStruct * expr, int index, MakeFieldDecl * decl, bool last ) override { - Visitor::preVisitMakeStructureField(expr,index,decl,last); + virtual void preVisitMakeStructureField ( const ExprMakeStruct * expr, int index, const MakeFieldDecl * decl, bool last ) override { + ConstVisitor::preVisitMakeStructureField(expr,index,decl,last); ss << decl->name << (decl->moveSemantics ? " <- " : " = "); } - virtual MakeFieldDeclPtr visitMakeStructureField ( ExprMakeStruct * expr, int index, MakeFieldDecl * decl, bool last ) override { + virtual void visitMakeStructureField ( const ExprMakeStruct * expr, int index, const MakeFieldDecl * decl, bool last ) override { if ( !last ) ss << ", "; - return Visitor::visitMakeStructureField(expr,index,decl,last); + return ConstVisitor::visitMakeStructureField(expr,index,decl,last); } - virtual void visitMakeStructureIndex ( ExprMakeStruct * expr, int index, bool lastField ) override { + virtual void visitMakeStructureIndex ( const ExprMakeStruct * expr, int index, bool lastField ) override { if ( !lastField ) ss << "; "; - Visitor::visitMakeStructureIndex(expr, index, lastField); + ConstVisitor::visitMakeStructureIndex(expr, index, lastField); } - virtual void preVisitMakeStructureBlock ( ExprMakeStruct *, Expression * ) override { + virtual void preVisitMakeStructureBlock ( const ExprMakeStruct *, const Expression * ) override { ss << " where "; } - virtual ExpressionPtr visit ( ExprMakeStruct * expr ) override { + virtual void visit ( const ExprMakeStruct * expr ) override { if ( gen2 ) { if ( !expr->structs.empty() ) { ss << ")"; @@ -1363,11 +1381,11 @@ namespace das { } else { ss << "]]"; } - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // make tuple - virtual void preVisit ( ExprMakeTuple * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprMakeTuple * expr ) override { + ConstVisitor::preVisit(expr); if ( gen2 ) { ss << "tuple"; if ( expr->type ) { @@ -1386,21 +1404,21 @@ namespace das { ss << " "; } } - virtual ExpressionPtr visitMakeTupleIndex ( ExprMakeTuple * expr, int index, Expression * init, bool lastField ) override { + virtual void visitMakeTupleIndex ( const ExprMakeTuple * expr, int index, const Expression * init, bool lastField ) override { if ( !lastField ) ss << ","; - return Visitor::visitMakeTupleIndex(expr, index, init, lastField); + return ConstVisitor::visitMakeTupleIndex(expr, index, init, lastField); } - virtual ExpressionPtr visit ( ExprMakeTuple * expr ) override { + virtual void visit ( const ExprMakeTuple * expr ) override { if ( gen2 ) { ss << ")"; } else { ss << "]]"; } - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // make array - virtual void preVisit ( ExprMakeArray * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprMakeArray * expr ) override { + ConstVisitor::preVisit(expr); if ( gen2 ) { // if ( expr->type ) { ss << "/*" << expr->type->describe() << "*/ "; } ss << "fixed_array"; @@ -1420,19 +1438,19 @@ namespace das { ss << " "; } } - virtual ExpressionPtr visitMakeArrayIndex ( ExprMakeArray * expr, int index, Expression * init, bool lastField ) override { + virtual void visitMakeArrayIndex ( const ExprMakeArray * expr, int index, const Expression * init, bool lastField ) override { if ( !lastField ) { ss << (gen2 ? ", " : "; "); } - return Visitor::visitMakeArrayIndex(expr, index, init, lastField); + return ConstVisitor::visitMakeArrayIndex(expr, index, init, lastField); } - virtual ExpressionPtr visit ( ExprMakeArray * expr ) override { + virtual void visit ( const ExprMakeArray * expr ) override { ss << (gen2 ? ")" : "]]"); - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // array comprehension - virtual void preVisit ( ExprArrayComprehension * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprArrayComprehension * expr ) override { + ConstVisitor::preVisit(expr); if ( expr->generatorSyntax ) { ss << "[["; } else if ( expr->tableSyntax ) { @@ -1441,15 +1459,15 @@ namespace das { ss << "[{"; } } - virtual void preVisitArrayComprehensionSubexpr ( ExprArrayComprehension * expr, Expression * subexpr ) override { - Visitor::preVisitArrayComprehensionSubexpr(expr, subexpr); + virtual void preVisitArrayComprehensionSubexpr ( const ExprArrayComprehension * expr, const Expression * subexpr ) override { + ConstVisitor::preVisitArrayComprehensionSubexpr(expr, subexpr); ss << "; "; } - virtual void preVisitArrayComprehensionWhere ( ExprArrayComprehension * expr, Expression * where ) override { - Visitor::preVisitArrayComprehensionWhere(expr, where); + virtual void preVisitArrayComprehensionWhere ( const ExprArrayComprehension * expr, const Expression * where ) override { + ConstVisitor::preVisitArrayComprehensionWhere(expr, where); ss << "; where "; } - virtual ExpressionPtr visit ( ExprArrayComprehension * expr ) override { + virtual void visit ( const ExprArrayComprehension * expr ) override { if ( expr->generatorSyntax ) { ss << "]]"; } else if ( expr->tableSyntax ) { @@ -1457,16 +1475,16 @@ namespace das { } else { ss << "}]"; } - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } // quote - virtual void preVisit ( ExprQuote * expr ) override { - Visitor::preVisit(expr); + virtual void preVisit ( const ExprQuote * expr ) override { + ConstVisitor::preVisit(expr); ss << "quote("; } - virtual ExpressionPtr visit ( ExprQuote * expr ) override { + virtual void visit ( const ExprQuote * expr ) override { ss << ")"; - return Visitor::visit(expr); + return ConstVisitor::visit(expr); } protected: TextWriter ss; @@ -1482,18 +1500,25 @@ namespace das { ClearPrinterFlags cflags; visit(cflags); SetPrinterFlags pflags; - visit(pflags); + constVisitProgram(pflags, this, false); + for ( auto & [expr, lv] : pflags.levels ) { + auto node = const_cast(expr); + node->topLevel = lv.top; + node->argLevel = lv.arg; + node->bottomLevel = lv.bottom; + } #endif } + static void printVisit ( const Expression & expr, ConstVisitor & vis ) { expr.visit(vis); } + static void printVisit ( const Function & func, ConstVisitor & vis ) { constVisitFunction(vis, &func); } + template __forceinline StringWriter& print ( StringWriter& stream, const TT & value ) { - ClearPrinterFlags cflags; - const_cast(value).visit(cflags); SetPrinterFlags flags; - const_cast(value).visit(flags); - Printer log(nullptr); - const_cast(value).visit(log); + printVisit(value, flags); + Printer log(flags.levels); + printVisit(value, log); stream << log.str(); return stream; } @@ -1509,12 +1534,10 @@ namespace das { }, "*"); if (any) stream << "\n"; bool logGenerics = program.options.getBoolOption("log_generics"); - ClearPrinterFlags cflags; - const_cast(program).visit(cflags, logGenerics); SetPrinterFlags flags; - const_cast(program).visit(flags, logGenerics); - Printer log(&program); - const_cast(program).visit(log, logGenerics); + constVisitProgram(flags, &program, logGenerics); + Printer log(flags.levels, &program); + constVisitProgram(log, &program, logGenerics); stream << log.str(); return stream; } diff --git a/src/ast/ast_unused.cpp b/src/ast/ast_unused.cpp index 10dde257bc..6976a073d1 100644 --- a/src/ast/ast_unused.cpp +++ b/src/ast/ast_unused.cpp @@ -7,12 +7,6 @@ namespace das { - // a global of a frozen (already compiled) module is read-only: module jobs that require it - // must not stamp its flags. src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers - static inline bool isFrozenGlobal ( const Variable * var ) { - return var->module && var->module->frozen; - } - class TrackVariableFlags : public Visitor { protected: virtual bool canVisitFunction ( Function * fun ) override { diff --git a/src/ast/dyn_modules.cpp b/src/ast/dyn_modules.cpp index 49627738ed..9eb6129086 100644 --- a/src/ast/dyn_modules.cpp +++ b/src/ast/dyn_modules.cpp @@ -663,6 +663,11 @@ static bool load_deferred_module_for_require(const string & name) { m->gc_collect(&loadRoot); return true; }); + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#compile-workers + Module::foreach([&](Module * m) { + if ( !m->frozen ) m->freeze(); + return true; + }); } loadRoot.gc_sweep(); move_all_nodes(parked, threadRoot); diff --git a/src/builtin/module_builtin_ast_adapters.cpp b/src/builtin/module_builtin_ast_adapters.cpp index 1ee2dbfc2d..f4dce39c8e 100644 --- a/src/builtin/module_builtin_ast_adapters.cpp +++ b/src/builtin/module_builtin_ast_adapters.cpp @@ -2607,8 +2607,16 @@ namespace das { } void addModuleCommentReader ( Module * module, CommentReaderPtr newM, Context * context, LineInfoArg * at ) { + // src/ast/ARCHITECTURE_COMPILE_MODULES.md#comment-readers + if ( !module->visibleEverywhere ) { + delete newM; + context->throw_error_at(at, "module %s installs a comment reader, so it has to be declared `module %s !inscope`: " + "every module after it in the require order waits for it and reads its comments through it", + module->name.c_str(), module->name.c_str()); + } module->noteRegistrationAtCompile(); if ( !module->addCommentReader(newM, true) ) { + delete newM; context->throw_error_at(at, "can't add comment reader to module %s", module->name.c_str()); } } @@ -2629,10 +2637,10 @@ namespace das { void addModuleCallMacro ( Module * module, CallMacroPtr newM, Context * context, LineInfoArg * at ) { module->noteRegistrationAtCompile(); module->ownedCallMacros.push_back(unique_ptr(newM)); + newM->module = module; if ( ! module->addCallMacro(newM->name, [=](const LineInfo & at) -> ExprLooksLikeCall * { auto ecm = new ExprCallMacro(at, newM->name); ecm->macro = newM; - newM->module = module; return ecm; }) ) { if ( daScriptEnvironment::getBound() && daScriptEnvironment::getBound()->g_Program ) { diff --git a/src/builtin/module_builtin_debugger.cpp b/src/builtin/module_builtin_debugger.cpp index ed8c24787f..7c72394fdf 100644 --- a/src/builtin/module_builtin_debugger.cpp +++ b/src/builtin/module_builtin_debugger.cpp @@ -1869,7 +1869,7 @@ namespace das ->args({"category","line","context"});; addExtern(*this, lib, "fork_debug_agent_context", SideEffects::modifyExternal, "forkDebugAgentContext") - ->args({"function","context","line"});; + ->args({"function","context","line"})->setNestsCompile(); addExtern(*this, lib, "delete_debug_agent_context", SideEffects::modifyExternal, "deleteDebugAgent") ->args({"category","line","context"});; diff --git a/src/builtin/module_builtin_jobque.cpp b/src/builtin/module_builtin_jobque.cpp index c9839a7404..82ac13aee7 100644 --- a/src/builtin/module_builtin_jobque.cpp +++ b/src/builtin/module_builtin_jobque.cpp @@ -6,6 +6,7 @@ #include "daScript/ast/ast_handle.h" #include "daScript/misc/job_que.h" +#include "daScript/misc/jobserver.h" #include "daScript/simulate/debug_agent.h" #include @@ -21,6 +22,7 @@ MAKE_TYPE_FACTORY(Channel, Channel) MAKE_TYPE_FACTORY(LockBox, LockBox) MAKE_TYPE_FACTORY(Stream, Stream) MAKE_TYPE_FACTORY(SeqBox, SeqBox) +MAKE_TYPE_FACTORY(Jobserver, das::Jobserver) MAKE_TYPE_FACTORY(Atomic32, AtomicTT) MAKE_TYPE_FACTORY(Atomic64, AtomicTT) @@ -259,6 +261,16 @@ namespace das { if ( !ch ) context->throw_error_at(at, "jobAppend: job is null"); return ch->append(size); } + struct JobserverAnnotation : ManagedStructureAnnotation { + JobserverAnnotation(ModuleLibrary & ml) : ManagedStructureAnnotation ("Jobserver", ml) {} + }; + + void withJobserverToken ( Jobserver * jobserver, const TBlock & blk, Context * context, LineInfoArg * at ) { + if ( !jobserver ) context->throw_error_at(at, "with_jobserver_token: jobserver is null"); + auto token = jobserver->acquire(); + das_invoke::invoke(context, at, blk); + } + void withChannel ( const TBlock & blk, Context * context, LineInfoArg * at ) { Channel ch(context); AddReleaseGuard guard(&ch, context, at); @@ -1449,7 +1461,7 @@ namespace das { }).detach(); } - void withJobQue ( const TBlock & block, Context * context, LineInfoArg * lineInfo ) { + static void runInJobQue ( Context * context, LineInfoArg * lineInfo, const callable & body ) { bool ok; // src/builtin/ARCHITECTURE_JOBQUE.md#jobque-block-panic { shared_ptr jq; @@ -1458,9 +1470,7 @@ namespace das { if ( !g_jobQue ) g_jobQue = make_shared(); // check under the lock: create_job_que can also init g_jobQue concurrently jq = g_jobQue; } - ok = context->runWithCatch([&]() { - context->invoke(block, nullptr, nullptr, lineInfo); - }); + ok = context->runWithCatch(body); } // Batch dispatch is a thread-local, block-scoped contract: flush any stragglers and reset the // flag so it cannot leak into unrelated jobque users later on this thread (e.g. the next test @@ -1501,6 +1511,20 @@ namespace das { } } + void withJobQue ( const TBlock & block, Context * context, LineInfoArg * lineInfo ) { + runInJobQue(context, lineInfo, [&]() { + context->invoke(block, nullptr, nullptr, lineInfo); + }); + } + + // src/misc/ARCHITECTURE_JOBSERVER.md#jobserver-client + void withJobserver ( int32_t limit, const TBlock & blk, Context * context, LineInfoArg * at ) { + Jobserver jobserver(limit); + runInJobQue(context, at, [&]() { + das_invoke::invoke(context, at, blk, &jobserver); + }); + } + // Persistent job-que lifecycle. Unlike with_job_que (block-scoped), the pool created here lives // until destroy_job_que — needed when the frame loop is driven externally (e.g. emscripten's // async set_main_loop), where a with_job_que block cannot span the per-frame new_job dispatches. @@ -1725,6 +1749,7 @@ namespace das { auto sqb = new SeqBoxAnnotation(lib); sqb->from("JobStatus"); addAnnotation(sqb); + addAnnotation(new JobserverAnnotation(lib)); auto a32 = new AtomicAnnotation("Atomic32",lib); addAnnotation(a32); auto a64 = new AtomicAnnotation("Atomic64",lib); @@ -1856,6 +1881,12 @@ namespace das { addExtern(*this, lib, "append", SideEffects::modifyArgument, "jobAppend") ->args({"channel","size","context","line"}); + addExtern(*this, lib, "with_jobserver", + SideEffects::invoke, "withJobserver") + ->args({"limit","block","context","line"}); + addExtern(*this, lib, "with_jobserver_token", + SideEffects::invoke, "withJobserverToken") + ->args({"jobserver","block","context","line"}); addExtern(*this, lib, "with_channel", SideEffects::invoke, "withChannel") ->args({"block","context","line"}); diff --git a/src/builtin/module_jit.cpp b/src/builtin/module_jit.cpp index 2ec7d04099..c4a2510ef1 100644 --- a/src/builtin/module_jit.cpp +++ b/src/builtin/module_jit.cpp @@ -40,11 +40,6 @@ #include #include #include -#include -#include -#include - -#include "daScript/misc/job_que.h" // JobQue::get_num_threads - the split emit pool's auto count #if !DAS_NO_FILEIO #include #endif @@ -516,136 +511,6 @@ namespace das { bool create_static_library ( const char * objFilePath, const char * libraryName, const char * customTool, Context * context ) { return true; } #endif - // ===== --jit-split-modules parallel optimize+emit ===== - // LLVM-agnostic job runner: the das side resolves the LLVM C-API entry points through its own - // dasbind registry (one resolution truth, libDaScript never links LLVM) and hands them over as - // raw pointers. Each job owns its (module, target machine, pass-builder options) trio, so - // LLVM's one-context-per-thread contract holds by construction. No shared mutable state and - // no lock: workers claim jobs via one atomic fetch_add and write only their own job's slots; - // Context is not thread-safe, so failures/walls are reported after join on the calling thread. - struct JitParEmitJob { - void * mod; - void * tm; - void * pbo; - string pipeline; - string objPath; - double passesSec = 0.0; - double emitSec = 0.0; - string error; - }; - static thread_local vector g_jitParEmitJobs; - - void jit_par_emit_begin () { - g_jitParEmitJobs.clear(); - } - - void jit_par_emit_add ( void * mod, void * tm, void * pbo, const char * pipeline, const char * objPath ) { - JitParEmitJob job; - job.mod = mod; - job.tm = tm; - job.pbo = pbo; - job.pipeline = pipeline ? pipeline : ""; - job.objPath = objPath ? objPath : ""; - g_jitParEmitJobs.emplace_back(std::move(job)); - } - - // threads <= 0 = auto (JobQue::get_num_threads - honors DAS_JOBQUE_THREADS, the das-side cap, - // Apple P-core selection, and >64-CPU Windows processor groups); always clamped to [1, jobs]. - // fileType is LLVMCodeGenFileType (the das side passes the enum value). An empty pipeline - // skips the pass run (the LLVM_ENABLE_OPT_PASS debug rail). Each module is verified AFTER - // passes and BEFORE emission - the monolith ordering; a broken module never reaches ISel. - // Fail-closed: any job failure reports every collected error and returns false; caller panics. - bool jit_par_emit_run ( int32_t threads, int32_t fileType, void * fnRunPasses, void * fnVerifyModule, - void * fnEmitToFile, void * fnGetErrorMessage, void * fnDisposeErrorMessage, - void * fnDisposeMessage, bool logTimes, Context * context ) { - // LLVMErrorRef LLVMRunPasses(M, Passes, TM, Options); LLVMBool LLVMVerifyModule(M, Action, char** Msg); - // LLVMBool LLVMTargetMachineEmitToFile(T, M, Filename, codegen, char** Err) - using RunPassesFn = void * (*) ( void *, const char *, void *, void * ); - using VerifyModuleFn = int32_t (*) ( void *, int32_t, char ** ); - using EmitToFileFn = int32_t (*) ( void *, void *, const char *, int32_t, char ** ); - using GetErrMsgFn = char * (*) ( void * ); - using DisposeFn = void (*) ( void * ); - auto runPasses = (RunPassesFn) fnRunPasses; - auto verifyModule = (VerifyModuleFn) fnVerifyModule; - auto emitToFile = (EmitToFileFn) fnEmitToFile; - auto getErrMsg = (GetErrMsgFn) fnGetErrorMessage; - auto disposeErrMsg = (DisposeFn) fnDisposeErrorMessage; - auto disposeMsg = (DisposeFn) fnDisposeMessage; - auto li = LineInfoArg(); - auto & callerJobs = g_jitParEmitJobs; - // the das caller validates each symbol by name first; this is the complete backstop so a - // future caller can't run workers that leak diagnostics through null dispose/message fns - if ( !runPasses || !verifyModule || !emitToFile || !getErrMsg || !disposeErrMsg || !disposeMsg - || callerJobs.empty() ) { - toLog(LogLevel::error, "jit_par_emit_run: missing entry points or no jobs\n", context, &li); - callerJobs.clear(); - return false; - } - int nThreads = threads > 0 ? threads : JobQue::get_num_threads(); - nThreads = std::max(1, std::min(nThreads, int(callerJobs.size()))); - std::atomic nextJob{0}; - constexpr int32_t LLVM_RETURN_STATUS_ACTION = 2; // LLVMReturnStatusAction - auto worker = [&]() { - for ( ;; ) { - size_t i = nextJob.fetch_add(1); - if ( i >= callerJobs.size() ) break; - auto & job = callerJobs[i]; - auto t0 = ref_time_ticks(); - if ( !job.pipeline.empty() ) { - void * err = runPasses(job.mod, job.pipeline.c_str(), job.tm, job.pbo); - if ( err ) { - char * msg = getErrMsg ? getErrMsg(err) : nullptr; // consumes err - job.error = string("pass run failed: ") + (msg ? msg : "(no message)"); - if ( msg && disposeErrMsg ) disposeErrMsg(msg); - continue; - } - } - char * vmsg = nullptr; - if ( verifyModule(job.mod, LLVM_RETURN_STATUS_ACTION, &vmsg) != 0 ) { - job.error = string("post-optimize verify failed for ") + job.objPath + ": " + (vmsg ? vmsg : "(no message)"); - if ( vmsg && disposeMsg ) disposeMsg(vmsg); - continue; - } - if ( vmsg && disposeMsg ) disposeMsg(vmsg); - job.passesSec = double(get_time_usec(t0)) / 1000000.0; - auto t1 = ref_time_ticks(); - char * emitErr = nullptr; - if ( job.objPath.empty() ) { - job.emitSec = 0.0; - continue; - } - if ( emitToFile(job.tm, job.mod, job.objPath.c_str(), fileType, &emitErr) != 0 ) { - job.error = string("emit failed for ") + job.objPath + ": " + (emitErr ? emitErr : "(no message)"); - if ( emitErr && disposeMsg ) disposeMsg(emitErr); - continue; - } - job.emitSec = double(get_time_usec(t1)) / 1000000.0; - } - }; - if ( nThreads == 1 ) { - worker(); - } else { - vector pool; - pool.reserve(nThreads); - for ( int t = 0; t != nThreads; ++t ) pool.emplace_back(worker); - for ( auto & th : pool ) th.join(); - } - bool ok = true; - for ( auto & job : callerJobs ) { - if ( !job.error.empty() ) { - ok = false; - string msg = string("LLVM JIT: parallel emit: ") + job.error + "\n"; - toLog(LogLevel::error, msg.c_str(), context, &li); - } else if ( logTimes ) { - auto msg = fmt::format(FMT_STRING("LLVM JIT time: job {} passes {:.6f} emit {:.6f}\n"), - job.objPath.c_str(), job.passesSec, job.emitSec); - toLog(LogLevel::info, msg.c_str(), context, &li); - } - } - callerJobs.clear(); - return ok; - } - #if (defined(_WIN32) || defined(__linux__) || defined(__APPLE__)) && !defined(_GAMING_XBOX) && !defined(_DURANGO) // Cross-compile-link a wasm32 object into a standalone .wasm via emcc. // runtimeLibPath — path to libDaScript_runtime.a (wasm32). Optional: @@ -904,14 +769,6 @@ namespace das { addExternInline(*this, lib, "create_static_library", SideEffects::worstDefault, "create_static_library") ->args({"objFilePath","libraryName","customTool","context"}); - addExternInline(*this, lib, "jit_par_emit_begin", - SideEffects::worstDefault, "jit_par_emit_begin"); - addExternInline(*this, lib, "jit_par_emit_add", - SideEffects::worstDefault, "jit_par_emit_add") - ->args({"mod","tm","pbo","pipeline","objPath"}); - addExternInline(*this, lib, "jit_par_emit_run", - SideEffects::worstDefault, "jit_par_emit_run") - ->args({"threads","fileType","fnRunPasses","fnVerifyModule","fnEmitToFile","fnGetErrorMessage","fnDisposeErrorMessage","fnDisposeMessage","logTimes","context"}); addExternInline(*this, lib, "host_jit_triple", SideEffects::none, "host_jit_triple"); addExternInline(*this, lib, "link_wasm", diff --git a/src/misc/ARCHITECTURE.md b/src/misc/ARCHITECTURE.md index d02d9ddb7b..fb6dfeea94 100644 --- a/src/misc/ARCHITECTURE.md +++ b/src/misc/ARCHITECTURE.md @@ -13,6 +13,8 @@ - `network.cpp` - the single-client TCP `Server` the DAP debugger and `daslib/network` sit on, the `Client` end beside it, `probe_local_port`, and the two helpers every socket error passes through. +- `jobserver.cpp` - the GNU make jobserver client a compile's extra threads take their tokens + from (`ARCHITECTURE_JOBSERVER.md`). - `dep_recorder.cpp` - what a run read, for a build system deciding whether a check has to run at all; armed by `DAS_DEPFILE` / `-MD`, silent otherwise. - `alloc_tracker.cpp` - the RelWithDebInfo C++ heap leak tracker: the live-allocation map, the diff --git a/src/misc/ARCHITECTURE_JOBSERVER.md b/src/misc/ARCHITECTURE_JOBSERVER.md new file mode 100644 index 0000000000..4514f6157e --- /dev/null +++ b/src/misc/ARCHITECTURE_JOBSERVER.md @@ -0,0 +1,36 @@ +# src/misc Architecture - the jobserver client + +A build that runs many compilers at once shares one budget of threads through the GNU make +jobserver. `ARCHITECTURE.md` beside this file holds the folder's other mechanisms. + +## A compile's extra threads are tokens from the build's pool {#jobserver-client} + +`jobserver.cpp` joins the pool a parent advertises in the environment - make, ninja's +`--jobserver-pool`, cargo - read from the last `--jobserver-auth=` (or the pre-4.2 +`--jobserver-fds=`) in `CARGO_MAKEFLAGS`, `MAKEFLAGS` or `MFLAGS`. A process owns one implicit +token; every job that runs beside it holds a token from the pool while it runs, and gives back +the same byte it read when it ends. A job takes its token with `Jobserver::acquire`, which +returns the implicit token when no job of this `Jobserver` holds it, else a pool token, and +otherwise waits: a token released inside the process wakes it at once, and the pool is read +again every 10 ms for tokens other processes free. The `JobserverToken` gives the token back +when it dies. A positive limit caps the tokens one `Jobserver` holds at once, the implicit one +included, so a caller's thread count holds with or without a pool. With no pool and no limit +`acquire` returns at once, and a compile runs as it would with no build around it. + +Each parallel job holds one token while it runs: a module of the compile DAG +(`src/ast/ast_compile_modules.cpp`), and a partition of the split JIT emit (`run_split_emit` in +`modules/dasLLVM/daslib/llvm_jit_run.das`, through the `jobque` module's `with_jobserver` and +`with_jobserver_token`). A job waits for its token on its own worker, so no worker gives up +while jobs remain, and a job never waits for another job while it holds one. + +The pool's three forms: `fifo:PATH` (make 4.4) is opened with a descriptor of its own; +`R,W` is a pair of inherited pipe descriptors; a bare name is a Windows semaphore. The pipe's +read end is reopened through `/proc/self/fd`, never switched to non-blocking in place, because +make shares that open file description and a non-blocking flag set on it changes make's own +reads; with no `/proc`, the pipe form is off and the fifo form serves. Make leaves the pipe +descriptors open only for a recipe it treats as recursive - `$(MAKE)` or a `+` prefix - so a +descriptor that is closed or is not a pipe turns the client off rather than reading whatever +the number now names. + +The library is the runtime's: the `jobque` module that binds it for das lives in the runtime, +and the compiler library reaches it through the exported `Jobserver` and `JobserverToken`. diff --git a/src/misc/jobserver.cpp b/src/misc/jobserver.cpp new file mode 100644 index 0000000000..09d456f3d1 --- /dev/null +++ b/src/misc/jobserver.cpp @@ -0,0 +1,196 @@ +#include "daScript/misc/platform.h" + +#include "daScript/misc/jobserver.h" +#include "daScript/misc/env_cfg.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) + #define WIN32_LEAN_AND_MEAN + #define NOMINMAX + #include +#else + #include + #include + #include + #include +#endif + +namespace das { + + namespace { + std::string authFromFlags ( const char * makeflags ) { + if ( !makeflags ) return ""; + std::string flags = makeflags; + for ( auto key : { "--jobserver-auth=", "--jobserver-fds=" } ) { + auto at = flags.rfind(key); + if ( at == std::string::npos ) continue; + at += strlen(key); + return flags.substr(at, flags.find(' ', at) - at); + } + return ""; + } + + const char * makeflagsFromEnvironment () { + for ( auto var : { "CARGO_MAKEFLAGS", "MAKEFLAGS", "MFLAGS" } ) { + auto flags = das_getenv(var); + if ( !authFromFlags(flags).empty() ) return flags; + } + return nullptr; + } + +#if !defined(_WIN32) && !DAS_TARGET_PS + bool isInheritedPipe ( int fd ) { + struct stat st; + return fd >= 0 && fcntl(fd, F_GETFD) != -1 && fstat(fd, &st) == 0 && S_ISFIFO(st.st_mode); + } +#endif + } + +#if defined(_WIN32) + + class JobserverPool { + public: + static std::unique_ptr open ( const std::string & auth ) { + auto h = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, auth.c_str()); + if ( !h ) return nullptr; + return std::unique_ptr(new JobserverPool(h)); + } + ~JobserverPool () { CloseHandle(sem); } + bool take ( char & byte ) { + byte = '+'; + return WaitForSingleObject(sem, 0) == WAIT_OBJECT_0; + } + void giveBack ( char ) { ReleaseSemaphore(sem, 1, nullptr); } + private: + explicit JobserverPool ( HANDLE h ) : sem(h) {} + HANDLE sem; + }; + +#elif DAS_TARGET_PS + + class JobserverPool { + public: + static std::unique_ptr open ( const std::string & ) { return nullptr; } + bool take ( char & ) { return false; } + void giveBack ( char ) {} + }; + +#else + + class JobserverPool { + public: + static std::unique_ptr open ( const std::string & auth ) { + if ( auth.compare(0, 5, "fifo:") == 0 ) { + int fd = ::open(auth.c_str() + 5, O_RDWR | O_NONBLOCK | O_CLOEXEC); + if ( fd < 0 ) return nullptr; + return std::unique_ptr(new JobserverPool(fd, fd)); + } + int r = -1, w = -1; + if ( sscanf(auth.c_str(), "%d,%d", &r, &w) != 2 ) return nullptr; + if ( !isInheritedPipe(r) || !isInheritedPipe(w) ) return nullptr; + int ownRead = ::open(("/proc/self/fd/" + std::to_string(r)).c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if ( ownRead < 0 ) return nullptr; + int ownWrite = dup(w); + if ( ownWrite < 0 ) { + close(ownRead); + return nullptr; + } + return std::unique_ptr(new JobserverPool(ownRead, ownWrite)); + } + ~JobserverPool () { + close(readFd); + if ( writeFd != readFd ) close(writeFd); + } + bool take ( char & byte ) { + for ( ;; ) { + auto n = read(readFd, &byte, 1); + if ( n == 1 ) return true; + if ( n < 0 && errno == EINTR ) continue; + return false; + } + } + void giveBack ( char byte ) { + while ( write(writeFd, &byte, 1) < 0 && errno == EINTR ) {} + } + private: + JobserverPool ( int r, int w ) : readFd(r), writeFd(w) {} + int readFd; + int writeFd; + }; + +#endif + + class JobserverState { + public: + std::unique_ptr pool; + int32_t limit = 0; + int32_t running = 0; + bool implicitBusy = false; + std::mutex lock; + std::condition_variable freed; + + void release ( bool implicitToken, char byte ) { + { + std::lock_guard guard(lock); + running --; + if ( implicitToken ) implicitBusy = false; + else if ( pool ) pool->giveBack(byte); + } + freed.notify_one(); + } + }; + + JobserverToken::JobserverToken ( JobserverToken && other ) noexcept + : state(other.state), implicitToken(other.implicitToken), byte(other.byte) { + other.state = nullptr; + } + + JobserverToken & JobserverToken::operator = ( JobserverToken && other ) noexcept { + if ( this != &other ) { + if ( state ) state->release(implicitToken, byte); + state = other.state; + implicitToken = other.implicitToken; + byte = other.byte; + other.state = nullptr; + } + return *this; + } + + JobserverToken::~JobserverToken () { + if ( state ) state->release(implicitToken, byte); + } + + Jobserver::Jobserver ( int32_t limit ) : Jobserver(limit, makeflagsFromEnvironment()) {} + + Jobserver::Jobserver ( int32_t limit, const char * makeflags ) : state(std::make_unique()) { + state->limit = limit; + auto auth = authFromFlags(makeflags); + if ( !auth.empty() ) state->pool = JobserverPool::open(auth); + } + + Jobserver::~Jobserver () = default; + + JobserverToken Jobserver::acquire () { + if ( !state->pool && state->limit <= 0 ) return JobserverToken(nullptr, false, 0); + std::unique_lock guard(state->lock); + for ( ;; ) { + if ( state->limit <= 0 || state->running < state->limit ) { + char byte = 0; + bool implicitToken = !state->implicitBusy; + if ( implicitToken || !state->pool || state->pool->take(byte) ) { + if ( implicitToken ) state->implicitBusy = true; + state->running ++; + return JobserverToken(state.get(), implicitToken, byte); + } + } + state->freed.wait_for(guard, std::chrono::milliseconds(10)); + } + } +} diff --git a/tests-cpp/small/test_compile_dag.cpp b/tests-cpp/small/test_compile_dag.cpp index 09c3c8f5d9..0fd5615784 100644 --- a/tests-cpp/small/test_compile_dag.cpp +++ b/tests-cpp/small/test_compile_dag.cpp @@ -24,6 +24,77 @@ TEST_CASE("compile DAG: four threads compile the modules one thread compiles") { CHECK_EQ(parallel, compileWith(1)); } +TEST_CASE("compile DAG: the modules after an !inscope module wait for it, so its comment reader sees a later module") { + auto fAccess = make_smart(); + TextWriter logs; + ModuleGroup libGroup; + CodeOfPolicies policies; + policies.compile_threads = 4; + auto program = compileDaScript(getDasRoot() + "/tests-cpp/small/test_compile_dag_reader_root.das", fAccess, logs, libGroup, policies); + REQUIRE_MESSAGE(!program->failed(), logs.str()); + auto reader = libGroup.findModule("test_compile_dag_reader"); + REQUIRE(reader); + REQUIRE(reader->macroContext); + auto ctx = reader->macroContext.get(); + auto index = ctx->findVariable("sibling_comment_chars"); + REQUIRE(index >= 0); + CHECK_GT(*(int32_t *)ctx->getVariable(index), 0); +} + +TEST_CASE("compile DAG: a module that installs a comment reader without !inscope fails to compile") { + auto fAccess = make_smart(); + auto dir = getDasRoot() + "/tests-cpp/small/"; + string reader = "options gen2\nmodule test_compile_dag_unmarked public\nrequire daslib/ast_boost\n" + "require test_compile_dag_reader\n[comment_reader]\nclass UnmarkedCommentCounter : SiblingCommentCounter {}\n"; + string root = "options gen2\nrequire test_compile_dag_unmarked\n"; + fAccess->setFileInfo(dir + "test_compile_dag_unmarked.das", make_unique(reader.c_str(), uint32_t(reader.size()), false)); + fAccess->setFileInfo(dir + "test_compile_dag_unmarked_root.das", make_unique(root.c_str(), uint32_t(root.size()), false)); + TextWriter logs; + ModuleGroup libGroup; + auto program = compileDaScript(dir + "test_compile_dag_unmarked_root.das", fAccess, logs, libGroup); + REQUIRE(program->failed()); + string errors; + for ( auto & err : program->errors ) errors += err.what + " " + err.extra + "\n"; + CHECK_MESSAGE(errors.find("!inscope") != string::npos, errors); +} + +TEST_CASE("compile DAG: a compile that starts with a comment reader loaded runs its jobs, and the reader reads what one thread reads") { + auto readWith = []( int32_t threads ) { + auto fAccess = make_smart(); + TextWriter logs; + ModuleGroup libGroup; + CodeOfPolicies policies; + policies.compile_threads = 1; + auto withReader = compileDaScript(getDasRoot() + "/tests-cpp/small/test_compile_dag_reader_root.das", fAccess, logs, libGroup, policies); + REQUIRE_MESSAGE(!withReader->failed(), logs.str()); + auto ctx = libGroup.findModule("test_compile_dag_reader")->macroContext.get(); + auto chars = (int32_t *)ctx->getVariable(ctx->findVariable("all_comment_chars")); + auto before = *chars; + policies.compile_threads = threads; + auto program = compileDaScript(getDasRoot() + "/tests-cpp/small/test_compile_dag_reader_jobs.das", fAccess, logs, libGroup, policies); + REQUIRE_MESSAGE(!program->failed(), logs.str()); + return *chars - before; + }; + readWith(1); + auto read = readWith(1); + CHECK_GT(read, 0); + CHECK_EQ(readWith(4), read); +} + +TEST_CASE("compile DAG deadlock prevention: a macro module that forks a debug agent context is nesting") { + auto fAccess = make_smart(); + TextWriter logs; + ModuleGroup libGroup; + CodeOfPolicies policies; + policies.compile_threads = 1; + auto program = compileDaScript(getDasRoot() + "/tests-cpp/small/test_compile_dag_fork_root.das", fAccess, logs, libGroup, policies); + REQUIRE_MESSAGE(!program->failed(), logs.str()); + auto fork = libGroup.findModule("test_compile_dag_fork"); + REQUIRE(fork); + REQUIRE(fork->macroContext); + CHECK(fork->macroNestsCompile); +} + TEST_CASE("compile DAG deadlock prevention: a macro module reaching a nesting builtin through a helper is nesting") { auto fAccess = make_smart(); TextWriter logs; @@ -116,7 +187,7 @@ TEST_CASE("compile DAG: a structure of a frozen module reads its aliases without CHECK(checked > 0); } -TEST_CASE("compile DAG: a module that writes a global of a frozen module leaves that global's flags alone, so jobs share it") { +TEST_CASE("compile DAG: a module that writes or folds a global of a frozen module leaves that global's flags alone, so jobs share it") { auto fAccess = make_smart(); TextWriter logs; ModuleGroup libGroup; @@ -131,4 +202,7 @@ TEST_CASE("compile DAG: a module that writes a global of a frozen module leaves REQUIRE(counter); CHECK_FALSE(bool(counter->access_ref)); CHECK_FALSE(bool(counter->access_info_pass_mutable)); + auto limit = base->findVariable("compile_dag_limit"); + REQUIRE(limit); + CHECK_FALSE(bool(limit->access_fold)); } diff --git a/tests-cpp/small/test_compile_dag_base.das b/tests-cpp/small/test_compile_dag_base.das index f92b6c5fc0..8745d1fb1c 100644 --- a/tests-cpp/small/test_compile_dag_base.das +++ b/tests-cpp/small/test_compile_dag_base.das @@ -2,10 +2,14 @@ options gen2 module test_compile_dag_base public +// a comment a reader loaded before the compile must see + def compile_dag_base() => 1 var compile_dag_counter = 0 +let compile_dag_limit = 1000 + def compile_dag_bump(var counter : int&) { counter ++ } diff --git a/tests-cpp/small/test_compile_dag_fork.das b/tests-cpp/small/test_compile_dag_fork.das new file mode 100644 index 0000000000..9255f77926 --- /dev/null +++ b/tests-cpp/small/test_compile_dag_fork.das @@ -0,0 +1,19 @@ +options gen2 + +module test_compile_dag_fork public + +require debugapi + +[unused_argument(ctx)] +def private fork_probe_agent(ctx : Context) { + pass +} + +[_macro] +def private fork_probe_installing { + if (is_compiling_macros_in_module("never_compiled_module")) { + fork_debug_agent_context(@@fork_probe_agent) + } +} + +def public fork_probe_value() => 1 diff --git a/tests-cpp/small/test_compile_dag_fork_root.das b/tests-cpp/small/test_compile_dag_fork_root.das new file mode 100644 index 0000000000..a0315eeee3 --- /dev/null +++ b/tests-cpp/small/test_compile_dag_fork_root.das @@ -0,0 +1,8 @@ +options gen2 + +require test_compile_dag_fork + +[export] +def main() { + assert(fork_probe_value() == 1) +} diff --git a/tests-cpp/small/test_compile_dag_leaf.das b/tests-cpp/small/test_compile_dag_leaf.das index 66211bbb94..9664bdfe28 100644 --- a/tests-cpp/small/test_compile_dag_leaf.das +++ b/tests-cpp/small/test_compile_dag_leaf.das @@ -2,6 +2,8 @@ options gen2 module test_compile_dag_leaf public +// a comment a reader loaded before the compile must see + require daslib/ast_boost require daslib/cross_context require test_compile_dag_base @@ -10,7 +12,7 @@ require test_compile_dag_base class DeadlockLeafProbe : AstFunctionAnnotation { def override apply(var func : FunctionPtr; var group : ModuleGroup; var args : AnnotationArgumentList; var errors : das_string) : bool => - length(args) <= 1000 + compile_dag_base() + length(args) <= compile_dag_limit + compile_dag_base() } def compile_dag_leaf_write() { diff --git a/tests-cpp/small/test_compile_dag_reader.das b/tests-cpp/small/test_compile_dag_reader.das new file mode 100644 index 0000000000..fa52cff260 --- /dev/null +++ b/tests-cpp/small/test_compile_dag_reader.das @@ -0,0 +1,136 @@ +options gen2 + +module test_compile_dag_reader public !inscope + +require daslib/ast_boost + +var sibling_comment_chars = 0 +var all_comment_chars = 0 + +[comment_reader] +class SiblingCommentCounter : AstCommentReader { + def override open(prog : ProgramPtr; mod : Module?; cpp : bool; info : LineInfo) : void { + pass + } + def override accept(prog : ProgramPtr; mod : Module?; ch : int; info : LineInfo) : void { + all_comment_chars ++ + if (mod != null && mod.name == "test_compile_dag_sibling") { + sibling_comment_chars ++ + } + } + def override close(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeStructure(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterStructure(st : StructurePtr; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeStructureFields(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterStructureField(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterStructureFields(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeFunction(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterFunction(fn : FunctionPtr; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeGlobalVariables(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterGlobalVariable(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterGlobalVariables(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeVariant(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeVariantEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterVariantEntry(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterVariantEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterVariant(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeTuple(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeTupleEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterTupleEntry(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterTupleEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterTuple(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeBitfield(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeBitfieldEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterBitfieldEntry(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterBitfieldEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterBitfield(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeEnumeration(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override beforeEnumerationEntries(prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterEnumerationEntry(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override afterEnumerationEntries(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterEnumeration(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } + def override beforeAlias(prog : ProgramPtr; mod : Module?; info : LineInfo) : void { + pass + } + def override afterAlias(name : string; prog : ProgramPtr; mod : Module?; + info : LineInfo) : void { + pass + } +} + +def public compile_dag_reader_probe() => 1 diff --git a/tests-cpp/small/test_compile_dag_reader_jobs.das b/tests-cpp/small/test_compile_dag_reader_jobs.das new file mode 100644 index 0000000000..4e062fd050 --- /dev/null +++ b/tests-cpp/small/test_compile_dag_reader_jobs.das @@ -0,0 +1,9 @@ +options gen2 + +require test_compile_dag_leaf +require test_compile_dag_base + +[export] +def main() { + assert(compile_dag_base() == 1) +} diff --git a/tests-cpp/small/test_compile_dag_reader_root.das b/tests-cpp/small/test_compile_dag_reader_root.das new file mode 100644 index 0000000000..5a53ca30e8 --- /dev/null +++ b/tests-cpp/small/test_compile_dag_reader_root.das @@ -0,0 +1,9 @@ +options gen2 + +require test_compile_dag_reader +require test_compile_dag_sibling + +[export] +def main() { + assert(compile_dag_reader_probe() + compile_dag_sibling_probe() == 3) +} diff --git a/tests-cpp/small/test_compile_dag_sibling.das b/tests-cpp/small/test_compile_dag_sibling.das new file mode 100644 index 0000000000..842322ef6f --- /dev/null +++ b/tests-cpp/small/test_compile_dag_sibling.das @@ -0,0 +1,6 @@ +options gen2 + +module test_compile_dag_sibling public + +// a comment the reader of an earlier module in the walk must see +def public compile_dag_sibling_probe() => 2 diff --git a/tests-cpp/small/test_jobserver.cpp b/tests-cpp/small/test_jobserver.cpp new file mode 100644 index 0000000000..230dee6de5 --- /dev/null +++ b/tests-cpp/small/test_jobserver.cpp @@ -0,0 +1,180 @@ +#include +#include "daScript/daScript.h" +#include "daScript/misc/jobserver.h" +#include "daScript/misc/env_cfg.h" + +#include +#include +#include +#include + +#if defined(_WIN32) + #define WIN32_LEAN_AND_MEAN + #define NOMINMAX + #include +#else + #include + #include + #include +#endif + +using namespace das; + +namespace { + std::vector acquireAll ( Jobserver & jobserver, size_t count ) { + std::vector tokens; + for ( size_t i = 0; i != count; ++i ) tokens.push_back(jobserver.acquire()); + return tokens; + } + + int32_t peakHeld ( Jobserver & jobserver, int32_t threads, int32_t rounds ) { + std::atomic held{0}, peak{0}; + std::vector workers; + for ( int32_t t = 0; t != threads; ++t ) { + workers.emplace_back([&]() { + for ( int32_t r = 0; r != rounds; ++r ) { + auto token = jobserver.acquire(); + auto now = ++held; + for ( auto seen = peak.load(); now > seen && !peak.compare_exchange_weak(seen, now); ) {} + --held; + } + }); + } + for ( auto & w : workers ) w.join(); + return peak.load(); + } +} + +TEST_CASE("jobserver: with no pool and no limit every acquire returns at once") { + for ( auto flags : { (const char *) nullptr, "-j8", "--jobserver-auth=x", "--jobserver-auth=1000,1001", + "--jobserver-auth=fifo:/nonexistent/das_jobserver" } ) { + Jobserver jobserver(0, flags); + CHECK_EQ(acquireAll(jobserver, 16).size(), 16); + } +} + +TEST_CASE("jobserver: a limit caps the tokens held at once") { + Jobserver jobserver(3, nullptr); + CHECK_LE(peakHeld(jobserver, 8, 200), 3); +} + +#if defined(_WIN32) + +TEST_CASE("jobserver: a named semaphore pool lends its tokens beside the implicit one and takes them back") { + auto name = "das_jobserver_test_" + std::to_string(GetCurrentProcessId()); + auto sem = CreateSemaphoreA(nullptr, 2, 2, name.c_str()); + REQUIRE(sem); + auto flags = " -j3 --jobserver-auth=" + name; + { + Jobserver jobserver(0, flags.c_str()); + auto held = acquireAll(jobserver, 3); + CHECK(WaitForSingleObject(sem, 0) == WAIT_TIMEOUT); + } + CHECK(WaitForSingleObject(sem, 0) == WAIT_OBJECT_0); + CHECK(WaitForSingleObject(sem, 0) == WAIT_OBJECT_0); + CloseHandle(sem); +} + +#else + +namespace { + std::string drain ( int fd ) { + std::string bytes; + char c; + while ( read(fd, &c, 1) == 1 ) bytes += c; + std::sort(bytes.begin(), bytes.end()); + return bytes; + } + + struct TestFifo { + std::string path; + int fd = -1; + explicit TestFifo ( const char * tokens ) { + auto tmp = das_getenv("TMPDIR"); + path = std::string(tmp && *tmp ? tmp : "/tmp") + "/das_jobserver_test_" + std::to_string(getpid()); + unlink(path.c_str()); + REQUIRE(mkfifo(path.c_str(), 0600) == 0); + fd = open(path.c_str(), O_RDWR | O_NONBLOCK); + REQUIRE(fd >= 0); + REQUIRE(write(fd, tokens, strlen(tokens)) == ssize_t(strlen(tokens))); + } + ~TestFifo () { + close(fd); + unlink(path.c_str()); + } + std::string flags () const { return " -j3 --jobserver-auth=fifo:" + path; } + }; +} + +TEST_CASE("jobserver: a fifo pool lends its tokens beside the implicit one and takes back the same bytes") { + TestFifo fifo("ab"); + auto flags = fifo.flags(); + { + Jobserver jobserver(0, flags.c_str()); + auto held = acquireAll(jobserver, 3); + CHECK_EQ(drain(fifo.fd), ""); + } + CHECK_EQ(drain(fifo.fd), "ab"); +} + +TEST_CASE("jobserver: the last --jobserver-auth wins") { + TestFifo fifo("c"); + auto flags = "--jobserver-auth=fifo:/nonexistent/das_jobserver --jobserver-auth=fifo:" + fifo.path; + { + Jobserver jobserver(0, flags.c_str()); + auto held = acquireAll(jobserver, 2); + CHECK_EQ(drain(fifo.fd), ""); + } + CHECK_EQ(drain(fifo.fd), "c"); +} + +TEST_CASE("jobserver: threads sharing a one-token pool hold at most two tokens and give the token back") { + TestFifo fifo("+"); + auto flags = fifo.flags(); + { + Jobserver jobserver(0, flags.c_str()); + CHECK_LE(peakHeld(jobserver, 8, 200), 2); + } + CHECK_EQ(drain(fifo.fd), "+"); +} + +TEST_CASE("jobserver: a parallel compile under a one-token pool finishes and gives the token back") { + TestFifo fifo("+"); + auto flags = fifo.flags(); + auto saved = das_getenv("MAKEFLAGS"); + std::string savedFlags = saved ? saved : ""; + das_setenv("MAKEFLAGS", flags.c_str()); + { + auto fAccess = make_smart(); + TextWriter logs; + ModuleGroup libGroup; + CodeOfPolicies policies; + policies.compile_threads = 4; + auto program = compileDaScript(getDasRoot() + "/tests-cpp/small/test_compile_dag.das", fAccess, logs, libGroup, policies); + CHECK_MESSAGE(!program->failed(), logs.str()); + } + if ( saved ) das_setenv("MAKEFLAGS", savedFlags.c_str()); + else das_unsetenv("MAKEFLAGS"); + CHECK_EQ(drain(fifo.fd), "+"); +} + +#if defined(__linux__) + +TEST_CASE("jobserver: an inherited pipe pool reads through its own non-blocking fd") { + int fds[2]; + REQUIRE(pipe(fds) == 0); + REQUIRE(write(fds[1], "+++", 3) == 3); + auto flags = "-j4 --jobserver-fds=" + std::to_string(fds[0]) + "," + std::to_string(fds[1]); + { + Jobserver jobserver(0, flags.c_str()); + auto held = acquireAll(jobserver, 4); + CHECK_EQ(fcntl(fds[0], F_GETFL) & O_NONBLOCK, 0); + } + fcntl(fds[0], F_SETFL, O_NONBLOCK); + CHECK_EQ(drain(fds[0]), "+++"); + close(fds[0]); + close(fds[1]); +} + +#endif +#endif diff --git a/tests-cpp/small/test_per_thread_emission_state.cpp b/tests-cpp/small/test_per_thread_emission_state.cpp deleted file mode 100644 index f11a5980a3..0000000000 --- a/tests-cpp/small/test_per_thread_emission_state.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include "daScript/daScript.h" -#include -#include -#include -#include - -using namespace das; - -namespace das { - void jit_par_emit_begin (); - void jit_par_emit_add ( void * mod, void * tm, void * pbo, const char * pipeline, const char * objPath ); - bool jit_par_emit_run ( int32_t threads, int32_t fileType, void * fnRunPasses, void * fnVerifyModule, - void * fnEmitToFile, void * fnGetErrorMessage, void * fnDisposeErrorMessage, - void * fnDisposeMessage, bool logTimes, Context * context ); -} - -namespace { - - std::mutex g_verifiedMutex; - std::vector g_verified; - - int32_t verify_records_the_module ( void * mod, int32_t, char ** ) { - std::lock_guard guard(g_verifiedMutex); - g_verified.push_back(mod); - return 0; - } - - void * never_runs_passes ( void *, const char *, void *, void * ) { return nullptr; } - int32_t never_emits ( void *, void *, const char *, int32_t, char ** ) { return 0; } - char * no_error_message ( void * ) { return nullptr; } - void disposes_nothing ( void * ) {} - - bool runQueuedJobs ( int32_t threads ) { - return jit_par_emit_run(threads, 0, (void *) &never_runs_passes, (void *) &verify_records_the_module, - (void *) &never_emits, (void *) &no_error_message, (void *) &disposes_nothing, (void *) &disposes_nothing, - false, nullptr); - } - - void queueJob ( int & module ) { - jit_par_emit_add(&module, nullptr, nullptr, "", ""); - } -} - -TEST_CASE("the parallel JIT emit queue belongs to the thread that fills it") { - int mine = 0, theirs = 0; - g_verified.clear(); - jit_par_emit_begin(); - queueJob(mine); - std::thread other([&]() { - jit_par_emit_begin(); - queueJob(theirs); - }); - other.join(); - REQUIRE(runQueuedJobs(1)); - REQUIRE_EQ(g_verified.size(), 1u); - CHECK_EQ(g_verified[0], (void *) &mine); -} - -TEST_CASE("the parallel JIT emit workers run the jobs of the thread that called run") { - int first = 0, second = 0; - g_verified.clear(); - jit_par_emit_begin(); - queueJob(first); - queueJob(second); - REQUIRE(runQueuedJobs(2)); - CHECK_EQ(g_verified.size(), 2u); -}