id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
11,244
libstore.hh
NixOS_nix/src/libstore-test-support/tests/libstore.hh
#pragma once ///@file #include <gtest/gtest.h> #include <gmock/gmock.h> #include "store-api.hh" namespace nix { class LibStoreTest : public virtual ::testing::Test { public: static void SetUpTestSuite() { initLibStore(false); } protected: LibStoreTest() : store(openStore({ .variant = StoreReference::Specified{ .scheme = "dummy", }, .params = {}, })) { } ref<Store> store; }; } /* namespace nix */
534
C++
.h
27
13.777778
51
0.548
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,245
outputs-spec.hh
NixOS_nix/src/libstore-test-support/tests/outputs-spec.hh
#pragma once ///@file #include <rapidcheck/gen/Arbitrary.h> #include <outputs-spec.hh> #include "tests/path.hh" namespace rc { using namespace nix; template<> struct Arbitrary<OutputsSpec> { static Gen<OutputsSpec> arbitrary(); }; }
243
C++
.h
12
18.416667
40
0.768889
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,246
protocol.hh
NixOS_nix/src/libstore-test-support/tests/protocol.hh
#pragma once ///@file #include <nlohmann/json.hpp> #include <gtest/gtest.h> #include "tests/libstore.hh" #include "tests/characterization.hh" namespace nix { template<class Proto, const char * protocolDir> class ProtoTest : public CharacterizationTest, public LibStoreTest { std::filesystem::path unitTestData = getUnitTestData() / protocolDir; std::filesystem::path goldenMaster(std::string_view testStem) const override { return unitTestData / (std::string { testStem + ".bin" }); } }; template<class Proto, const char * protocolDir> class VersionedProtoTest : public ProtoTest<Proto, protocolDir> { public: /** * Golden test for `T` reading */ template<typename T> void readProtoTest(PathView testStem, typename Proto::Version version, T expected) { CharacterizationTest::readTest(testStem, [&](const auto & encoded) { T got = ({ StringSource from { encoded }; Proto::template Serialise<T>::read( *LibStoreTest::store, typename Proto::ReadConn { .from = from, .version = version, }); }); ASSERT_EQ(got, expected); }); } /** * Golden test for `T` write */ template<typename T> void writeProtoTest(PathView testStem, typename Proto::Version version, const T & decoded) { CharacterizationTest::writeTest(testStem, [&]() { StringSink to; Proto::template Serialise<T>::write( *LibStoreTest::store, typename Proto::WriteConn { .to = to, .version = version, }, decoded); return std::move(to.s); }); } }; #define VERSIONED_CHARACTERIZATION_TEST(FIXTURE, NAME, STEM, VERSION, VALUE) \ TEST_F(FIXTURE, NAME ## _read) { \ readProtoTest(STEM, VERSION, VALUE); \ } \ TEST_F(FIXTURE, NAME ## _write) { \ writeProtoTest(STEM, VERSION, VALUE); \ } }
2,107
C++
.h
65
24.184615
94
0.585138
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,247
path.hh
NixOS_nix/src/libstore-test-support/tests/path.hh
#pragma once ///@file #include <rapidcheck/gen/Arbitrary.h> #include <path.hh> namespace nix { struct StorePathName { std::string name; }; // For rapidcheck void showValue(const StorePath & p, std::ostream & os); } namespace rc { using namespace nix; template<> struct Arbitrary<StorePathName> { static Gen<StorePathName> arbitrary(); }; template<> struct Arbitrary<StorePath> { static Gen<StorePath> arbitrary(); }; }
441
C++
.h
22
18.045455
55
0.753056
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,248
derived-path.hh
NixOS_nix/src/libstore-test-support/tests/derived-path.hh
#pragma once ///@file #include <rapidcheck/gen/Arbitrary.h> #include <derived-path.hh> #include "tests/path.hh" #include "tests/outputs-spec.hh" namespace rc { using namespace nix; template<> struct Arbitrary<SingleDerivedPath::Opaque> { static Gen<SingleDerivedPath::Opaque> arbitrary(); }; template<> struct Arbitrary<SingleDerivedPath::Built> { static Gen<SingleDerivedPath::Built> arbitrary(); }; template<> struct Arbitrary<SingleDerivedPath> { static Gen<SingleDerivedPath> arbitrary(); }; template<> struct Arbitrary<DerivedPath::Built> { static Gen<DerivedPath::Built> arbitrary(); }; template<> struct Arbitrary<DerivedPath> { static Gen<DerivedPath> arbitrary(); }; }
708
C++
.h
29
22.37931
54
0.77429
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,249
nix_api_store.hh
NixOS_nix/src/libstore-test-support/tests/nix_api_store.hh
#pragma once ///@file #include "tests/nix_api_util.hh" #include "file-system.hh" #include <filesystem> #include "nix_api_store.h" #include "nix_api_store_internal.h" #include <filesystem> #include <gtest/gtest.h> namespace fs { using namespace std::filesystem; } namespace nixC { class nix_api_store_test : public nix_api_util_context { public: nix_api_store_test() { nix_libstore_init(ctx); init_local_store(); }; ~nix_api_store_test() override { nix_store_free(store); for (auto & path : fs::recursive_directory_iterator(nixDir)) { fs::permissions(path, fs::perms::owner_all); } fs::remove_all(nixDir); } Store * store; std::string nixDir; std::string nixStoreDir; protected: void init_local_store() { #ifdef _WIN32 // no `mkdtemp` with MinGW auto tmpl = nix::defaultTempDir() + "/tests_nix-store."; for (size_t i = 0; true; ++i) { nixDir = tmpl + std::string { i }; if (fs::create_directory(nixDir)) break; } #else // resolve any symlinks in i.e. on macOS /tmp -> /private/tmp // because this is not allowed for a nix store. auto tmpl = nix::absPath(std::filesystem::path(nix::defaultTempDir()) / "tests_nix-store.XXXXXX", true); nixDir = mkdtemp((char *) tmpl.c_str()); #endif nixStoreDir = nixDir + "/my_nix_store"; // Options documented in `nix help-stores` const char * p1[] = {"store", nixStoreDir.c_str()}; const char * p2[] = {"state", (new std::string(nixDir + "/my_state"))->c_str()}; const char * p3[] = {"log", (new std::string(nixDir + "/my_log"))->c_str()}; const char ** params[] = {p1, p2, p3, nullptr}; store = nix_store_open(ctx, "local", params); if (!store) { std::string errMsg = nix_err_msg(nullptr, ctx, nullptr); ASSERT_NE(store, nullptr) << "Could not open store: " << errMsg; }; } }; }
2,019
C++
.h
60
27.566667
112
0.59147
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,250
graphml.hh
NixOS_nix/src/nix-store/graphml.hh
#pragma once ///@file #include "store-api.hh" namespace nix { void printGraphML(ref<Store> store, StorePathSet && roots); }
128
C++
.h
6
19.666667
59
0.754237
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,251
dotgraph.hh
NixOS_nix/src/nix-store/dotgraph.hh
#pragma once ///@file #include "store-api.hh" namespace nix { void printDotGraph(ref<Store> store, StorePathSet && roots); }
129
C++
.h
6
19.833333
60
0.756303
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,252
characterization.hh
NixOS_nix/src/libutil-test-support/tests/characterization.hh
#pragma once ///@file #include <gtest/gtest.h> #include "types.hh" #include "environment-variables.hh" #include "file-system.hh" namespace nix { /** * The path to the unit test data directory. See the contributing guide * in the manual for further details. */ static inline std::filesystem::path getUnitTestData() { return getEnv("_NIX_TEST_UNIT_DATA").value(); } /** * Whether we should update "golden masters" instead of running tests * against them. See the contributing guide in the manual for further * details. */ static inline bool testAccept() { return getEnv("_NIX_TEST_ACCEPT") == "1"; } /** * Mixin class for writing characterization tests */ class CharacterizationTest : public virtual ::testing::Test { protected: /** * While the "golden master" for this characterization test is * located. It should not be shared with any other test. */ virtual std::filesystem::path goldenMaster(PathView testStem) const = 0; public: /** * Golden test for reading * * @param test hook that takes the contents of the file and does the * actual work */ void readTest(PathView testStem, auto && test) { auto file = goldenMaster(testStem); if (testAccept()) { GTEST_SKIP() << "Cannot read golden master " << file << "because another test is also updating it"; } else { test(readFile(file)); } } /** * Golden test for writing * * @param test hook that produces contents of the file and does the * actual work */ void writeTest( PathView testStem, auto && test, auto && readFile2, auto && writeFile2) { auto file = goldenMaster(testStem); auto got = test(); if (testAccept()) { std::filesystem::create_directories(file.parent_path()); writeFile2(file, got); GTEST_SKIP() << "Updating golden master " << file; } else { decltype(got) expected = readFile2(file); ASSERT_EQ(got, expected); } } /** * Specialize to `std::string` */ void writeTest(PathView testStem, auto && test) { writeTest( testStem, test, [](const std::filesystem::path & f) -> std::string { return readFile(f); }, [](const std::filesystem::path & f, const std::string & c) { return writeFile(f, c); }); } }; }
2,622
C++
.h
96
20.552083
79
0.582173
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,253
tracing-file-system-object-sink.hh
NixOS_nix/src/libutil-test-support/tests/tracing-file-system-object-sink.hh
#pragma once #include "fs-sink.hh" namespace nix::test { /** * A `FileSystemObjectSink` that traces calls, writing to stderr. */ class TracingFileSystemObjectSink : public virtual FileSystemObjectSink { FileSystemObjectSink & sink; public: TracingFileSystemObjectSink(FileSystemObjectSink & sink) : sink(sink) { } void createDirectory(const CanonPath & path) override; void createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> fn) override; void createSymlink(const CanonPath & path, const std::string & target) override; }; /** * A `ExtendedFileSystemObjectSink` that traces calls, writing to stderr. */ class TracingExtendedFileSystemObjectSink : public TracingFileSystemObjectSink, public ExtendedFileSystemObjectSink { ExtendedFileSystemObjectSink & sink; public: TracingExtendedFileSystemObjectSink(ExtendedFileSystemObjectSink & sink) : TracingFileSystemObjectSink(sink) , sink(sink) { } void createHardlink(const CanonPath & path, const CanonPath & target) override; }; }
1,097
C++
.h
33
29.69697
115
0.769886
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,254
nix_api_util.hh
NixOS_nix/src/libutil-test-support/tests/nix_api_util.hh
#pragma once ///@file #include "nix_api_util.h" #include <gtest/gtest.h> namespace nixC { class nix_api_util_context : public ::testing::Test { protected: nix_api_util_context() { ctx = nix_c_context_create(); nix_libutil_init(ctx); }; ~nix_api_util_context() override { nix_c_context_free(ctx); ctx = nullptr; } nix_c_context * ctx; inline void assert_ctx_ok() { if (nix_err_code(ctx) == NIX_OK) { return; } unsigned int n; const char * p = nix_err_msg(nullptr, ctx, &n); std::string msg(p, n); FAIL() << "nix_err_code(ctx) != NIX_OK, message: " << msg; } inline void assert_ctx_err() { if (nix_err_code(ctx) != NIX_OK) { return; } FAIL() << "Got NIX_OK, but expected an error!"; } }; }
878
C++
.h
38
17.105263
66
0.536145
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,255
gtest-with-params.hh
NixOS_nix/src/libutil-test-support/tests/gtest-with-params.hh
#pragma once // SPDX-FileCopyrightText: 2014 Emil Eriksson // // SPDX-License-Identifier: BSD-2-Clause // // The lion's share of this code is copy pasted directly out of RapidCheck // headers, so the copyright is set accordingly. /** * @file * * Implements the ability to run a RapidCheck test under gtest with changed * test parameters such as the number of tests to run. This is useful for * running very large numbers of the extremely cheap property tests. */ #include <gtest/gtest.h> #include <rapidcheck/gtest.h> #include <rapidcheck/gen/Arbitrary.hpp> namespace rc::detail { using MakeTestParams = TestParams (*)(); template<typename Testable> void checkGTestWith(Testable && testable, MakeTestParams makeTestParams) { const auto testInfo = ::testing::UnitTest::GetInstance()->current_test_info(); detail::TestMetadata metadata; metadata.id = std::string(testInfo->test_case_name()) + "/" + std::string(testInfo->name()); metadata.description = std::string(testInfo->name()); const auto result = checkTestable(std::forward<Testable>(testable), metadata, makeTestParams()); if (result.template is<detail::SuccessResult>()) { const auto success = result.template get<detail::SuccessResult>(); if (!success.distribution.empty()) { printResultMessage(result, std::cout); std::cout << std::endl; } } else { std::ostringstream ss; printResultMessage(result, ss); FAIL() << ss.str() << std::endl; } } } #define RC_GTEST_PROP_WITH_PARAMS(TestCase, Name, MakeParams, ArgList) \ void rapidCheck_propImpl_##TestCase##_##Name ArgList; \ \ TEST(TestCase, Name) \ { \ ::rc::detail::checkGTestWith(&rapidCheck_propImpl_##TestCase##_##Name, MakeParams); \ } \ \ void rapidCheck_propImpl_##TestCase##_##Name ArgList
2,328
C++
.h
49
39.795918
100
0.551937
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,256
string_callback.hh
NixOS_nix/src/libutil-test-support/tests/string_callback.hh
#pragma once #include <string> namespace nix::testing { void observe_string_cb(const char * start, unsigned int n, void * user_data); inline void * observe_string_cb_data(std::string & out) { return (void *) &out; }; #define OBSERVE_STRING(str) nix::testing::observe_string_cb, nix::testing::observe_string_cb_data(str) }
331
C++
.h
10
31.2
102
0.734177
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,257
hash.hh
NixOS_nix/src/libutil-test-support/tests/hash.hh
#pragma once ///@file #include <rapidcheck/gen/Arbitrary.h> #include <hash.hh> namespace rc { using namespace nix; template<> struct Arbitrary<Hash> { static Gen<Hash> arbitrary(); }; }
195
C++
.h
11
15.909091
37
0.748603
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,258
common-eval-args.hh
NixOS_nix/src/libcmd/common-eval-args.hh
#pragma once ///@file #include "args.hh" #include "canon-path.hh" #include "common-args.hh" #include "search-path.hh" #include <filesystem> namespace nix { class Store; namespace fetchers { struct Settings; } class EvalState; struct EvalSettings; struct CompatibilitySettings; class Bindings; struct SourcePath; namespace flake { struct Settings; } /** * @todo Get rid of global setttings variables */ extern fetchers::Settings fetchSettings; /** * @todo Get rid of global setttings variables */ extern EvalSettings evalSettings; /** * @todo Get rid of global setttings variables */ extern flake::Settings flakeSettings; /** * Settings that control behaviors that have changed since Nix 2.3. */ extern CompatibilitySettings compatibilitySettings; struct MixEvalArgs : virtual Args, virtual MixRepair { static constexpr auto category = "Common evaluation options"; MixEvalArgs(); Bindings * getAutoArgs(EvalState & state); LookupPath lookupPath; std::optional<std::string> evalStoreUrl; private: struct AutoArgExpr { std::string expr; }; struct AutoArgString { std::string s; }; struct AutoArgFile { std::filesystem::path path; }; struct AutoArgStdin { }; using AutoArg = std::variant<AutoArgExpr, AutoArgString, AutoArgFile, AutoArgStdin>; std::map<std::string, AutoArg> autoArgs; }; /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ SourcePath lookupFileArg(EvalState & state, std::string_view s, const Path * baseDir = nullptr); }
1,577
C++
.h
52
27.884615
112
0.763963
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,259
markdown.hh
NixOS_nix/src/libcmd/markdown.hh
#pragma once ///@file #include <string_view> namespace nix { /** * Render the given Markdown text to the terminal. * * If Nix is compiled without Markdown support, this function will return the input text as-is. * * The renderer takes into account the terminal width, and wraps text accordingly. */ std::string renderMarkdownToTerminal(std::string_view markdown); }
376
C++
.h
13
27.153846
95
0.771588
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,260
installable-derived-path.hh
NixOS_nix/src/libcmd/installable-derived-path.hh
#pragma once ///@file #include "installables.hh" namespace nix { struct InstallableDerivedPath : Installable { ref<Store> store; DerivedPath derivedPath; InstallableDerivedPath(ref<Store> store, DerivedPath && derivedPath) : store(store), derivedPath(std::move(derivedPath)) { } std::string what() const override; DerivedPathsWithInfo toDerivedPaths() override; std::optional<StorePath> getStorePath() override; static InstallableDerivedPath parse( ref<Store> store, std::string_view prefix, ExtendedOutputsSpec extendedOutputsSpec); }; }
612
C++
.h
20
25.95
72
0.734134
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,261
misc-store-flags.hh
NixOS_nix/src/libcmd/misc-store-flags.hh
#include "args.hh" #include "content-address.hh" namespace nix::flag { Args::Flag hashAlgo(std::string && longName, HashAlgorithm * ha); static inline Args::Flag hashAlgo(HashAlgorithm * ha) { return hashAlgo("hash-algo", ha); } Args::Flag hashAlgoOpt(std::string && longName, std::optional<HashAlgorithm> * oha); Args::Flag hashFormatWithDefault(std::string && longName, HashFormat * hf); Args::Flag hashFormatOpt(std::string && longName, std::optional<HashFormat> * ohf); static inline Args::Flag hashAlgoOpt(std::optional<HashAlgorithm> * oha) { return hashAlgoOpt("hash-algo", oha); } Args::Flag fileIngestionMethod(FileIngestionMethod * method); Args::Flag contentAddressMethod(ContentAddressMethod * method); }
728
C++
.h
18
38.833333
84
0.76662
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,262
installable-flake.hh
NixOS_nix/src/libcmd/installable-flake.hh
#pragma once ///@file #include "common-eval-args.hh" #include "installable-value.hh" namespace nix { /** * Extra info about a \ref DerivedPath "derived path" that ultimately * come from a Flake. * * Invariant: every ExtraPathInfo gotten from an InstallableFlake should * be possible to downcast to an ExtraPathInfoFlake. */ struct ExtraPathInfoFlake : ExtraPathInfoValue { /** * Extra struct to get around C++ designated initializer limitations */ struct Flake { FlakeRef originalRef; FlakeRef lockedRef; }; Flake flake; ExtraPathInfoFlake(Value && v, Flake && f) : ExtraPathInfoValue(std::move(v)), flake(std::move(f)) { } }; struct InstallableFlake : InstallableValue { FlakeRef flakeRef; Strings attrPaths; Strings prefixes; ExtendedOutputsSpec extendedOutputsSpec; const flake::LockFlags & lockFlags; mutable std::shared_ptr<flake::LockedFlake> _lockedFlake; InstallableFlake( SourceExprCommand * cmd, ref<EvalState> state, FlakeRef && flakeRef, std::string_view fragment, ExtendedOutputsSpec extendedOutputsSpec, Strings attrPaths, Strings prefixes, const flake::LockFlags & lockFlags); std::string what() const override { return flakeRef.to_string() + "#" + *attrPaths.begin(); } std::vector<std::string> getActualAttrPaths(); DerivedPathsWithInfo toDerivedPaths() override; std::pair<Value *, PosIdx> toValue(EvalState & state) override; /** * Get a cursor to every attrpath in getActualAttrPaths() that * exists. However if none exists, throw an exception. */ std::vector<ref<eval_cache::AttrCursor>> getCursors(EvalState & state) override; std::shared_ptr<flake::LockedFlake> getLockedFlake() const; FlakeRef nixpkgsFlakeRef() const; }; /** * Default flake ref for referring to Nixpkgs. For flakes that don't * have their own Nixpkgs input, or other installables. * * It is a layer violation for Nix to know about Nixpkgs; currently just * `nix develop` does. Be wary of using this / * `InstallableFlake::nixpkgsFlakeRef` more places. */ static inline FlakeRef defaultNixpkgsFlakeRef() { return FlakeRef::fromAttrs(fetchSettings, {{"type","indirect"}, {"id", "nixpkgs"}}); } ref<eval_cache::EvalCache> openEvalCache( EvalState & state, std::shared_ptr<flake::LockedFlake> lockedFlake); }
2,440
C++
.h
72
29.513889
97
0.713313
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,263
compatibility-settings.hh
NixOS_nix/src/libcmd/compatibility-settings.hh
#pragma once #include "config.hh" namespace nix { struct CompatibilitySettings : public Config { CompatibilitySettings() = default; // Added in Nix 2.24, July 2024. Setting<bool> nixShellAlwaysLooksForShellNix{this, true, "nix-shell-always-looks-for-shell-nix", R"( Before Nix 2.24, [`nix-shell`](@docroot@/command-ref/nix-shell.md) would only look at `shell.nix` if it was in the working directory - when no file was specified. Since Nix 2.24, `nix-shell` always looks for a `shell.nix`, whether that's in the working directory, or in a directory that was passed as an argument. You may set this to `false` to temporarily revert to the behavior of Nix 2.23 and older. Using this setting is not recommended. It will be deprecated and removed. )"}; // Added in Nix 2.24, July 2024. Setting<bool> nixShellShebangArgumentsRelativeToScript{ this, true, "nix-shell-shebang-arguments-relative-to-script", R"( Before Nix 2.24, relative file path expressions in arguments in a `nix-shell` shebang were resolved relative to the working directory. Since Nix 2.24, `nix-shell` resolves these paths in a manner that is relative to the [base directory](@docroot@/glossary.md#gloss-base-directory), defined as the script's directory. You may set this to `false` to temporarily revert to the behavior of Nix 2.23 and older. Using this setting is not recommended. It will be deprecated and removed. )"}; }; };
1,521
C++
.h
25
54.76
189
0.717845
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,264
installable-value.hh
NixOS_nix/src/libcmd/installable-value.hh
#pragma once ///@file #include "installables.hh" #include "flake/flake.hh" namespace nix { struct PackageInfo; struct SourceExprCommand; namespace eval_cache { class EvalCache; class AttrCursor; } struct App { std::vector<DerivedPath> context; Path program; // FIXME: add args, sandbox settings, metadata, ... }; struct UnresolvedApp { App unresolved; App resolve(ref<Store> evalStore, ref<Store> store); }; /** * Extra info about a \ref DerivedPath "derived path" that ultimately * come from a Nix language value. * * Invariant: every ExtraPathInfo gotten from an InstallableValue should * be possible to downcast to an ExtraPathInfoValue. */ struct ExtraPathInfoValue : ExtraPathInfo { /** * Extra struct to get around C++ designated initializer limitations */ struct Value { /** * An optional priority for use with "build envs". See Package */ std::optional<NixInt::Inner> priority; /** * The attribute path associated with this value. The idea is * that an installable referring to a value typically refers to * a larger value, from which we project a smaller value out * with this. */ std::string attrPath; /** * \todo merge with DerivedPath's 'outputs' field? */ ExtendedOutputsSpec extendedOutputsSpec; }; Value value; ExtraPathInfoValue(Value && v) : value(std::move(v)) { } virtual ~ExtraPathInfoValue() = default; }; /** * An Installable which corresponds a Nix language value, in addition to * a collection of \ref DerivedPath "derived paths". */ struct InstallableValue : Installable { ref<EvalState> state; InstallableValue(ref<EvalState> state) : state(state) {} virtual ~InstallableValue() { } virtual std::pair<Value *, PosIdx> toValue(EvalState & state) = 0; /** * Get a cursor to each value this Installable could refer to. * However if none exists, throw exception instead of returning * empty vector. */ virtual std::vector<ref<eval_cache::AttrCursor>> getCursors(EvalState & state); /** * Get the first and most preferred cursor this Installable could * refer to, or throw an exception if none exists. */ virtual ref<eval_cache::AttrCursor> getCursor(EvalState & state); UnresolvedApp toApp(EvalState & state); static InstallableValue & require(Installable & installable); static ref<InstallableValue> require(ref<Installable> installable); protected: /** * Handles either a plain path, or a string with a single string * context elem in the right format. The latter case is handled by * `EvalState::coerceToDerivedPath()`; see it for details. * * @param v Value that is hopefully a string or path per the above. * * @param pos Position of value to aid with diagnostics. * * @param errorCtx Arbitrary message for use in potential error message when something is wrong with `v`. * * @result A derived path (with empty info, for now) if the value * matched the above criteria. */ std::optional<DerivedPathWithInfo> trySinglePathToDerivedPaths(Value & v, const PosIdx pos, std::string_view errorCtx); }; }
3,311
C++
.h
98
28.836735
123
0.690596
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,265
repl-interacter.hh
NixOS_nix/src/libcmd/repl-interacter.hh
#pragma once /// @file #include "finally.hh" #include "types.hh" #include <functional> #include <string> namespace nix { namespace detail { /** Provides the completion hooks for the repl, without exposing its complete * internals. */ struct ReplCompleterMixin { virtual StringSet completePrefix(const std::string & prefix) = 0; }; }; enum class ReplPromptType { ReplPrompt, ContinuationPrompt, }; class ReplInteracter { public: using Guard = Finally<std::function<void()>>; virtual Guard init(detail::ReplCompleterMixin * repl) = 0; /** Returns a boolean of whether the interacter got EOF */ virtual bool getLine(std::string & input, ReplPromptType promptType) = 0; virtual ~ReplInteracter(){}; }; class ReadlineLikeInteracter : public virtual ReplInteracter { std::string historyFile; public: ReadlineLikeInteracter(std::string historyFile) : historyFile(historyFile) { } virtual Guard init(detail::ReplCompleterMixin * repl) override; virtual bool getLine(std::string & input, ReplPromptType promptType) override; virtual ~ReadlineLikeInteracter() override; }; };
1,143
C++
.h
40
25.65
82
0.747032
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,266
network-proxy.hh
NixOS_nix/src/libcmd/network-proxy.hh
#pragma once ///@file #include "types.hh" namespace nix { /** * Environment variables relating to network proxying. These are used by * a few misc commands. * * See the Environment section of https://curl.se/docs/manpage.html for details. */ extern const StringSet networkProxyVariables; /** * Heuristically check if there is a proxy connection by checking for defined * proxy variables. */ bool haveNetworkProxyConnection(); }
441
C++
.h
17
24.176471
80
0.775656
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,267
installables.hh
NixOS_nix/src/libcmd/installables.hh
#pragma once ///@file #include "path.hh" #include "outputs-spec.hh" #include "derived-path.hh" #include "built-path.hh" #include "store-api.hh" #include "build-result.hh" #include <optional> namespace nix { struct PackageInfo; enum class Realise { /** * Build the derivation. * * Postcondition: the derivation outputs exist. */ Outputs, /** * Don't build the derivation. * * Postcondition: the store derivation exists. */ Derivation, /** * Evaluate in dry-run mode. * * Postcondition: nothing. * * \todo currently unused, but could be revived if we can evaluate * derivations in-memory. */ Nothing }; /** * How to handle derivations in commands that operate on store paths. */ enum class OperateOn { /** * Operate on the output path. */ Output, /** * Operate on the .drv path. */ Derivation }; /** * Extra info about a DerivedPath * * Yes, this is empty, but that is intended. It will be sub-classed by * the subclasses of Installable to allow those to provide more info. * Certain commands will make use of this info. */ struct ExtraPathInfo { virtual ~ExtraPathInfo() = default; }; /** * A DerivedPath with \ref ExtraPathInfo "any additional info" that * commands might need from the derivation. */ struct DerivedPathWithInfo { DerivedPath path; ref<ExtraPathInfo> info; }; /** * Like DerivedPathWithInfo but extending BuiltPath with \ref * ExtraPathInfo "extra info" and also possibly the \ref BuildResult * "result of building". */ struct BuiltPathWithResult { BuiltPath path; ref<ExtraPathInfo> info; std::optional<BuildResult> result; }; /** * Shorthand, for less typing and helping us keep the choice of * collection in sync. */ typedef std::vector<DerivedPathWithInfo> DerivedPathsWithInfo; struct Installable; /** * Shorthand, for less typing and helping us keep the choice of * collection in sync. */ typedef std::vector<ref<Installable>> Installables; /** * Installables are the main positional arguments for the Nix * Command-line. * * This base class is very flexible, and just assumes and the * Installable refers to a collection of \ref DerivedPath "derived paths" with * \ref ExtraPathInfo "extra info". */ struct Installable { virtual ~Installable() { } /** * What Installable is this? * * Prints back valid CLI syntax that would result in this same * installable. It doesn't need to be exactly what the user wrote, * just something that means the same thing. */ virtual std::string what() const = 0; /** * Get the collection of \ref DerivedPathWithInfo "derived paths * with info" that this \ref Installable instalallable denotes. * * This is the main method of this class */ virtual DerivedPathsWithInfo toDerivedPaths() = 0; /** * A convenience wrapper of the above for when we expect an * installable to produce a single \ref DerivedPath "derived path" * only. * * If no or multiple \ref DerivedPath "derived paths" are produced, * and error is raised. */ DerivedPathWithInfo toDerivedPath(); /** * Return a value only if this installable is a store path or a * symlink to it. * * \todo should we move this to InstallableDerivedPath? It is only * supposed to work there anyways. Can always downcast. */ virtual std::optional<StorePath> getStorePath() { return {}; } static std::vector<BuiltPathWithResult> build( ref<Store> evalStore, ref<Store> store, Realise mode, const Installables & installables, BuildMode bMode = bmNormal); static std::vector<std::pair<ref<Installable>, BuiltPathWithResult>> build2( ref<Store> evalStore, ref<Store> store, Realise mode, const Installables & installables, BuildMode bMode = bmNormal); static std::set<StorePath> toStorePathSet( ref<Store> evalStore, ref<Store> store, Realise mode, OperateOn operateOn, const Installables & installables); static std::vector<StorePath> toStorePaths( ref<Store> evalStore, ref<Store> store, Realise mode, OperateOn operateOn, const Installables & installables); static StorePath toStorePath( ref<Store> evalStore, ref<Store> store, Realise mode, OperateOn operateOn, ref<Installable> installable); static std::set<StorePath> toDerivations( ref<Store> store, const Installables & installables, bool useDeriver = false); static BuiltPaths toBuiltPaths( ref<Store> evalStore, ref<Store> store, Realise mode, OperateOn operateOn, const Installables & installables); }; }
4,937
C++
.h
177
23.073446
80
0.677719
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,268
command-installable-value.hh
NixOS_nix/src/libcmd/command-installable-value.hh
#pragma once ///@file #include "installable-value.hh" #include "command.hh" namespace nix { /** * An InstallableCommand where the single positional argument must be an * InstallableValue in particular. */ struct InstallableValueCommand : InstallableCommand { /** * Entry point to this command */ virtual void run(ref<Store> store, ref<InstallableValue> installable) = 0; void run(ref<Store> store, ref<Installable> installable) override; }; }
473
C++
.h
18
23.611111
78
0.746667
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,269
editor-for.hh
NixOS_nix/src/libcmd/editor-for.hh
#pragma once ///@file #include "types.hh" #include "source-path.hh" namespace nix { /** * Helper function to generate args that invoke $EDITOR on * filename:lineno. */ Strings editorFor(const SourcePath & file, uint32_t line); }
236
C++
.h
11
19.818182
58
0.746606
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,270
built-path.hh
NixOS_nix/src/libcmd/built-path.hh
#pragma once ///@file #include "derived-path.hh" #include "realisation.hh" namespace nix { struct SingleBuiltPath; struct SingleBuiltPathBuilt { ref<SingleBuiltPath> drvPath; std::pair<std::string, StorePath> output; SingleDerivedPathBuilt discardOutputPath() const; std::string to_string(const StoreDirConfig & store) const; static SingleBuiltPathBuilt parse(const StoreDirConfig & store, std::string_view, std::string_view); nlohmann::json toJSON(const StoreDirConfig & store) const; bool operator ==(const SingleBuiltPathBuilt &) const noexcept; std::strong_ordering operator <=>(const SingleBuiltPathBuilt &) const noexcept; }; using _SingleBuiltPathRaw = std::variant< DerivedPathOpaque, SingleBuiltPathBuilt >; struct SingleBuiltPath : _SingleBuiltPathRaw { using Raw = _SingleBuiltPathRaw; using Raw::Raw; using Opaque = DerivedPathOpaque; using Built = SingleBuiltPathBuilt; bool operator == (const SingleBuiltPath &) const = default; auto operator <=> (const SingleBuiltPath &) const = default; inline const Raw & raw() const { return static_cast<const Raw &>(*this); } StorePath outPath() const; SingleDerivedPath discardOutputPath() const; static SingleBuiltPath parse(const StoreDirConfig & store, std::string_view); nlohmann::json toJSON(const StoreDirConfig & store) const; }; static inline ref<SingleBuiltPath> staticDrv(StorePath drvPath) { return make_ref<SingleBuiltPath>(SingleBuiltPath::Opaque { drvPath }); } /** * A built derived path with hints in the form of optional concrete output paths. * * See 'BuiltPath' for more an explanation. */ struct BuiltPathBuilt { ref<SingleBuiltPath> drvPath; std::map<std::string, StorePath> outputs; bool operator == (const BuiltPathBuilt &) const noexcept; // TODO libc++ 16 (used by darwin) missing `std::map::operator <=>`, can't do yet. //std::strong_ordering operator <=> (const BuiltPathBuilt &) const noexcept; std::string to_string(const StoreDirConfig & store) const; static BuiltPathBuilt parse(const StoreDirConfig & store, std::string_view, std::string_view); nlohmann::json toJSON(const StoreDirConfig & store) const; }; using _BuiltPathRaw = std::variant< DerivedPath::Opaque, BuiltPathBuilt >; /** * A built path. Similar to a DerivedPath, but enriched with the corresponding * output path(s). */ struct BuiltPath : _BuiltPathRaw { using Raw = _BuiltPathRaw; using Raw::Raw; using Opaque = DerivedPathOpaque; using Built = BuiltPathBuilt; bool operator == (const BuiltPath &) const = default; // TODO libc++ 16 (used by darwin) missing `std::map::operator <=>`, can't do yet. //auto operator <=> (const BuiltPath &) const = default; inline const Raw & raw() const { return static_cast<const Raw &>(*this); } StorePathSet outPaths() const; RealisedPath::Set toRealisedPaths(Store & store) const; nlohmann::json toJSON(const StoreDirConfig & store) const; }; typedef std::vector<BuiltPath> BuiltPaths; }
3,107
C++
.h
79
35.405063
104
0.729
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,271
installable-attr-path.hh
NixOS_nix/src/libcmd/installable-attr-path.hh
#pragma once ///@file #include "globals.hh" #include "installable-value.hh" #include "outputs-spec.hh" #include "command.hh" #include "attr-path.hh" #include "common-eval-args.hh" #include "derivations.hh" #include "eval-inline.hh" #include "eval.hh" #include "get-drvs.hh" #include "store-api.hh" #include "shared.hh" #include "eval-cache.hh" #include "url.hh" #include "registry.hh" #include "build-result.hh" #include <regex> #include <queue> #include <nlohmann/json.hpp> namespace nix { class InstallableAttrPath : public InstallableValue { SourceExprCommand & cmd; RootValue v; std::string attrPath; ExtendedOutputsSpec extendedOutputsSpec; InstallableAttrPath( ref<EvalState> state, SourceExprCommand & cmd, Value * v, const std::string & attrPath, ExtendedOutputsSpec extendedOutputsSpec); std::string what() const override { return attrPath; }; std::pair<Value *, PosIdx> toValue(EvalState & state) override; DerivedPathsWithInfo toDerivedPaths() override; public: static InstallableAttrPath parse( ref<EvalState> state, SourceExprCommand & cmd, Value * v, std::string_view prefix, ExtendedOutputsSpec extendedOutputsSpec); }; }
1,265
C++
.h
46
23.717391
67
0.724109
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,272
legacy.hh
NixOS_nix/src/libcmd/legacy.hh
#pragma once ///@file #include <functional> #include <map> #include <string> namespace nix { typedef std::function<void(int, char * *)> MainFunction; struct RegisterLegacyCommand { typedef std::map<std::string, MainFunction> Commands; static Commands * commands; RegisterLegacyCommand(const std::string & name, MainFunction fun) { if (!commands) commands = new Commands; (*commands)[name] = fun; } }; }
445
C++
.h
18
21.388889
69
0.703088
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,273
command.hh
NixOS_nix/src/libcmd/command.hh
#pragma once ///@file #include "installable-value.hh" #include "args.hh" #include "common-eval-args.hh" #include "path.hh" #include "flake/lockfile.hh" #include <optional> namespace nix { extern std::string programPath; extern char ** savedArgv; class EvalState; struct Pos; class Store; static constexpr Command::Category catHelp = -1; static constexpr Command::Category catSecondary = 100; static constexpr Command::Category catUtility = 101; static constexpr Command::Category catNixInstallation = 102; static constexpr auto installablesCategory = "Options that change the interpretation of [installables](@docroot@/command-ref/new-cli/nix.md#installables)"; struct NixMultiCommand : MultiCommand, virtual Command { nlohmann::json toJSON() override; using MultiCommand::MultiCommand; virtual void run() override; }; // For the overloaded run methods #pragma GCC diagnostic ignored "-Woverloaded-virtual" /** * A command that requires a \ref Store "Nix store". */ struct StoreCommand : virtual Command { StoreCommand(); void run() override; ref<Store> getStore(); virtual ref<Store> createStore(); /** * Main entry point, with a `Store` provided */ virtual void run(ref<Store>) = 0; private: std::shared_ptr<Store> _store; }; /** * A command that copies something between `--from` and `--to` \ref * Store stores. */ struct CopyCommand : virtual StoreCommand { std::string srcUri, dstUri; CopyCommand(); ref<Store> createStore() override; ref<Store> getDstStore(); }; /** * A command that needs to evaluate Nix language expressions. */ struct EvalCommand : virtual StoreCommand, MixEvalArgs { bool startReplOnEvalErrors = false; bool ignoreExceptionsDuringTry = false; EvalCommand(); ~EvalCommand(); ref<Store> getEvalStore(); ref<EvalState> getEvalState(); private: std::shared_ptr<Store> evalStore; std::shared_ptr<EvalState> evalState; }; /** * A mixin class for commands that process flakes, adding a few standard * flake-related options/flags. */ struct MixFlakeOptions : virtual Args, EvalCommand { flake::LockFlags lockFlags; MixFlakeOptions(); /** * The completion for some of these flags depends on the flake(s) in * question. * * This method should be implemented to gather all flakerefs the * command is operating with (presumably specified via some other * arguments) so that the completions for these flags can use them. */ virtual std::vector<FlakeRef> getFlakeRefsForCompletion() { return {}; } }; struct SourceExprCommand : virtual Args, MixFlakeOptions { std::optional<Path> file; std::optional<std::string> expr; SourceExprCommand(); Installables parseInstallables(ref<Store> store, std::vector<std::string> ss); ref<Installable> parseInstallable(ref<Store> store, const std::string & installable); virtual Strings getDefaultFlakeAttrPaths(); virtual Strings getDefaultFlakeAttrPathPrefixes(); /** * Complete an installable from the given prefix. */ void completeInstallable(AddCompletions & completions, std::string_view prefix); /** * Convenience wrapper around the underlying function to make setting the * callback easier. */ CompleterClosure getCompleteInstallable(); }; /** * A mixin class for commands that need a read-only flag. * * What exactly is "read-only" is unspecified, but it will usually be * the \ref Store "Nix store". */ struct MixReadOnlyOption : virtual Args { MixReadOnlyOption(); }; /** * Like InstallablesCommand but the installables are not loaded. * * This is needed by `CmdRepl` which wants to load (and reload) the * installables itself. */ struct RawInstallablesCommand : virtual Args, SourceExprCommand { RawInstallablesCommand(); virtual void run(ref<Store> store, std::vector<std::string> && rawInstallables) = 0; void run(ref<Store> store) override; // FIXME make const after `CmdRepl`'s override is fixed up virtual void applyDefaultInstallables(std::vector<std::string> & rawInstallables); bool readFromStdIn = false; std::vector<FlakeRef> getFlakeRefsForCompletion() override; private: std::vector<std::string> rawInstallables; }; /** * A command that operates on a list of "installables", which can be * store paths, attribute paths, Nix expressions, etc. */ struct InstallablesCommand : RawInstallablesCommand { virtual void run(ref<Store> store, Installables && installables) = 0; void run(ref<Store> store, std::vector<std::string> && rawInstallables) override; }; /** * A command that operates on exactly one "installable". */ struct InstallableCommand : virtual Args, SourceExprCommand { InstallableCommand(); virtual void run(ref<Store> store, ref<Installable> installable) = 0; void run(ref<Store> store) override; std::vector<FlakeRef> getFlakeRefsForCompletion() override; private: std::string _installable{"."}; }; struct MixOperateOnOptions : virtual Args { OperateOn operateOn = OperateOn::Output; MixOperateOnOptions(); }; /** * A command that operates on zero or more extant store paths. * * If the argument the user passes is a some sort of recipe for a path * not yet built, it must be built first. */ struct BuiltPathsCommand : InstallablesCommand, virtual MixOperateOnOptions { private: bool recursive = false; bool all = false; protected: Realise realiseMode = Realise::Derivation; public: BuiltPathsCommand(bool recursive = false); virtual void run(ref<Store> store, BuiltPaths && paths) = 0; void run(ref<Store> store, Installables && installables) override; void applyDefaultInstallables(std::vector<std::string> & rawInstallables) override; }; struct StorePathsCommand : public BuiltPathsCommand { StorePathsCommand(bool recursive = false); virtual void run(ref<Store> store, StorePaths && storePaths) = 0; void run(ref<Store> store, BuiltPaths && paths) override; }; /** * A command that operates on exactly one store path. */ struct StorePathCommand : public StorePathsCommand { virtual void run(ref<Store> store, const StorePath & storePath) = 0; void run(ref<Store> store, StorePaths && storePaths) override; }; /** * A helper class for registering \ref Command commands globally. */ struct RegisterCommand { typedef std::map<std::vector<std::string>, std::function<ref<Command>()>> Commands; static Commands * commands; RegisterCommand(std::vector<std::string> && name, std::function<ref<Command>()> command) { if (!commands) commands = new Commands; commands->emplace(name, command); } static nix::Commands getCommandsFor(const std::vector<std::string> & prefix); }; template<class T> static RegisterCommand registerCommand(const std::string & name) { return RegisterCommand({name}, []() { return make_ref<T>(); }); } template<class T> static RegisterCommand registerCommand2(std::vector<std::string> && name) { return RegisterCommand(std::move(name), []() { return make_ref<T>(); }); } struct MixProfile : virtual StoreCommand { std::optional<Path> profile; MixProfile(); /* If 'profile' is set, make it point at 'storePath'. */ void updateProfile(const StorePath & storePath); /* If 'profile' is set, make it point at the store path produced by 'buildables'. */ void updateProfile(const BuiltPaths & buildables); }; struct MixDefaultProfile : MixProfile { MixDefaultProfile(); }; struct MixEnvironment : virtual Args { StringSet keepVars; StringSet unsetVars; std::map<std::string, std::string> setVars; bool ignoreEnvironment; MixEnvironment(); /*** * Modify global environ based on `ignoreEnvironment`, `keep`, * `unset`, and `added`. It's expected that exec will be called * before this class goes out of scope, otherwise `environ` will * become invalid. */ void setEnviron(); }; void completeFlakeInputPath( AddCompletions & completions, ref<EvalState> evalState, const std::vector<FlakeRef> & flakeRefs, std::string_view prefix); void completeFlakeRef(AddCompletions & completions, ref<Store> store, std::string_view prefix); void completeFlakeRefWithFragment( AddCompletions & completions, ref<EvalState> evalState, flake::LockFlags lockFlags, Strings attrPathPrefixes, const Strings & defaultFlakeAttrPaths, std::string_view prefix); std::string showVersions(const std::set<std::string> & versions); void printClosureDiff( ref<Store> store, const StorePath & beforePath, const StorePath & afterPath, std::string_view indent); }
8,796
C++
.h
268
29.309701
114
0.731722
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,274
repl.hh
NixOS_nix/src/libcmd/repl.hh
#pragma once ///@file #include "eval.hh" namespace nix { struct AbstractNixRepl { ref<EvalState> state; Bindings * autoArgs; AbstractNixRepl(ref<EvalState> state) : state(state) { } virtual ~AbstractNixRepl() { } typedef std::vector<std::pair<Value*,std::string>> AnnotatedValues; using RunNix = void(Path program, const Strings & args, const std::optional<std::string> & input); /** * @param runNix Function to run the nix CLI to support various * `:<something>` commands. Optional; if not provided, * everything else will still work fine, but those commands won't. */ static std::unique_ptr<AbstractNixRepl> create( const LookupPath & lookupPath, nix::ref<Store> store, ref<EvalState> state, std::function<AnnotatedValues()> getValues, RunNix * runNix = nullptr); static ReplExitStatus runSimple( ref<EvalState> evalState, const ValMap & extraEnv); virtual void initEnv() = 0; virtual ReplExitStatus mainLoop() = 0; }; }
1,071
C++
.h
33
26.969697
102
0.670565
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,275
lexer-helpers.hh
NixOS_nix/src/libexpr/lexer-helpers.hh
#pragma once namespace nix::lexer::internal { void initLoc(YYLTYPE * loc); void adjustLoc(yyscan_t yyscanner, YYLTYPE * loc, const char * s, size_t len); } // namespace nix::lexer
184
C++
.h
5
35
78
0.742857
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,276
eval-gc.hh
NixOS_nix/src/libexpr/eval-gc.hh
#pragma once ///@file #include <cstddef> #if HAVE_BOEHMGC # define GC_INCLUDE_NEW # include <gc/gc.h> # include <gc/gc_cpp.h> # include <gc/gc_allocator.h> #else # include <memory> /* Some dummy aliases for Boehm GC definitions to reduce the number of #ifdefs. */ template<typename T> using traceable_allocator = std::allocator<T>; template<typename T> using gc_allocator = std::allocator<T>; # define GC_MALLOC_ATOMIC std::malloc struct gc {}; #endif namespace nix { /** * Initialise the Boehm GC, if applicable. */ void initGC(); /** * Make sure `initGC` has already been called. */ void assertGCInitialized(); #ifdef HAVE_BOEHMGC /** * The number of GC cycles since initGC(). */ size_t getGCCycles(); #endif } // namespace nix
762
C++
.h
36
19.444444
70
0.729196
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,277
search-path.hh
NixOS_nix/src/libexpr/search-path.hh
#pragma once ///@file #include <optional> #include "types.hh" #include "comparator.hh" namespace nix { /** * A "search path" is a list of ways look for something, used with * `builtins.findFile` and `< >` lookup expressions. */ struct LookupPath { /** * A single element of a `LookupPath`. * * Each element is tried in succession when looking up a path. The first * element to completely match wins. */ struct Elem; /** * The first part of a `LookupPath::Elem` pair. * * Called a "prefix" because it takes the form of a prefix of a file * path (first `n` path components). When looking up a path, to use * a `LookupPath::Elem`, its `Prefix` must match the path. */ struct Prefix; /** * The second part of a `LookupPath::Elem` pair. * * It is either a path or a URL (with certain restrictions / extra * structure). * * If the prefix of the path we are looking up matches, we then * check if the rest of the path points to something that exists * within the directory denoted by this. If so, the * `LookupPath::Elem` as a whole matches, and that *something* being * pointed to by the rest of the path we are looking up is the * result. */ struct Path; /** * The list of search path elements. Each one is checked for a path * when looking up. (The actual lookup entry point is in `EvalState` * not in this class.) */ std::list<LookupPath::Elem> elements; /** * Parse a string into a `LookupPath` */ static LookupPath parse(const Strings & rawElems); }; struct LookupPath::Prefix { /** * Underlying string * * @todo Should we normalize this when constructing a `LookupPath::Prefix`? */ std::string s; GENERATE_CMP(LookupPath::Prefix, me->s); /** * If the path possibly matches this search path element, return the * suffix that we should look for inside the resolved value of the * element * Note the double optionality in the name. While we might have a matching prefix, the suffix may not exist. */ std::optional<std::string_view> suffixIfPotentialMatch(std::string_view path) const; }; struct LookupPath::Path { /** * The location of a search path item, as a path or URL. * * @todo Maybe change this to `std::variant<SourcePath, URL>`. */ std::string s; GENERATE_CMP(LookupPath::Path, me->s); }; struct LookupPath::Elem { Prefix prefix; Path path; GENERATE_CMP(LookupPath::Elem, me->prefix, me->path); /** * Parse a string into a `LookupPath::Elem` */ static LookupPath::Elem parse(std::string_view rawElem); }; }
2,746
C++
.h
90
25.811111
112
0.654663
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,278
print-options.hh
NixOS_nix/src/libexpr/print-options.hh
#pragma once /** * @file * @brief Options for printing Nix values. */ #include <limits> namespace nix { /** * How errors should be handled when printing values. */ enum class ErrorPrintBehavior { /** * Print the first line of the error in brackets: `«error: oh no!»` */ Print, /** * Throw the error to the code that attempted to print the value, instead * of suppressing it it. */ Throw, /** * Only throw the error if encountered at the top level of the expression. * * This will cause expressions like `builtins.throw "uh oh!"` to throw * errors, but will print attribute sets and other nested structures * containing values that error (like `nixpkgs`) normally. */ ThrowTopLevel, }; /** * Options for printing Nix values. */ struct PrintOptions { /** * If true, output ANSI color sequences. */ bool ansiColors = false; /** * If true, force values. */ bool force = false; /** * If true and `force` is set, print derivations as * `«derivation /nix/store/...»` instead of as attribute sets. */ bool derivationPaths = false; /** * If true, track which values have been printed and skip them on * subsequent encounters. Useful for self-referential values. */ bool trackRepeated = true; /** * Maximum depth to evaluate to. */ size_t maxDepth = std::numeric_limits<size_t>::max(); /** * Maximum number of attributes in attribute sets to print. * * Note that this is a limit for the entire print invocation, not for each * attribute set encountered. */ size_t maxAttrs = std::numeric_limits<size_t>::max(); /** * Maximum number of list items to print. * * Note that this is a limit for the entire print invocation, not for each * list encountered. */ size_t maxListItems = std::numeric_limits<size_t>::max(); /** * Maximum string length to print. */ size_t maxStringLength = std::numeric_limits<size_t>::max(); /** * Indentation width for pretty-printing. * * If set to 0 (the default), values are not pretty-printed. */ size_t prettyIndent = 0; /** * How to handle errors encountered while printing values. */ ErrorPrintBehavior errors = ErrorPrintBehavior::Print; /** * True if pretty-printing is enabled. */ inline bool shouldPrettyPrint() { return prettyIndent > 0; } }; /** * `PrintOptions` for unknown and therefore potentially large values in error messages, * to avoid printing "too much" output. */ static PrintOptions errorPrintOptions = PrintOptions { .ansiColors = true, .maxDepth = 10, .maxAttrs = 10, .maxListItems = 10, .maxStringLength = 1024, }; }
2,852
C++
.h
104
22.644231
87
0.643695
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,279
eval-cache.hh
NixOS_nix/src/libexpr/eval-cache.hh
#pragma once ///@file #include "sync.hh" #include "hash.hh" #include "eval.hh" #include <functional> #include <variant> namespace nix::eval_cache { struct AttrDb; class AttrCursor; struct CachedEvalError : EvalError { const ref<AttrCursor> cursor; const Symbol attr; CachedEvalError(ref<AttrCursor> cursor, Symbol attr); /** * Evaluate this attribute, which should result in a regular * `EvalError` exception being thrown. */ [[noreturn]] void force(); }; class EvalCache : public std::enable_shared_from_this<EvalCache> { friend class AttrCursor; friend struct CachedEvalError; std::shared_ptr<AttrDb> db; EvalState & state; typedef std::function<Value *()> RootLoader; RootLoader rootLoader; RootValue value; Value * getRootValue(); public: EvalCache( std::optional<std::reference_wrapper<const Hash>> useCache, EvalState & state, RootLoader rootLoader); ref<AttrCursor> getRoot(); }; enum AttrType { Placeholder = 0, FullAttrs = 1, String = 2, Missing = 3, Misc = 4, Failed = 5, Bool = 6, ListOfStrings = 7, Int = 8, }; struct placeholder_t {}; struct missing_t {}; struct misc_t {}; struct failed_t {}; struct int_t { NixInt x; }; typedef uint64_t AttrId; typedef std::pair<AttrId, Symbol> AttrKey; typedef std::pair<std::string, NixStringContext> string_t; typedef std::variant< std::vector<Symbol>, string_t, placeholder_t, missing_t, misc_t, failed_t, bool, int_t, std::vector<std::string> > AttrValue; class AttrCursor : public std::enable_shared_from_this<AttrCursor> { friend class EvalCache; friend struct CachedEvalError; ref<EvalCache> root; typedef std::optional<std::pair<std::shared_ptr<AttrCursor>, Symbol>> Parent; Parent parent; RootValue _value; std::optional<std::pair<AttrId, AttrValue>> cachedValue; AttrKey getKey(); Value & getValue(); public: AttrCursor( ref<EvalCache> root, Parent parent, Value * value = nullptr, std::optional<std::pair<AttrId, AttrValue>> && cachedValue = {}); std::vector<Symbol> getAttrPath() const; std::vector<Symbol> getAttrPath(Symbol name) const; std::string getAttrPathStr() const; std::string getAttrPathStr(Symbol name) const; Suggestions getSuggestionsForAttr(Symbol name); std::shared_ptr<AttrCursor> maybeGetAttr(Symbol name); std::shared_ptr<AttrCursor> maybeGetAttr(std::string_view name); ref<AttrCursor> getAttr(Symbol name); ref<AttrCursor> getAttr(std::string_view name); /** * Get an attribute along a chain of attrsets. Note that this does * not auto-call functors or functions. */ OrSuggestions<ref<AttrCursor>> findAlongAttrPath(const std::vector<Symbol> & attrPath); std::string getString(); string_t getStringWithContext(); bool getBool(); NixInt getInt(); std::vector<std::string> getListOfStrings(); std::vector<Symbol> getAttrs(); bool isDerivation(); Value & forceValue(); /** * Force creation of the .drv file in the Nix store. */ StorePath forceDerivation(); }; }
3,244
C++
.h
114
23.929825
91
0.687824
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,280
print-ambiguous.hh
NixOS_nix/src/libexpr/print-ambiguous.hh
#pragma once #include "value.hh" namespace nix { /** * Print a value in the deprecated format used by `nix-instantiate --eval` and * `nix-env` (for manifests). * * This output can't be changed because it's part of the `nix-instantiate` API, * but it produces ambiguous output; unevaluated thunks and lambdas (and a few * other types) are printed as Nix path syntax like `<CODE>`. * * See: https://github.com/NixOS/nix/issues/9730 */ void printAmbiguous( Value &v, const SymbolTable &symbols, std::ostream &str, std::set<const void *> *seen, int depth); }
588
C++
.h
20
26.75
79
0.707447
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,281
eval-inline.hh
NixOS_nix/src/libexpr/eval-inline.hh
#pragma once ///@file #include "print.hh" #include "eval.hh" #include "eval-error.hh" #include "eval-settings.hh" namespace nix { /** * Note: Various places expect the allocated memory to be zeroed. */ [[gnu::always_inline]] inline void * allocBytes(size_t n) { void * p; #if HAVE_BOEHMGC p = GC_MALLOC(n); #else p = calloc(n, 1); #endif if (!p) throw std::bad_alloc(); return p; } [[gnu::always_inline]] Value * EvalState::allocValue() { #if HAVE_BOEHMGC /* We use the boehm batch allocator to speed up allocations of Values (of which there are many). GC_malloc_many returns a linked list of objects of the given size, where the first word of each object is also the pointer to the next object in the list. This also means that we have to explicitly clear the first word of every object we take. */ if (!*valueAllocCache) { *valueAllocCache = GC_malloc_many(sizeof(Value)); if (!*valueAllocCache) throw std::bad_alloc(); } /* GC_NEXT is a convenience macro for accessing the first word of an object. Take the first list item, advance the list to the next item, and clear the next pointer. */ void * p = *valueAllocCache; *valueAllocCache = GC_NEXT(p); GC_NEXT(p) = nullptr; #else void * p = allocBytes(sizeof(Value)); #endif nrValues++; return (Value *) p; } [[gnu::always_inline]] Env & EvalState::allocEnv(size_t size) { nrEnvs++; nrValuesInEnvs += size; Env * env; #if HAVE_BOEHMGC if (size == 1) { /* see allocValue for explanations. */ if (!*env1AllocCache) { *env1AllocCache = GC_malloc_many(sizeof(Env) + sizeof(Value *)); if (!*env1AllocCache) throw std::bad_alloc(); } void * p = *env1AllocCache; *env1AllocCache = GC_NEXT(p); GC_NEXT(p) = nullptr; env = (Env *) p; } else #endif env = (Env *) allocBytes(sizeof(Env) + size * sizeof(Value *)); /* We assume that env->values has been cleared by the allocator; maybeThunk() and lookupVar fromWith expect this. */ return *env; } [[gnu::always_inline]] void EvalState::forceValue(Value & v, const PosIdx pos) { if (v.isThunk()) { Env * env = v.payload.thunk.env; Expr * expr = v.payload.thunk.expr; try { v.mkBlackhole(); //checkInterrupt(); expr->eval(*this, *env, v); } catch (...) { v.mkThunk(env, expr); tryFixupBlackHolePos(v, pos); throw; } } else if (v.isApp()) callFunction(*v.payload.app.left, *v.payload.app.right, v, pos); } [[gnu::always_inline]] inline void EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx) { forceAttrs(v, [&]() { return pos; }, errorCtx); } template <typename Callable> [[gnu::always_inline]] inline void EvalState::forceAttrs(Value & v, Callable getPos, std::string_view errorCtx) { PosIdx pos = getPos(); forceValue(v, pos); if (v.type() != nAttrs) { error<TypeError>( "expected a set but found %1%: %2%", showType(v), ValuePrinter(*this, v, errorPrintOptions) ).withTrace(pos, errorCtx).debugThrow(); } } [[gnu::always_inline]] inline void EvalState::forceList(Value & v, const PosIdx pos, std::string_view errorCtx) { forceValue(v, pos); if (!v.isList()) { error<TypeError>( "expected a list but found %1%: %2%", showType(v), ValuePrinter(*this, v, errorPrintOptions) ).withTrace(pos, errorCtx).debugThrow(); } } [[gnu::always_inline]] inline CallDepth EvalState::addCallDepth(const PosIdx pos) { if (callDepth > settings.maxCallDepth) error<EvalError>("stack overflow; max-call-depth exceeded").atPos(pos).debugThrow(); return CallDepth(callDepth); }; }
3,906
C++
.h
125
26
120
0.630724
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,282
eval-settings.hh
NixOS_nix/src/libexpr/eval-settings.hh
#pragma once ///@file #include "config.hh" #include "ref.hh" namespace nix { class Store; struct EvalSettings : Config { /** * Function used to interpet look path entries of a given scheme. * * The argument is the non-scheme part of the lookup path entry (see * `LookupPathHooks` below). * * The return value is (a) whether the entry was valid, and, if so, * what does it map to. * * @todo Return (`std::optional` of) `SourceAccssor` or something * more structured instead of mere `std::string`? */ using LookupPathHook = std::optional<std::string>(ref<Store> store, std::string_view); /** * Map from "scheme" to a `LookupPathHook`. * * Given a lookup path value (i.e. either the whole thing, or after * the `<key>=`) in the form of: * * ``` * <scheme>:<arbitrary string> * ``` * * if `<scheme>` is a key in this map, then `<arbitrary string>` is * passed to the hook that is the value in this map. */ using LookupPathHooks = std::map<std::string, std::function<LookupPathHook>>; EvalSettings(bool & readOnlyMode, LookupPathHooks lookupPathHooks = {}); bool & readOnlyMode; static Strings getDefaultNixPath(); static bool isPseudoUrl(std::string_view s); static Strings parseNixPath(const std::string & s); static std::string resolvePseudoUrl(std::string_view url); LookupPathHooks lookupPathHooks; Setting<bool> enableNativeCode{this, false, "allow-unsafe-native-code-during-evaluation", R"( Enable built-in functions that allow executing native code. In particular, this adds: - `builtins.importNative` *path* *symbol* Opens dynamic shared object (DSO) at *path*, loads the function with the symbol name *symbol* from it and runs it. The loaded function must have the following signature: ```cpp extern "C" typedef void (*ValueInitialiser) (EvalState & state, Value & v); ``` The [Nix C++ API documentation](@docroot@/development/documentation.md#api-documentation) has more details on evaluator internals. - `builtins.exec` *arguments* Execute a program, where *arguments* are specified as a list of strings, and parse its output as a Nix expression. )"}; Setting<Strings> nixPath{ this, {}, "nix-path", R"( List of search paths to use for [lookup path](@docroot@/language/constructs/lookup-path.md) resolution. This setting determines the value of [`builtins.nixPath`](@docroot@/language/builtins.md#builtins-nixPath) and can be used with [`builtins.findFile`](@docroot@/language/builtins.md#builtins-findFile). - The configuration setting is overridden by the [`NIX_PATH`](@docroot@/command-ref/env-common.md#env-NIX_PATH) environment variable. - `NIX_PATH` is overridden by [specifying the setting as the command line flag](@docroot@/command-ref/conf-file.md#command-line-flags) `--nix-path`. - Any current value is extended by the [`-I` option](@docroot@/command-ref/opt-common.md#opt-I) or `--extra-nix-path`. If the respective paths are accessible, the default values are: - `$HOME/.nix-defexpr/channels` The [user channel link](@docroot@/command-ref/files/default-nix-expression.md#user-channel-link), pointing to the current state of [channels](@docroot@/command-ref/files/channels.md) for the current user. - `nixpkgs=$NIX_STATE_DIR/profiles/per-user/root/channels/nixpkgs` The current state of the `nixpkgs` channel for the `root` user. - `$NIX_STATE_DIR/profiles/per-user/root/channels` The current state of all channels for the `root` user. These files are set up by the [Nix installer](@docroot@/installation/installing-binary.md). See [`NIX_STATE_DIR`](@docroot@/command-ref/env-common.md#env-NIX_STATE_DIR) for details on the environment variable. > **Note** > > If [restricted evaluation](@docroot@/command-ref/conf-file.md#conf-restrict-eval) is enabled, the default value is empty. > > If [pure evaluation](#conf-pure-eval) is enabled, `builtins.nixPath` *always* evaluates to the empty list `[ ]`. )", {}, false}; Setting<std::string> currentSystem{ this, "", "eval-system", R"( This option defines [`builtins.currentSystem`](@docroot@/language/builtins.md#builtins-currentSystem) in the Nix language if it is set as a non-empty string. Otherwise, if it is defined as the empty string (the default), the value of the [`system` ](#conf-system) configuration setting is used instead. Unlike `system`, this setting does not change what kind of derivations can be built locally. This is useful for evaluating Nix code on one system to produce derivations to be built on another type of system. )"}; /** * Implements the `eval-system` vs `system` defaulting logic * described for `eval-system`. */ const std::string & getCurrentSystem() const; Setting<bool> restrictEval{ this, false, "restrict-eval", R"( If set to `true`, the Nix evaluator will not allow access to any files outside of [`builtins.nixPath`](@docroot@/language/builtins.md#builtins-nixPath), or to URIs outside of [`allowed-uris`](@docroot@/command-ref/conf-file.md#conf-allowed-uris). )"}; Setting<bool> pureEval{this, false, "pure-eval", R"( Pure evaluation mode ensures that the result of Nix expressions is fully determined by explicitly declared inputs, and not influenced by external state: - Restrict file system and network access to files specified by cryptographic hash - Disable impure constants: - [`builtins.currentSystem`](@docroot@/language/builtins.md#builtins-currentSystem) - [`builtins.currentTime`](@docroot@/language/builtins.md#builtins-currentTime) - [`builtins.nixPath`](@docroot@/language/builtins.md#builtins-nixPath) - [`builtins.storePath`](@docroot@/language/builtins.md#builtins-storePath) )" }; Setting<bool> enableImportFromDerivation{ this, true, "allow-import-from-derivation", R"( By default, Nix allows [Import from Derivation](@docroot@/language/import-from-derivation.md). With this option set to `false`, Nix will throw an error when evaluating an expression that uses this feature, even when the required store object is readily available. This ensures that evaluation will not require any builds to take place, regardless of the state of the store. )"}; Setting<Strings> allowedUris{this, {}, "allowed-uris", R"( A list of URI prefixes to which access is allowed in restricted evaluation mode. For example, when set to `https://github.com/NixOS`, builtin functions such as `fetchGit` are allowed to access `https://github.com/NixOS/patchelf.git`. Access is granted when - the URI is equal to the prefix, - or the URI is a subpath of the prefix, - or the prefix is a URI scheme ended by a colon `:` and the URI has the same scheme. )"}; Setting<bool> traceFunctionCalls{this, false, "trace-function-calls", R"( If set to `true`, the Nix evaluator will trace every function call. Nix will print a log message at the "vomit" level for every function entrance and function exit. function-trace entered undefined position at 1565795816999559622 function-trace exited undefined position at 1565795816999581277 function-trace entered /nix/store/.../example.nix:226:41 at 1565795253249935150 function-trace exited /nix/store/.../example.nix:226:41 at 1565795253249941684 The `undefined position` means the function call is a builtin. Use the `contrib/stack-collapse.py` script distributed with the Nix source code to convert the trace logs in to a format suitable for `flamegraph.pl`. )"}; Setting<bool> useEvalCache{this, true, "eval-cache", R"( Whether to use the flake evaluation cache. Certain commands won't have to evaluate when invoked for the second time with a particular version of a flake. Intermediate results are not cached. )"}; Setting<bool> ignoreExceptionsDuringTry{this, false, "ignore-try", R"( If set to true, ignore exceptions inside 'tryEval' calls when evaluating nix expressions in debug mode (using the --debugger flag). By default the debugger will pause on all exceptions. )"}; Setting<bool> traceVerbose{this, false, "trace-verbose", "Whether `builtins.traceVerbose` should trace its first argument when evaluated."}; Setting<unsigned int> maxCallDepth{this, 10000, "max-call-depth", "The maximum function call depth to allow before erroring."}; Setting<bool> builtinsTraceDebugger{this, false, "debugger-on-trace", R"( If set to true and the `--debugger` flag is given, the following functions will enter the debugger like [`builtins.break`](@docroot@/language/builtins.md#builtins-break). * [`builtins.trace`](@docroot@/language/builtins.md#builtins-trace) * [`builtins.traceVerbose`](@docroot@/language/builtins.md#builtins-traceVerbose) if [`trace-verbose`](#conf-trace-verbose) is set to true. * [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn) This is useful for debugging warnings in third-party Nix code. )"}; Setting<bool> builtinsDebuggerOnWarn{this, false, "debugger-on-warn", R"( If set to true and the `--debugger` flag is given, [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn) will enter the debugger like [`builtins.break`](@docroot@/language/builtins.md#builtins-break). This is useful for debugging warnings in third-party Nix code. Use [`debugger-on-trace`](#conf-debugger-on-trace) to also enter the debugger on legacy warnings that are logged with [`builtins.trace`](@docroot@/language/builtins.md#builtins-trace). )"}; Setting<bool> builtinsAbortOnWarn{this, false, "abort-on-warn", R"( If set to true, [`builtins.warn`](@docroot@/language/builtins.md#builtins-warn) will throw an error when logging a warning. This will give you a stack trace that leads to the location of the warning. This is useful for finding information about warnings in third-party Nix code when you can not start the interactive debugger, such as when Nix is called from a non-interactive script. See [`debugger-on-warn`](#conf-debugger-on-warn). Currently, a stack trace can only be produced when the debugger is enabled, or when evaluation is aborted. This option can be enabled by setting `NIX_ABORT_ON_WARN=1` in the environment. )"}; }; /** * Conventionally part of the default nix path in impure mode. */ Path getNixDefExpr(); }
11,463
C++
.h
197
49.28934
244
0.67214
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,283
json-to-value.hh
NixOS_nix/src/libexpr/json-to-value.hh
#pragma once ///@file #include "error.hh" #include <string> namespace nix { class EvalState; struct Value; MakeError(JSONParseError, Error); void parseJSON(EvalState & state, const std::string_view & s, Value & v); }
224
C++
.h
10
20.7
73
0.763285
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,284
repl-exit-status.hh
NixOS_nix/src/libexpr/repl-exit-status.hh
#pragma once namespace nix { /** * Exit status returned from the REPL. */ enum class ReplExitStatus { /** * The user exited with `:quit`. The program (e.g., if the REPL was acting * as the debugger) should exit. */ QuitAll, /** * The user exited with `:continue`. The program should continue running. */ Continue, }; }
365
C++
.h
17
17.764706
78
0.634783
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,285
parser-state.hh
NixOS_nix/src/libexpr/parser-state.hh
#pragma once ///@file #include <limits> #include "eval.hh" namespace nix { /** * @note Storing a C-style `char *` and `size_t` allows us to avoid * having to define the special members that using string_view here * would implicitly delete. */ struct StringToken { const char * p; size_t l; bool hasIndentation; operator std::string_view() const { return {p, l}; } }; // This type must be trivially copyable; see YYLTYPE_IS_TRIVIAL in parser.y. struct ParserLocation { int beginOffset; int endOffset; // backup to recover from yyless(0) int stashedBeginOffset, stashedEndOffset; void stash() { stashedBeginOffset = beginOffset; stashedEndOffset = endOffset; } void unstash() { beginOffset = stashedBeginOffset; endOffset = stashedEndOffset; } /** Latest doc comment position, or 0. */ int doc_comment_first_column, doc_comment_last_column; }; struct LexerState { /** * Tracks the distance to the last doc comment, in terms of lexer tokens. * * The lexer sets this to 0 when reading a doc comment, and increments it * for every matched rule; see `lexer-helpers.cc`. * Whitespace and comment rules decrement the distance, so that they result * in a net 0 change in distance. */ int docCommentDistance = std::numeric_limits<int>::max(); /** * The location of the last doc comment. * * (stashing fields are not used) */ ParserLocation lastDocCommentLoc; /** * @brief Maps some positions to a DocComment, where the comment is relevant to the location. */ std::unordered_map<PosIdx, DocComment> & positionToDocComment; PosTable & positions; PosTable::Origin origin; PosIdx at(const ParserLocation & loc); }; struct ParserState { const LexerState & lexerState; SymbolTable & symbols; PosTable & positions; Expr * result; SourcePath basePath; PosTable::Origin origin; const ref<SourceAccessor> rootFS; const Expr::AstSymbols & s; const EvalSettings & settings; void dupAttr(const AttrPath & attrPath, const PosIdx pos, const PosIdx prevPos); void dupAttr(Symbol attr, const PosIdx pos, const PosIdx prevPos); void addAttr(ExprAttrs * attrs, AttrPath && attrPath, const ParserLocation & loc, Expr * e, const ParserLocation & exprLoc); Formals * validateFormals(Formals * formals, PosIdx pos = noPos, Symbol arg = {}); Expr * stripIndentation(const PosIdx pos, std::vector<std::pair<PosIdx, std::variant<Expr *, StringToken>>> && es); PosIdx at(const ParserLocation & loc); }; inline void ParserState::dupAttr(const AttrPath & attrPath, const PosIdx pos, const PosIdx prevPos) { throw ParseError({ .msg = HintFmt("attribute '%1%' already defined at %2%", showAttrPath(symbols, attrPath), positions[prevPos]), .pos = positions[pos] }); } inline void ParserState::dupAttr(Symbol attr, const PosIdx pos, const PosIdx prevPos) { throw ParseError({ .msg = HintFmt("attribute '%1%' already defined at %2%", symbols[attr], positions[prevPos]), .pos = positions[pos] }); } inline void ParserState::addAttr(ExprAttrs * attrs, AttrPath && attrPath, const ParserLocation & loc, Expr * e, const ParserLocation & exprLoc) { AttrPath::iterator i; // All attrpaths have at least one attr assert(!attrPath.empty()); auto pos = at(loc); // Checking attrPath validity. // =========================== for (i = attrPath.begin(); i + 1 < attrPath.end(); i++) { if (i->symbol) { ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(i->symbol); if (j != attrs->attrs.end()) { if (j->second.kind != ExprAttrs::AttrDef::Kind::Inherited) { ExprAttrs * attrs2 = dynamic_cast<ExprAttrs *>(j->second.e); if (!attrs2) dupAttr(attrPath, pos, j->second.pos); attrs = attrs2; } else dupAttr(attrPath, pos, j->second.pos); } else { ExprAttrs * nested = new ExprAttrs; attrs->attrs[i->symbol] = ExprAttrs::AttrDef(nested, pos); attrs = nested; } } else { ExprAttrs *nested = new ExprAttrs; attrs->dynamicAttrs.push_back(ExprAttrs::DynamicAttrDef(i->expr, nested, pos)); attrs = nested; } } // Expr insertion. // ========================== if (i->symbol) { ExprAttrs::AttrDefs::iterator j = attrs->attrs.find(i->symbol); if (j != attrs->attrs.end()) { // This attr path is already defined. However, if both // e and the expr pointed by the attr path are two attribute sets, // we want to merge them. // Otherwise, throw an error. auto ae = dynamic_cast<ExprAttrs *>(e); auto jAttrs = dynamic_cast<ExprAttrs *>(j->second.e); if (jAttrs && ae) { if (ae->inheritFromExprs && !jAttrs->inheritFromExprs) jAttrs->inheritFromExprs = std::make_unique<std::vector<Expr *>>(); for (auto & ad : ae->attrs) { auto j2 = jAttrs->attrs.find(ad.first); if (j2 != jAttrs->attrs.end()) // Attr already defined in iAttrs, error. dupAttr(ad.first, j2->second.pos, ad.second.pos); jAttrs->attrs.emplace(ad.first, ad.second); if (ad.second.kind == ExprAttrs::AttrDef::Kind::InheritedFrom) { auto & sel = dynamic_cast<ExprSelect &>(*ad.second.e); auto & from = dynamic_cast<ExprInheritFrom &>(*sel.e); from.displ += jAttrs->inheritFromExprs->size(); } } jAttrs->dynamicAttrs.insert(jAttrs->dynamicAttrs.end(), ae->dynamicAttrs.begin(), ae->dynamicAttrs.end()); if (ae->inheritFromExprs) { jAttrs->inheritFromExprs->insert(jAttrs->inheritFromExprs->end(), ae->inheritFromExprs->begin(), ae->inheritFromExprs->end()); } } else { dupAttr(attrPath, pos, j->second.pos); } } else { // This attr path is not defined. Let's create it. attrs->attrs.emplace(i->symbol, ExprAttrs::AttrDef(e, pos)); e->setName(i->symbol); } } else { attrs->dynamicAttrs.push_back(ExprAttrs::DynamicAttrDef(i->expr, e, pos)); } auto it = lexerState.positionToDocComment.find(pos); if (it != lexerState.positionToDocComment.end()) { e->setDocComment(it->second); lexerState.positionToDocComment.emplace(at(exprLoc), it->second); } } inline Formals * ParserState::validateFormals(Formals * formals, PosIdx pos, Symbol arg) { std::sort(formals->formals.begin(), formals->formals.end(), [] (const auto & a, const auto & b) { return std::tie(a.name, a.pos) < std::tie(b.name, b.pos); }); std::optional<std::pair<Symbol, PosIdx>> duplicate; for (size_t i = 0; i + 1 < formals->formals.size(); i++) { if (formals->formals[i].name != formals->formals[i + 1].name) continue; std::pair thisDup{formals->formals[i].name, formals->formals[i + 1].pos}; duplicate = std::min(thisDup, duplicate.value_or(thisDup)); } if (duplicate) throw ParseError({ .msg = HintFmt("duplicate formal function argument '%1%'", symbols[duplicate->first]), .pos = positions[duplicate->second] }); if (arg && formals->has(arg)) throw ParseError({ .msg = HintFmt("duplicate formal function argument '%1%'", symbols[arg]), .pos = positions[pos] }); return formals; } inline Expr * ParserState::stripIndentation(const PosIdx pos, std::vector<std::pair<PosIdx, std::variant<Expr *, StringToken>>> && es) { if (es.empty()) return new ExprString(""); /* Figure out the minimum indentation. Note that by design whitespace-only final lines are not taken into account. (So the " " in "\n ''" is ignored, but the " " in "\n foo''" is.) */ bool atStartOfLine = true; /* = seen only whitespace in the current line */ size_t minIndent = 1000000; size_t curIndent = 0; for (auto & [i_pos, i] : es) { auto * str = std::get_if<StringToken>(&i); if (!str || !str->hasIndentation) { /* Anti-quotations and escaped characters end the current start-of-line whitespace. */ if (atStartOfLine) { atStartOfLine = false; if (curIndent < minIndent) minIndent = curIndent; } continue; } for (size_t j = 0; j < str->l; ++j) { if (atStartOfLine) { if (str->p[j] == ' ') curIndent++; else if (str->p[j] == '\n') { /* Empty line, doesn't influence minimum indentation. */ curIndent = 0; } else { atStartOfLine = false; if (curIndent < minIndent) minIndent = curIndent; } } else if (str->p[j] == '\n') { atStartOfLine = true; curIndent = 0; } } } /* Strip spaces from each line. */ auto * es2 = new std::vector<std::pair<PosIdx, Expr *>>; atStartOfLine = true; size_t curDropped = 0; size_t n = es.size(); auto i = es.begin(); const auto trimExpr = [&] (Expr * e) { atStartOfLine = false; curDropped = 0; es2->emplace_back(i->first, e); }; const auto trimString = [&] (const StringToken & t) { std::string s2; for (size_t j = 0; j < t.l; ++j) { if (atStartOfLine) { if (t.p[j] == ' ') { if (curDropped++ >= minIndent) s2 += t.p[j]; } else if (t.p[j] == '\n') { curDropped = 0; s2 += t.p[j]; } else { atStartOfLine = false; curDropped = 0; s2 += t.p[j]; } } else { s2 += t.p[j]; if (t.p[j] == '\n') atStartOfLine = true; } } /* Remove the last line if it is empty and consists only of spaces. */ if (n == 1) { std::string::size_type p = s2.find_last_of('\n'); if (p != std::string::npos && s2.find_first_not_of(' ', p + 1) == std::string::npos) s2 = std::string(s2, 0, p + 1); } // Ignore empty strings for a minor optimisation and AST simplification if (s2 != "") { es2->emplace_back(i->first, new ExprString(std::move(s2))); } }; for (; i != es.end(); ++i, --n) { std::visit(overloaded { trimExpr, trimString }, i->second); } // If there is nothing at all, return the empty string directly. // This also ensures that equivalent empty strings result in the same ast, which is helpful when testing formatters. if (es2->size() == 0) { auto *const result = new ExprString(""); delete es2; return result; } /* If this is a single string, then don't do a concatenation. */ if (es2->size() == 1 && dynamic_cast<ExprString *>((*es2)[0].second)) { auto *const result = (*es2)[0].second; delete es2; return result; } return new ExprConcatStrings(pos, true, es2); } inline PosIdx LexerState::at(const ParserLocation & loc) { return positions.add(origin, loc.beginOffset); } inline PosIdx ParserState::at(const ParserLocation & loc) { return positions.add(origin, loc.beginOffset); } }
12,061
C++
.h
304
30.615132
143
0.567602
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,286
primops.hh
NixOS_nix/src/libexpr/primops.hh
#pragma once ///@file #include "eval.hh" #include <tuple> #include <vector> namespace nix { /** * For functions where we do not expect deep recursion, we can use a sizable * part of the stack a free allocation space. * * Note: this is expected to be multiplied by sizeof(Value), or about 24 bytes. */ constexpr size_t nonRecursiveStackReservation = 128; /** * Functions that maybe applied to self-similar inputs, such as concatMap on a * tree, should reserve a smaller part of the stack for allocation. * * Note: this is expected to be multiplied by sizeof(Value), or about 24 bytes. */ constexpr size_t conservativeStackReservation = 16; struct RegisterPrimOp { typedef std::vector<PrimOp> PrimOps; static PrimOps * primOps; /** * You can register a constant by passing an arity of 0. fun * will get called during EvalState initialization, so there * may be primops not yet added and builtins is not yet sorted. */ RegisterPrimOp(PrimOp && primOp); }; /* These primops are disabled without enableNativeCode, but plugins may wish to use them in limited contexts without globally enabling them. */ /** * Load a ValueInitializer from a DSO and return whatever it initializes */ void prim_importNative(EvalState & state, const PosIdx pos, Value * * args, Value & v); /** * Execute a program and parse its output */ void prim_exec(EvalState & state, const PosIdx pos, Value * * args, Value & v); void makePositionThunks(EvalState & state, const PosIdx pos, Value & line, Value & column); }
1,554
C++
.h
44
32.772727
91
0.740988
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,287
eval-error.hh
NixOS_nix/src/libexpr/eval-error.hh
#pragma once #include "error.hh" #include "pos-idx.hh" namespace nix { struct Env; struct Expr; struct Value; class EvalState; template<class T> class EvalErrorBuilder; /** * Base class for all errors that occur during evaluation. * * Most subclasses should inherit from `EvalError` instead of this class. */ class EvalBaseError : public Error { template<class T> friend class EvalErrorBuilder; public: EvalState & state; EvalBaseError(EvalState & state, ErrorInfo && errorInfo) : Error(errorInfo) , state(state) { } template<typename... Args> explicit EvalBaseError(EvalState & state, const std::string & formatString, const Args &... formatArgs) : Error(formatString, formatArgs...) , state(state) { } }; /** * `EvalError` is the base class for almost all errors that occur during evaluation. * * All instances of `EvalError` should show a degree of purity that allows them to be * cached in pure mode. This means that they should not depend on the configuration or the overall environment. */ MakeError(EvalError, EvalBaseError); MakeError(ParseError, Error); MakeError(AssertionError, EvalError); MakeError(ThrownError, AssertionError); MakeError(Abort, EvalError); MakeError(TypeError, EvalError); MakeError(UndefinedVarError, EvalError); MakeError(MissingArgumentError, EvalError); MakeError(InfiniteRecursionError, EvalError); struct InvalidPathError : public EvalError { public: Path path; InvalidPathError(EvalState & state, const Path & path) : EvalError(state, "path '%s' is not valid", path) { } }; /** * `EvalErrorBuilder`s may only be constructed by `EvalState`. The `debugThrow` * method must be the final method in any such `EvalErrorBuilder` usage, and it * handles deleting the object. */ template<class T> class EvalErrorBuilder final { friend class EvalState; template<typename... Args> explicit EvalErrorBuilder(EvalState & state, const Args &... args) : error(T(state, args...)) { } public: T error; [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & withExitStatus(unsigned int exitStatus); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & atPos(PosIdx pos); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & atPos(Value & value, PosIdx fallback = noPos); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & withTrace(PosIdx pos, const std::string_view text); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & withFrameTrace(PosIdx pos, const std::string_view text); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & withSuggestions(Suggestions & s); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & withFrame(const Env & e, const Expr & ex); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & addTrace(PosIdx pos, HintFmt hint); [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & setIsFromExpr(); template<typename... Args> [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & addTrace(PosIdx pos, std::string_view formatString, const Args &... formatArgs); /** * Delete the `EvalErrorBuilder` and throw the underlying exception. */ [[gnu::noinline, gnu::noreturn]] void debugThrow(); /** * A programming error or fatal condition occurred. Abort the process for core dump and debugging. * This does not print a proper backtrace, because unwinding the stack is destructive. */ [[gnu::noinline, gnu::noreturn]] void panic(); }; }
3,511
C++
.h
96
32.916667
111
0.723304
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,288
pos-table.hh
NixOS_nix/src/libexpr/pos-table.hh
#pragma once #include <cstdint> #include <vector> #include "pos-idx.hh" #include "position.hh" #include "sync.hh" namespace nix { class PosTable { public: class Origin { friend PosTable; private: uint32_t offset; Origin(Pos::Origin origin, uint32_t offset, size_t size): offset(offset), origin(origin), size(size) {} public: const Pos::Origin origin; const size_t size; uint32_t offsetOf(PosIdx p) const { return p.id - 1 - offset; } }; private: using Lines = std::vector<uint32_t>; std::map<uint32_t, Origin> origins; mutable Sync<std::map<uint32_t, Lines>> lines; const Origin * resolve(PosIdx p) const { if (p.id == 0) return nullptr; const auto idx = p.id - 1; /* we want the last key <= idx, so we'll take prev(first key > idx). this is guaranteed to never rewind origin.begin because the first key is always 0. */ const auto pastOrigin = origins.upper_bound(idx); return &std::prev(pastOrigin)->second; } public: Origin addOrigin(Pos::Origin origin, size_t size) { uint32_t offset = 0; if (auto it = origins.rbegin(); it != origins.rend()) offset = it->first + it->second.size; // +1 because all PosIdx are offset by 1 to begin with, and // another +1 to ensure that all origins can point to EOF, eg // on (invalid) empty inputs. if (2 + offset + size < offset) return Origin{origin, offset, 0}; return origins.emplace(offset, Origin{origin, offset, size}).first->second; } PosIdx add(const Origin & origin, size_t offset) { if (offset > origin.size) return PosIdx(); return PosIdx(1 + origin.offset + offset); } Pos operator[](PosIdx p) const; Pos::Origin originOf(PosIdx p) const { if (auto o = resolve(p)) return o->origin; return std::monostate{}; } }; }
2,073
C++
.h
69
23.130435
83
0.592555
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,289
attr-path.hh
NixOS_nix/src/libexpr/attr-path.hh
#pragma once ///@file #include "eval.hh" #include <string> #include <map> namespace nix { MakeError(AttrPathNotFound, Error); MakeError(NoPositionInfo, Error); std::pair<Value *, PosIdx> findAlongAttrPath( EvalState & state, const std::string & attrPath, Bindings & autoArgs, Value & vIn); /** * Heuristic to find the filename and lineno or a nix value. */ std::pair<SourcePath, uint32_t> findPackageFilename(EvalState & state, Value & v, std::string what); std::vector<Symbol> parseAttrPath(EvalState & state, std::string_view s); }
560
C++
.h
19
27.105263
100
0.737336
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,290
nixexpr.hh
NixOS_nix/src/libexpr/nixexpr.hh
#pragma once ///@file #include <map> #include <vector> #include "value.hh" #include "symbol-table.hh" #include "eval-error.hh" #include "pos-idx.hh" namespace nix { class EvalState; class PosTable; struct Env; struct ExprWith; struct StaticEnv; struct Value; /** * A documentation comment, in the sense of [RFC 145](https://github.com/NixOS/rfcs/blob/master/rfcs/0145-doc-strings.md) * * Note that this does not implement the following: * - argument attribute names ("formals"): TBD * - argument names: these are internal to the function and their names may not be optimal for documentation * - function arity (degree of currying or number of ':'s): * - Functions returning partially applied functions have a higher arity * than can be determined locally and without evaluation. * We do not want to present false data. * - Some functions should be thought of as transformations of other * functions. For instance `overlay -> overlay -> overlay` is the simplest * way to understand `composeExtensions`, but its implementation looks like * `f: g: final: prev: <...>`. The parameters `final` and `prev` are part * of the overlay concept, while distracting from the function's purpose. */ struct DocComment { /** * Start of the comment, including the opening, ie `/` and `**`. */ PosIdx begin; /** * Position right after the final asterisk and `/` that terminate the comment. */ PosIdx end; /** * Whether the comment is set. * * A `DocComment` is small enough that it makes sense to pass by value, and * therefore baking optionality into it is also useful, to avoiding the memory * overhead of `std::optional`. */ operator bool() const { return static_cast<bool>(begin); } std::string getInnerText(const PosTable & positions) const; }; /** * An attribute path is a sequence of attribute names. */ struct AttrName { Symbol symbol; Expr * expr; AttrName(Symbol s) : symbol(s) {}; AttrName(Expr * e) : expr(e) {}; }; typedef std::vector<AttrName> AttrPath; std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath); /* Abstract syntax of Nix expressions. */ struct Expr { struct AstSymbols { Symbol sub, lessThan, mul, div, or_, findFile, nixPath, body; }; static unsigned long nrExprs; Expr() { nrExprs++; } virtual ~Expr() { }; virtual void show(const SymbolTable & symbols, std::ostream & str) const; virtual void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env); virtual void eval(EvalState & state, Env & env, Value & v); virtual Value * maybeThunk(EvalState & state, Env & env); virtual void setName(Symbol name); virtual void setDocComment(DocComment docComment) { }; virtual PosIdx getPos() const { return noPos; } // These are temporary methods to be used only in parser.y virtual void resetCursedOr() { }; virtual void warnIfCursedOr(const SymbolTable & symbols, const PosTable & positions) { }; }; #define COMMON_METHODS \ void show(const SymbolTable & symbols, std::ostream & str) const override; \ void eval(EvalState & state, Env & env, Value & v) override; \ void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override; struct ExprInt : Expr { Value v; ExprInt(NixInt n) { v.mkInt(n); }; ExprInt(NixInt::Inner n) { v.mkInt(n); }; Value * maybeThunk(EvalState & state, Env & env) override; COMMON_METHODS }; struct ExprFloat : Expr { Value v; ExprFloat(NixFloat nf) { v.mkFloat(nf); }; Value * maybeThunk(EvalState & state, Env & env) override; COMMON_METHODS }; struct ExprString : Expr { std::string s; Value v; ExprString(std::string &&s) : s(std::move(s)) { v.mkString(this->s.data()); }; Value * maybeThunk(EvalState & state, Env & env) override; COMMON_METHODS }; struct ExprPath : Expr { ref<SourceAccessor> accessor; std::string s; Value v; ExprPath(ref<SourceAccessor> accessor, std::string s) : accessor(accessor), s(std::move(s)) { v.mkPath(&*accessor, this->s.c_str()); } Value * maybeThunk(EvalState & state, Env & env) override; COMMON_METHODS }; typedef uint32_t Level; typedef uint32_t Displacement; struct ExprVar : Expr { PosIdx pos; Symbol name; /* Whether the variable comes from an environment (e.g. a rec, let or function argument) or from a "with". `nullptr`: Not from a `with`. Valid pointer: the nearest, innermost `with` expression to query first. */ ExprWith * fromWith; /* In the former case, the value is obtained by going `level` levels up from the current environment and getting the `displ`th value in that environment. In the latter case, the value is obtained by getting the attribute named `name` from the set stored in the environment that is `level` levels up from the current one.*/ Level level; Displacement displ; ExprVar(Symbol name) : name(name) { }; ExprVar(const PosIdx & pos, Symbol name) : pos(pos), name(name) { }; Value * maybeThunk(EvalState & state, Env & env) override; PosIdx getPos() const override { return pos; } COMMON_METHODS }; /** * A pseudo-expression for the purpose of evaluating the `from` expression in `inherit (from)` syntax. * Unlike normal variable references, the displacement is set during parsing, and always refers to * `ExprAttrs::inheritFromExprs` (by itself or in `ExprLet`), whose values are put into their own `Env`. */ struct ExprInheritFrom : ExprVar { ExprInheritFrom(PosIdx pos, Displacement displ): ExprVar(pos, {}) { this->level = 0; this->displ = displ; this->fromWith = nullptr; } void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override; }; struct ExprSelect : Expr { PosIdx pos; Expr * e, * def; AttrPath attrPath; ExprSelect(const PosIdx & pos, Expr * e, AttrPath attrPath, Expr * def) : pos(pos), e(e), def(def), attrPath(std::move(attrPath)) { }; ExprSelect(const PosIdx & pos, Expr * e, Symbol name) : pos(pos), e(e), def(0) { attrPath.push_back(AttrName(name)); }; PosIdx getPos() const override { return pos; } /** * Evaluate the `a.b.c` part of `a.b.c.d`. This exists mostly for the purpose of :doc in the repl. * * @param[out] attrs The attribute set that should contain the last attribute name (if it exists). * @return The last attribute name in `attrPath` * * @note This does *not* evaluate the final attribute, and does not fail if that's the only attribute that does not exist. */ Symbol evalExceptFinalSelect(EvalState & state, Env & env, Value & attrs); COMMON_METHODS }; struct ExprOpHasAttr : Expr { Expr * e; AttrPath attrPath; ExprOpHasAttr(Expr * e, AttrPath attrPath) : e(e), attrPath(std::move(attrPath)) { }; PosIdx getPos() const override { return e->getPos(); } COMMON_METHODS }; struct ExprAttrs : Expr { bool recursive; PosIdx pos; struct AttrDef { enum class Kind { /** `attr = expr;` */ Plain, /** `inherit attr1 attrn;` */ Inherited, /** `inherit (expr) attr1 attrn;` */ InheritedFrom, }; Kind kind; Expr * e; PosIdx pos; Displacement displ; // displacement AttrDef(Expr * e, const PosIdx & pos, Kind kind = Kind::Plain) : kind(kind), e(e), pos(pos) { }; AttrDef() { }; template<typename T> const T & chooseByKind(const T & plain, const T & inherited, const T & inheritedFrom) const { switch (kind) { case Kind::Plain: return plain; case Kind::Inherited: return inherited; default: case Kind::InheritedFrom: return inheritedFrom; } } }; typedef std::map<Symbol, AttrDef> AttrDefs; AttrDefs attrs; std::unique_ptr<std::vector<Expr *>> inheritFromExprs; struct DynamicAttrDef { Expr * nameExpr, * valueExpr; PosIdx pos; DynamicAttrDef(Expr * nameExpr, Expr * valueExpr, const PosIdx & pos) : nameExpr(nameExpr), valueExpr(valueExpr), pos(pos) { }; }; typedef std::vector<DynamicAttrDef> DynamicAttrDefs; DynamicAttrDefs dynamicAttrs; ExprAttrs(const PosIdx &pos) : recursive(false), pos(pos) { }; ExprAttrs() : recursive(false) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS std::shared_ptr<const StaticEnv> bindInheritSources( EvalState & es, const std::shared_ptr<const StaticEnv> & env); Env * buildInheritFromEnv(EvalState & state, Env & up); void showBindings(const SymbolTable & symbols, std::ostream & str) const; }; struct ExprList : Expr { std::vector<Expr *> elems; ExprList() { }; COMMON_METHODS Value * maybeThunk(EvalState & state, Env & env) override; PosIdx getPos() const override { return elems.empty() ? noPos : elems.front()->getPos(); } }; struct Formal { PosIdx pos; Symbol name; Expr * def; }; struct Formals { typedef std::vector<Formal> Formals_; Formals_ formals; bool ellipsis; bool has(Symbol arg) const { auto it = std::lower_bound(formals.begin(), formals.end(), arg, [] (const Formal & f, const Symbol & sym) { return f.name < sym; }); return it != formals.end() && it->name == arg; } std::vector<Formal> lexicographicOrder(const SymbolTable & symbols) const { std::vector<Formal> result(formals.begin(), formals.end()); std::sort(result.begin(), result.end(), [&] (const Formal & a, const Formal & b) { std::string_view sa = symbols[a.name], sb = symbols[b.name]; return sa < sb; }); return result; } }; struct ExprLambda : Expr { PosIdx pos; Symbol name; Symbol arg; Formals * formals; Expr * body; DocComment docComment; ExprLambda(PosIdx pos, Symbol arg, Formals * formals, Expr * body) : pos(pos), arg(arg), formals(formals), body(body) { }; ExprLambda(PosIdx pos, Formals * formals, Expr * body) : pos(pos), formals(formals), body(body) { } void setName(Symbol name) override; std::string showNamePos(const EvalState & state) const; inline bool hasFormals() const { return formals != nullptr; } PosIdx getPos() const override { return pos; } virtual void setDocComment(DocComment docComment) override; COMMON_METHODS }; struct ExprCall : Expr { Expr * fun; std::vector<Expr *> args; PosIdx pos; std::optional<PosIdx> cursedOrEndPos; // used during parsing to warn about https://github.com/NixOS/nix/issues/11118 ExprCall(const PosIdx & pos, Expr * fun, std::vector<Expr *> && args) : fun(fun), args(args), pos(pos), cursedOrEndPos({}) { } ExprCall(const PosIdx & pos, Expr * fun, std::vector<Expr *> && args, PosIdx && cursedOrEndPos) : fun(fun), args(args), pos(pos), cursedOrEndPos(cursedOrEndPos) { } PosIdx getPos() const override { return pos; } virtual void resetCursedOr() override; virtual void warnIfCursedOr(const SymbolTable & symbols, const PosTable & positions) override; COMMON_METHODS }; struct ExprLet : Expr { ExprAttrs * attrs; Expr * body; ExprLet(ExprAttrs * attrs, Expr * body) : attrs(attrs), body(body) { }; COMMON_METHODS }; struct ExprWith : Expr { PosIdx pos; Expr * attrs, * body; size_t prevWith; ExprWith * parentWith; ExprWith(const PosIdx & pos, Expr * attrs, Expr * body) : pos(pos), attrs(attrs), body(body) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS }; struct ExprIf : Expr { PosIdx pos; Expr * cond, * then, * else_; ExprIf(const PosIdx & pos, Expr * cond, Expr * then, Expr * else_) : pos(pos), cond(cond), then(then), else_(else_) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS }; struct ExprAssert : Expr { PosIdx pos; Expr * cond, * body; ExprAssert(const PosIdx & pos, Expr * cond, Expr * body) : pos(pos), cond(cond), body(body) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS }; struct ExprOpNot : Expr { Expr * e; ExprOpNot(Expr * e) : e(e) { }; PosIdx getPos() const override { return e->getPos(); } COMMON_METHODS }; #define MakeBinOp(name, s) \ struct name : Expr \ { \ PosIdx pos; \ Expr * e1, * e2; \ name(Expr * e1, Expr * e2) : e1(e1), e2(e2) { }; \ name(const PosIdx & pos, Expr * e1, Expr * e2) : pos(pos), e1(e1), e2(e2) { }; \ void show(const SymbolTable & symbols, std::ostream & str) const override \ { \ str << "("; e1->show(symbols, str); str << " " s " "; e2->show(symbols, str); str << ")"; \ } \ void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override \ { \ e1->bindVars(es, env); e2->bindVars(es, env); \ } \ void eval(EvalState & state, Env & env, Value & v) override; \ PosIdx getPos() const override { return pos; } \ }; MakeBinOp(ExprOpEq, "==") MakeBinOp(ExprOpNEq, "!=") MakeBinOp(ExprOpAnd, "&&") MakeBinOp(ExprOpOr, "||") MakeBinOp(ExprOpImpl, "->") MakeBinOp(ExprOpUpdate, "//") MakeBinOp(ExprOpConcatLists, "++") struct ExprConcatStrings : Expr { PosIdx pos; bool forceString; std::vector<std::pair<PosIdx, Expr *>> * es; ExprConcatStrings(const PosIdx & pos, bool forceString, std::vector<std::pair<PosIdx, Expr *>> * es) : pos(pos), forceString(forceString), es(es) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS }; struct ExprPos : Expr { PosIdx pos; ExprPos(const PosIdx & pos) : pos(pos) { }; PosIdx getPos() const override { return pos; } COMMON_METHODS }; /* only used to mark thunks as black holes. */ struct ExprBlackHole : Expr { void show(const SymbolTable & symbols, std::ostream & str) const override {} void eval(EvalState & state, Env & env, Value & v) override; void bindVars(EvalState & es, const std::shared_ptr<const StaticEnv> & env) override {} }; extern ExprBlackHole eBlackHole; /* Static environments are used to map variable names onto (level, displacement) pairs used to obtain the value of the variable at runtime. */ struct StaticEnv { ExprWith * isWith; const StaticEnv * up; // Note: these must be in sorted order. typedef std::vector<std::pair<Symbol, Displacement>> Vars; Vars vars; StaticEnv(ExprWith * isWith, const StaticEnv * up, size_t expectedSize = 0) : isWith(isWith), up(up) { vars.reserve(expectedSize); }; void sort() { std::stable_sort(vars.begin(), vars.end(), [](const Vars::value_type & a, const Vars::value_type & b) { return a.first < b.first; }); } void deduplicate() { auto it = vars.begin(), jt = it, end = vars.end(); while (jt != end) { *it = *jt++; while (jt != end && it->first == jt->first) *it = *jt++; it++; } vars.erase(it, end); } Vars::const_iterator find(Symbol name) const { Vars::value_type key(name, 0); auto i = std::lower_bound(vars.begin(), vars.end(), key); if (i != vars.end() && i->first == name) return i; return vars.end(); } }; }
15,781
C++
.h
450
29.942222
138
0.641397
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,291
attr-set.hh
NixOS_nix/src/libexpr/attr-set.hh
#pragma once ///@file #include "nixexpr.hh" #include "symbol-table.hh" #include <algorithm> namespace nix { class EvalState; struct Value; /** * Map one attribute name to its value. */ struct Attr { /* the placement of `name` and `pos` in this struct is important. both of them are uint32 wrappers, they are next to each other to make sure that Attr has no padding on 64 bit machines. that way we keep Attr size at two words with no wasted space. */ Symbol name; PosIdx pos; Value * value; Attr(Symbol name, Value * value, PosIdx pos = noPos) : name(name), pos(pos), value(value) { }; Attr() { }; auto operator <=> (const Attr & a) const { return name <=> a.name; } }; static_assert(sizeof(Attr) == 2 * sizeof(uint32_t) + sizeof(Value *), "performance of the evaluator is highly sensitive to the size of Attr. " "avoid introducing any padding into Attr if at all possible, and do not " "introduce new fields that need not be present for almost every instance."); /** * Bindings contains all the attributes of an attribute set. It is defined * by its size and its capacity, the capacity being the number of Attr * elements allocated after this structure, while the size corresponds to * the number of elements already inserted in this structure. */ class Bindings { public: typedef uint32_t size_t; PosIdx pos; private: size_t size_, capacity_; Attr attrs[0]; Bindings(size_t capacity) : size_(0), capacity_(capacity) { } Bindings(const Bindings & bindings) = delete; public: size_t size() const { return size_; } bool empty() const { return !size_; } typedef Attr * iterator; typedef const Attr * const_iterator; void push_back(const Attr & attr) { assert(size_ < capacity_); attrs[size_++] = attr; } const_iterator find(Symbol name) const { Attr key(name, 0); const_iterator i = std::lower_bound(begin(), end(), key); if (i != end() && i->name == name) return i; return end(); } const Attr * get(Symbol name) const { Attr key(name, 0); const_iterator i = std::lower_bound(begin(), end(), key); if (i != end() && i->name == name) return &*i; return nullptr; } iterator begin() { return &attrs[0]; } iterator end() { return &attrs[size_]; } const_iterator begin() const { return &attrs[0]; } const_iterator end() const { return &attrs[size_]; } Attr & operator[](size_t pos) { return attrs[pos]; } const Attr & operator[](size_t pos) const { return attrs[pos]; } void sort(); size_t capacity() const { return capacity_; } /** * Returns the attributes in lexicographically sorted order. */ std::vector<const Attr *> lexicographicOrder(const SymbolTable & symbols) const { std::vector<const Attr *> res; res.reserve(size_); for (size_t n = 0; n < size_; n++) res.emplace_back(&attrs[n]); std::sort(res.begin(), res.end(), [&](const Attr * a, const Attr * b) { std::string_view sa = symbols[a->name], sb = symbols[b->name]; return sa < sb; }); return res; } friend class EvalState; }; /** * A wrapper around Bindings that ensures that its always in sorted * order at the end. The only way to consume a BindingsBuilder is to * call finish(), which sorts the bindings. */ class BindingsBuilder { Bindings * bindings; public: // needed by std::back_inserter using value_type = Attr; EvalState & state; BindingsBuilder(EvalState & state, Bindings * bindings) : bindings(bindings), state(state) { } void insert(Symbol name, Value * value, PosIdx pos = noPos) { insert(Attr(name, value, pos)); } void insert(const Attr & attr) { push_back(attr); } void push_back(const Attr & attr) { bindings->push_back(attr); } Value & alloc(Symbol name, PosIdx pos = noPos); Value & alloc(std::string_view name, PosIdx pos = noPos); Bindings * finish() { bindings->sort(); return bindings; } Bindings * alreadySorted() { return bindings; } size_t capacity() { return bindings->capacity(); } void grow(Bindings * newBindings) { for (auto & i : *bindings) newBindings->push_back(i); bindings = newBindings; } friend struct ExprAttrs; }; }
4,595
C++
.h
154
24.409091
83
0.621904
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,292
value.hh
NixOS_nix/src/libexpr/value.hh
#pragma once ///@file #include <cassert> #include <span> #include "eval-gc.hh" #include "symbol-table.hh" #include "value/context.hh" #include "source-path.hh" #include "print-options.hh" #include "checked-arithmetic.hh" #include <nlohmann/json_fwd.hpp> namespace nix { struct Value; class BindingsBuilder; typedef enum { tUninitialized = 0, tInt = 1, tBool, tString, tPath, tNull, tAttrs, tList1, tList2, tListN, tThunk, tApp, tLambda, tPrimOp, tPrimOpApp, tExternal, tFloat } InternalType; /** * This type abstracts over all actual value types in the language, * grouping together implementation details like tList*, different function * types, and types in non-normal form (so thunks and co.) */ typedef enum { nThunk, nInt, nFloat, nBool, nString, nPath, nNull, nAttrs, nList, nFunction, nExternal } ValueType; class Bindings; struct Env; struct Expr; struct ExprLambda; struct ExprBlackHole; struct PrimOp; class Symbol; class PosIdx; struct Pos; class StorePath; class EvalState; class XMLWriter; class Printer; using NixInt = checked::Checked<int64_t>; using NixFloat = double; /** * External values must descend from ExternalValueBase, so that * type-agnostic nix functions (e.g. showType) can be implemented */ class ExternalValueBase { friend std::ostream & operator << (std::ostream & str, const ExternalValueBase & v); friend class Printer; protected: /** * Print out the value */ virtual std::ostream & print(std::ostream & str) const = 0; public: /** * Return a simple string describing the type */ virtual std::string showType() const = 0; /** * Return a string to be used in builtins.typeOf */ virtual std::string typeOf() const = 0; /** * Coerce the value to a string. Defaults to uncoercable, i.e. throws an * error. */ virtual std::string coerceToString(EvalState & state, const PosIdx & pos, NixStringContext & context, bool copyMore, bool copyToStore) const; /** * Compare to another value of the same type. Defaults to uncomparable, * i.e. always false. */ virtual bool operator ==(const ExternalValueBase & b) const noexcept; /** * Print the value as JSON. Defaults to unconvertable, i.e. throws an error */ virtual nlohmann::json printValueAsJSON(EvalState & state, bool strict, NixStringContext & context, bool copyToStore = true) const; /** * Print the value as XML. Defaults to unevaluated */ virtual void printValueAsXML(EvalState & state, bool strict, bool location, XMLWriter & doc, NixStringContext & context, PathSet & drvsSeen, const PosIdx pos) const; virtual ~ExternalValueBase() { }; }; std::ostream & operator << (std::ostream & str, const ExternalValueBase & v); class ListBuilder { const size_t size; Value * inlineElems[2] = {nullptr, nullptr}; public: Value * * elems; ListBuilder(EvalState & state, size_t size); // NOTE: Can be noexcept because we are just copying integral values and // raw pointers. ListBuilder(ListBuilder && x) noexcept : size(x.size) , inlineElems{x.inlineElems[0], x.inlineElems[1]} , elems(size <= 2 ? inlineElems : x.elems) { } Value * & operator [](size_t n) { return elems[n]; } typedef Value * * iterator; iterator begin() { return &elems[0]; } iterator end() { return &elems[size]; } friend struct Value; }; struct Value { private: InternalType internalType = tUninitialized; friend std::string showType(const Value & v); public: void print(EvalState &state, std::ostream &str, PrintOptions options = PrintOptions {}); // Functions needed to distinguish the type // These should be removed eventually, by putting the functionality that's // needed by callers into methods of this type // type() == nThunk inline bool isThunk() const { return internalType == tThunk; }; inline bool isApp() const { return internalType == tApp; }; inline bool isBlackhole() const; // type() == nFunction inline bool isLambda() const { return internalType == tLambda; }; inline bool isPrimOp() const { return internalType == tPrimOp; }; inline bool isPrimOpApp() const { return internalType == tPrimOpApp; }; /** * Strings in the evaluator carry a so-called `context` which * is a list of strings representing store paths. This is to * allow users to write things like * * "--with-freetype2-library=" + freetype + "/lib" * * where `freetype` is a derivation (or a source to be copied * to the store). If we just concatenated the strings without * keeping track of the referenced store paths, then if the * string is used as a derivation attribute, the derivation * will not have the correct dependencies in its inputDrvs and * inputSrcs. * The semantics of the context is as follows: when a string * with context C is used as a derivation attribute, then the * derivations in C will be added to the inputDrvs of the * derivation, and the other store paths in C will be added to * the inputSrcs of the derivations. * For canonicity, the store paths should be in sorted order. */ struct StringWithContext { const char * c_str; const char * * context; // must be in sorted order }; struct Path { SourceAccessor * accessor; const char * path; }; struct ClosureThunk { Env * env; Expr * expr; }; struct FunctionApplicationThunk { Value * left, * right; }; struct Lambda { Env * env; ExprLambda * fun; }; using Payload = union { NixInt integer; bool boolean; StringWithContext string; Path path; Bindings * attrs; struct { size_t size; Value * const * elems; } bigList; Value * smallList[2]; ClosureThunk thunk; FunctionApplicationThunk app; Lambda lambda; PrimOp * primOp; FunctionApplicationThunk primOpApp; ExternalValueBase * external; NixFloat fpoint; }; Payload payload; /** * Returns the normal type of a Value. This only returns nThunk if * the Value hasn't been forceValue'd * * @param invalidIsThunk Instead of aborting an an invalid (probably * 0, so uninitialized) internal type, return `nThunk`. */ inline ValueType type(bool invalidIsThunk = false) const { switch (internalType) { case tUninitialized: break; case tInt: return nInt; case tBool: return nBool; case tString: return nString; case tPath: return nPath; case tNull: return nNull; case tAttrs: return nAttrs; case tList1: case tList2: case tListN: return nList; case tLambda: case tPrimOp: case tPrimOpApp: return nFunction; case tExternal: return nExternal; case tFloat: return nFloat; case tThunk: case tApp: return nThunk; } if (invalidIsThunk) return nThunk; else unreachable(); } inline void finishValue(InternalType newType, Payload newPayload) { payload = newPayload; internalType = newType; } /** * A value becomes valid when it is initialized. We don't use this * in the evaluator; only in the bindings, where the slight extra * cost is warranted because of inexperienced callers. */ inline bool isValid() const { return internalType != tUninitialized; } inline void mkInt(NixInt::Inner n) { mkInt(NixInt{n}); } inline void mkInt(NixInt n) { finishValue(tInt, { .integer = n }); } inline void mkBool(bool b) { finishValue(tBool, { .boolean = b }); } inline void mkString(const char * s, const char * * context = 0) { finishValue(tString, { .string = { .c_str = s, .context = context } }); } void mkString(std::string_view s); void mkString(std::string_view s, const NixStringContext & context); void mkStringMove(const char * s, const NixStringContext & context); inline void mkString(const SymbolStr & s) { mkString(s.c_str()); } void mkPath(const SourcePath & path); void mkPath(std::string_view path); inline void mkPath(SourceAccessor * accessor, const char * path) { finishValue(tPath, { .path = { .accessor = accessor, .path = path } }); } inline void mkNull() { finishValue(tNull, {}); } inline void mkAttrs(Bindings * a) { finishValue(tAttrs, { .attrs = a }); } Value & mkAttrs(BindingsBuilder & bindings); void mkList(const ListBuilder & builder) { if (builder.size == 1) finishValue(tList1, { .smallList = { builder.inlineElems[0] } }); else if (builder.size == 2) finishValue(tList2, { .smallList = { builder.inlineElems[0], builder.inlineElems[1] } }); else finishValue(tListN, { .bigList = { .size = builder.size, .elems = builder.elems } }); } inline void mkThunk(Env * e, Expr * ex) { finishValue(tThunk, { .thunk = { .env = e, .expr = ex } }); } inline void mkApp(Value * l, Value * r) { finishValue(tApp, { .app = { .left = l, .right = r } }); } inline void mkLambda(Env * e, ExprLambda * f) { finishValue(tLambda, { .lambda = { .env = e, .fun = f } }); } inline void mkBlackhole(); void mkPrimOp(PrimOp * p); inline void mkPrimOpApp(Value * l, Value * r) { finishValue(tPrimOpApp, { .primOpApp = { .left = l, .right = r } }); } /** * For a `tPrimOpApp` value, get the original `PrimOp` value. */ const PrimOp * primOpAppPrimOp() const; inline void mkExternal(ExternalValueBase * e) { finishValue(tExternal, { .external = e }); } inline void mkFloat(NixFloat n) { finishValue(tFloat, { .fpoint = n }); } bool isList() const { return internalType == tList1 || internalType == tList2 || internalType == tListN; } Value * const * listElems() { return internalType == tList1 || internalType == tList2 ? payload.smallList : payload.bigList.elems; } std::span<Value * const> listItems() const { assert(isList()); return std::span<Value * const>(listElems(), listSize()); } Value * const * listElems() const { return internalType == tList1 || internalType == tList2 ? payload.smallList : payload.bigList.elems; } size_t listSize() const { return internalType == tList1 ? 1 : internalType == tList2 ? 2 : payload.bigList.size; } PosIdx determinePos(const PosIdx pos) const; /** * Check whether forcing this value requires a trivial amount of * computation. In particular, function applications are * non-trivial. */ bool isTrivial() const; SourcePath path() const { assert(internalType == tPath); return SourcePath( ref(payload.path.accessor->shared_from_this()), CanonPath(CanonPath::unchecked_t(), payload.path.path)); } std::string_view string_view() const { assert(internalType == tString); return std::string_view(payload.string.c_str); } const char * c_str() const { assert(internalType == tString); return payload.string.c_str; } const char * * context() const { return payload.string.context; } ExternalValueBase * external() const { return payload.external; } const Bindings * attrs() const { return payload.attrs; } const PrimOp * primOp() const { return payload.primOp; } bool boolean() const { return payload.boolean; } NixInt integer() const { return payload.integer; } NixFloat fpoint() const { return payload.fpoint; } }; extern ExprBlackHole eBlackHole; bool Value::isBlackhole() const { return internalType == tThunk && payload.thunk.expr == (Expr*) &eBlackHole; } void Value::mkBlackhole() { mkThunk(nullptr, (Expr *) &eBlackHole); } typedef std::vector<Value *, traceable_allocator<Value *>> ValueVector; typedef std::unordered_map<Symbol, Value *, std::hash<Symbol>, std::equal_to<Symbol>, traceable_allocator<std::pair<const Symbol, Value *>>> ValueMap; typedef std::map<Symbol, ValueVector, std::less<Symbol>, traceable_allocator<std::pair<const Symbol, ValueVector>>> ValueVectorMap; /** * A value allocated in traceable memory. */ typedef std::shared_ptr<Value *> RootValue; RootValue allocRootValue(Value * v); }
13,051
C++
.h
414
25.763285
150
0.643324
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,293
symbol-table.hh
NixOS_nix/src/libexpr/symbol-table.hh
#pragma once ///@file #include <list> #include <map> #include <unordered_map> #include "types.hh" #include "chunked-vector.hh" #include "error.hh" namespace nix { /** * This class mainly exists to give us an operator<< for ostreams. We could also * return plain strings from SymbolTable, but then we'd have to wrap every * instance of a symbol that is fmt()ed, which is inconvenient and error-prone. */ class SymbolStr { friend class SymbolTable; private: const std::string * s; explicit SymbolStr(const std::string & symbol): s(&symbol) {} public: bool operator == (std::string_view s2) const { return *s == s2; } const char * c_str() const { return s->c_str(); } operator const std::string_view () const { return *s; } friend std::ostream & operator <<(std::ostream & os, const SymbolStr & symbol); bool empty() const { return s->empty(); } }; /** * Symbols have the property that they can be compared efficiently * (using an equality test), because the symbol table stores only one * copy of each string. */ class Symbol { friend class SymbolTable; private: uint32_t id; explicit Symbol(uint32_t id): id(id) {} public: Symbol() : id(0) {} explicit operator bool() const { return id > 0; } auto operator<=>(const Symbol other) const { return id <=> other.id; } bool operator==(const Symbol other) const { return id == other.id; } friend class std::hash<Symbol>; }; /** * Symbol table used by the parser and evaluator to represent and look * up identifiers and attributes efficiently. */ class SymbolTable { private: std::unordered_map<std::string_view, std::pair<const std::string *, uint32_t>> symbols; ChunkedVector<std::string, 8192> store{16}; public: /** * converts a string into a symbol. */ Symbol create(std::string_view s) { // Most symbols are looked up more than once, so we trade off insertion performance // for lookup performance. // TODO: could probably be done more efficiently with transparent Hash and Equals // on the original implementation using unordered_set // FIXME: make this thread-safe. auto it = symbols.find(s); if (it != symbols.end()) return Symbol(it->second.second + 1); const auto & [rawSym, idx] = store.add(std::string(s)); symbols.emplace(rawSym, std::make_pair(&rawSym, idx)); return Symbol(idx + 1); } std::vector<SymbolStr> resolve(const std::vector<Symbol> & symbols) const { std::vector<SymbolStr> result; result.reserve(symbols.size()); for (auto sym : symbols) result.push_back((*this)[sym]); return result; } SymbolStr operator[](Symbol s) const { if (s.id == 0 || s.id > store.size()) unreachable(); return SymbolStr(store[s.id - 1]); } size_t size() const { return store.size(); } size_t totalSize() const; template<typename T> void dump(T callback) const { store.forEach(callback); } }; } template<> struct std::hash<nix::Symbol> { std::size_t operator()(const nix::Symbol & s) const noexcept { return std::hash<decltype(s.id)>{}(s.id); } };
3,338
C++
.h
117
23.717949
91
0.640977
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,294
value-to-xml.hh
NixOS_nix/src/libexpr/value-to-xml.hh
#pragma once ///@file #include "nixexpr.hh" #include "eval.hh" #include <string> #include <map> namespace nix { void printValueAsXML(EvalState & state, bool strict, bool location, Value & v, std::ostream & out, NixStringContext & context, const PosIdx pos); }
269
C++
.h
10
25
81
0.744094
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,295
eval.hh
NixOS_nix/src/libexpr/eval.hh
#pragma once ///@file #include "attr-set.hh" #include "eval-error.hh" #include "types.hh" #include "value.hh" #include "nixexpr.hh" #include "symbol-table.hh" #include "config.hh" #include "experimental-features.hh" #include "position.hh" #include "pos-table.hh" #include "source-accessor.hh" #include "search-path.hh" #include "repl-exit-status.hh" #include "ref.hh" #include <map> #include <optional> #include <functional> namespace nix { /** * We put a limit on primop arity because it lets us use a fixed size array on * the stack. 8 is already an impractical number of arguments. Use an attrset * argument for such overly complicated functions. */ constexpr size_t maxPrimOpArity = 8; class Store; namespace fetchers { struct Settings; } struct EvalSettings; class EvalState; class StorePath; struct SingleDerivedPath; enum RepairFlag : bool; struct MemorySourceAccessor; namespace eval_cache { class EvalCache; } /** * Increments a count on construction and decrements on destruction. */ class CallDepth { size_t & count; public: CallDepth(size_t & count) : count(count) { ++count; } ~CallDepth() { --count; } }; /** * Function that implements a primop. */ using PrimOpFun = void(EvalState & state, const PosIdx pos, Value * * args, Value & v); /** * Info about a primitive operation, and its implementation */ struct PrimOp { /** * Name of the primop. `__` prefix is treated specially. */ std::string name; /** * Names of the parameters of a primop, for primops that take a * fixed number of arguments to be substituted for these parameters. */ std::vector<std::string> args; /** * Aritiy of the primop. * * If `args` is not empty, this field will be computed from that * field instead, so it doesn't need to be manually set. */ size_t arity = 0; /** * Optional free-form documentation about the primop. */ const char * doc = nullptr; /** * Add a trace item, while calling the `<name>` builtin. * * This is used to remove the redundant item for `builtins.addErrorContext`. */ bool addTrace = true; /** * Implementation of the primop. */ std::function<PrimOpFun> fun; /** * Optional experimental for this to be gated on. */ std::optional<ExperimentalFeature> experimentalFeature; /** * If true, this primop is not exposed to the user. */ bool internal = false; /** * Validity check to be performed by functions that introduce primops, * such as RegisterPrimOp() and Value::mkPrimOp(). */ void check(); }; std::ostream & operator<<(std::ostream & output, const PrimOp & primOp); /** * Info about a constant */ struct Constant { /** * Optional type of the constant (known since it is a fixed value). * * @todo we should use an enum for this. */ ValueType type = nThunk; /** * Optional free-form documentation about the constant. */ const char * doc = nullptr; /** * Whether the constant is impure, and not available in pure mode. */ bool impureOnly = false; }; typedef std::map<std::string, Value *, std::less<std::string>, traceable_allocator<std::pair<const std::string, Value *> > > ValMap; typedef std::unordered_map<PosIdx, DocComment> DocCommentMap; struct Env { Env * up; Value * values[0]; }; void printEnvBindings(const EvalState &es, const Expr & expr, const Env & env); void printEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env, int lvl = 0); std::unique_ptr<ValMap> mapStaticEnvBindings(const SymbolTable & st, const StaticEnv & se, const Env & env); void copyContext(const Value & v, NixStringContext & context); std::string printValue(EvalState & state, Value & v); std::ostream & operator << (std::ostream & os, const ValueType t); struct RegexCache; std::shared_ptr<RegexCache> makeRegexCache(); struct DebugTrace { std::shared_ptr<Pos> pos; const Expr & expr; const Env & env; HintFmt hint; bool isError; }; class EvalState : public std::enable_shared_from_this<EvalState> { public: const fetchers::Settings & fetchSettings; const EvalSettings & settings; SymbolTable symbols; PosTable positions; const Symbol sWith, sOutPath, sDrvPath, sType, sMeta, sName, sValue, sSystem, sOverrides, sOutputs, sOutputName, sIgnoreNulls, sFile, sLine, sColumn, sFunctor, sToString, sRight, sWrong, sStructuredAttrs, sAllowedReferences, sAllowedRequisites, sDisallowedReferences, sDisallowedRequisites, sMaxSize, sMaxClosureSize, sBuilder, sArgs, sContentAddressed, sImpure, sOutputHash, sOutputHashAlgo, sOutputHashMode, sRecurseForDerivations, sDescription, sSelf, sEpsilon, sStartSet, sOperator, sKey, sPath, sPrefix, sOutputSpecified; const Expr::AstSymbols exprSymbols; /** * If set, force copying files to the Nix store even if they * already exist there. */ RepairFlag repair; Bindings emptyBindings; /** * Empty list constant. */ Value vEmptyList; /** * `null` constant. * * This is _not_ a singleton. Pointer equality is _not_ sufficient. */ Value vNull; /** * `true` constant. * * This is _not_ a singleton. Pointer equality is _not_ sufficient. */ Value vTrue; /** * `true` constant. * * This is _not_ a singleton. Pointer equality is _not_ sufficient. */ Value vFalse; /** `"regular"` */ Value vStringRegular; /** `"directory"` */ Value vStringDirectory; /** `"symlink"` */ Value vStringSymlink; /** `"unknown"` */ Value vStringUnknown; /** * The accessor for the root filesystem. */ const ref<SourceAccessor> rootFS; /** * The in-memory filesystem for <nix/...> paths. */ const ref<MemorySourceAccessor> corepkgsFS; /** * In-memory filesystem for internal, non-user-callable Nix * expressions like call-flake.nix. */ const ref<MemorySourceAccessor> internalFS; const SourcePath derivationInternal; const SourcePath callFlakeInternal; /** * Store used to materialise .drv files. */ const ref<Store> store; /** * Store used to build stuff. */ const ref<Store> buildStore; RootValue vImportedDrvToDerivation = nullptr; /** * Debugger */ ReplExitStatus (* debugRepl)(ref<EvalState> es, const ValMap & extraEnv); bool debugStop; bool inDebugger = false; int trylevel; std::list<DebugTrace> debugTraces; std::map<const Expr*, const std::shared_ptr<const StaticEnv>> exprEnvs; const std::shared_ptr<const StaticEnv> getStaticEnv(const Expr & expr) const { auto i = exprEnvs.find(&expr); if (i != exprEnvs.end()) return i->second; else return std::shared_ptr<const StaticEnv>();; } /** Whether a debug repl can be started. If `false`, `runDebugRepl(error)` will return without starting a repl. */ bool canDebug(); /** Use front of `debugTraces`; see `runDebugRepl(error,env,expr)` */ void runDebugRepl(const Error * error); /** * Run a debug repl with the given error, environment and expression. * @param error The error to debug, may be nullptr. * @param env The environment to debug, matching the expression. * @param expr The expression to debug, matching the environment. */ void runDebugRepl(const Error * error, const Env & env, const Expr & expr); template<class T, typename... Args> [[nodiscard, gnu::noinline]] EvalErrorBuilder<T> & error(const Args & ... args) { // `EvalErrorBuilder::debugThrow` performs the corresponding `delete`. return *new EvalErrorBuilder<T>(*this, args...); } /** * A cache for evaluation caches, so as to reuse the same root value if possible */ std::map<const Hash, ref<eval_cache::EvalCache>> evalCaches; private: /* Cache for calls to addToStore(); maps source paths to the store paths. */ Sync<std::unordered_map<SourcePath, StorePath>> srcToStore; /** * A cache from path names to parse trees. */ typedef std::unordered_map<SourcePath, Expr *, std::hash<SourcePath>, std::equal_to<SourcePath>, traceable_allocator<std::pair<const SourcePath, Expr *>>> FileParseCache; FileParseCache fileParseCache; /** * A cache from path names to values. */ typedef std::unordered_map<SourcePath, Value, std::hash<SourcePath>, std::equal_to<SourcePath>, traceable_allocator<std::pair<const SourcePath, Value>>> FileEvalCache; FileEvalCache fileEvalCache; /** * Associate source positions of certain AST nodes with their preceding doc comment, if they have one. * Grouped by file. */ std::unordered_map<SourcePath, DocCommentMap> positionToDocComment; LookupPath lookupPath; std::map<std::string, std::optional<std::string>> lookupPathResolved; /** * Cache used by prim_match(). */ std::shared_ptr<RegexCache> regexCache; #if HAVE_BOEHMGC /** * Allocation cache for GC'd Value objects. */ std::shared_ptr<void *> valueAllocCache; /** * Allocation cache for size-1 Env objects. */ std::shared_ptr<void *> env1AllocCache; #endif public: EvalState( const LookupPath & _lookupPath, ref<Store> store, const fetchers::Settings & fetchSettings, const EvalSettings & settings, std::shared_ptr<Store> buildStore = nullptr); ~EvalState(); LookupPath getLookupPath() { return lookupPath; } /** * Return a `SourcePath` that refers to `path` in the root * filesystem. */ SourcePath rootPath(CanonPath path); /** * Variant which accepts relative paths too. */ SourcePath rootPath(PathView path); /** * Allow access to a path. */ void allowPath(const Path & path); /** * Allow access to a store path. Note that this gets remapped to * the real store path if `store` is a chroot store. */ void allowPath(const StorePath & storePath); /** * Allow access to a store path and return it as a string. */ void allowAndSetStorePathString(const StorePath & storePath, Value & v); void checkURI(const std::string & uri); /** * When using a diverted store and 'path' is in the Nix store, map * 'path' to the diverted location (e.g. /nix/store/foo is mapped * to /home/alice/my-nix/nix/store/foo). However, this is only * done if the context is not empty, since otherwise we're * probably trying to read from the actual /nix/store. This is * intended to distinguish between import-from-derivation and * sources stored in the actual /nix/store. */ Path toRealPath(const Path & path, const NixStringContext & context); /** * Parse a Nix expression from the specified file. */ Expr * parseExprFromFile(const SourcePath & path); Expr * parseExprFromFile(const SourcePath & path, std::shared_ptr<StaticEnv> & staticEnv); /** * Parse a Nix expression from the specified string. */ Expr * parseExprFromString(std::string s, const SourcePath & basePath, std::shared_ptr<StaticEnv> & staticEnv); Expr * parseExprFromString(std::string s, const SourcePath & basePath); Expr * parseStdin(); /** * Evaluate an expression read from the given file to normal * form. Optionally enforce that the top-level expression is * trivial (i.e. doesn't require arbitrary computation). */ void evalFile(const SourcePath & path, Value & v, bool mustBeTrivial = false); void resetFileCache(); /** * Look up a file in the search path. */ SourcePath findFile(const std::string_view path); SourcePath findFile(const LookupPath & lookupPath, const std::string_view path, const PosIdx pos = noPos); /** * Try to resolve a search path value (not the optional key part). * * If the specified search path element is a URI, download it. * * If it is not found, return `std::nullopt` */ std::optional<std::string> resolveLookupPathPath( const LookupPath::Path & elem, bool initAccessControl = false); /** * Evaluate an expression to normal form * * @param [out] v The resulting is stored here. */ void eval(Expr * e, Value & v); /** * Evaluation the expression, then verify that it has the expected * type. */ inline bool evalBool(Env & env, Expr * e); inline bool evalBool(Env & env, Expr * e, const PosIdx pos, std::string_view errorCtx); inline void evalAttrs(Env & env, Expr * e, Value & v, const PosIdx pos, std::string_view errorCtx); /** * If `v` is a thunk, enter it and overwrite `v` with the result * of the evaluation of the thunk. If `v` is a delayed function * application, call the function and overwrite `v` with the * result. Otherwise, this is a no-op. */ inline void forceValue(Value & v, const PosIdx pos); void tryFixupBlackHolePos(Value & v, PosIdx pos); /** * Force a value, then recursively force list elements and * attributes. */ void forceValueDeep(Value & v); /** * Force `v`, and then verify that it has the expected type. */ NixInt forceInt(Value & v, const PosIdx pos, std::string_view errorCtx); NixFloat forceFloat(Value & v, const PosIdx pos, std::string_view errorCtx); bool forceBool(Value & v, const PosIdx pos, std::string_view errorCtx); void forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx); template <typename Callable> inline void forceAttrs(Value & v, Callable getPos, std::string_view errorCtx); inline void forceList(Value & v, const PosIdx pos, std::string_view errorCtx); /** * @param v either lambda or primop */ void forceFunction(Value & v, const PosIdx pos, std::string_view errorCtx); std::string_view forceString(Value & v, const PosIdx pos, std::string_view errorCtx); std::string_view forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx); std::string_view forceStringNoCtx(Value & v, const PosIdx pos, std::string_view errorCtx); template<typename... Args> [[gnu::noinline]] void addErrorTrace(Error & e, const Args & ... formatArgs) const; template<typename... Args> [[gnu::noinline]] void addErrorTrace(Error & e, const PosIdx pos, const Args & ... formatArgs) const; public: /** * @return true iff the value `v` denotes a derivation (i.e. a * set with attribute `type = "derivation"`). */ bool isDerivation(Value & v); std::optional<std::string> tryAttrsToString(const PosIdx pos, Value & v, NixStringContext & context, bool coerceMore = false, bool copyToStore = true); /** * String coercion. * * Converts strings, paths and derivations to a * string. If `coerceMore` is set, also converts nulls, integers, * booleans and lists to a string. If `copyToStore` is set, * referenced paths are copied to the Nix store as a side effect. */ BackedStringView coerceToString(const PosIdx pos, Value & v, NixStringContext & context, std::string_view errorCtx, bool coerceMore = false, bool copyToStore = true, bool canonicalizePath = true); StorePath copyPathToStore(NixStringContext & context, const SourcePath & path); /** * Path coercion. * * Converts strings, paths and derivations to a * path. The result is guaranteed to be a canonicalised, absolute * path. Nothing is copied to the store. */ SourcePath coerceToPath(const PosIdx pos, Value & v, NixStringContext & context, std::string_view errorCtx); /** * Like coerceToPath, but the result must be a store path. */ StorePath coerceToStorePath(const PosIdx pos, Value & v, NixStringContext & context, std::string_view errorCtx); /** * Part of `coerceToSingleDerivedPath()` without any store IO which is exposed for unit testing only. */ std::pair<SingleDerivedPath, std::string_view> coerceToSingleDerivedPathUnchecked(const PosIdx pos, Value & v, std::string_view errorCtx); /** * Coerce to `SingleDerivedPath`. * * Must be a string which is either a literal store path or a * "placeholder (see `DownstreamPlaceholder`). * * Even more importantly, the string context must be exactly one * element, which is either a `NixStringContextElem::Opaque` or * `NixStringContextElem::Built`. (`NixStringContextEleme::DrvDeep` * is not permitted). * * The string is parsed based on the context --- the context is the * source of truth, and ultimately tells us what we want, and then * we ensure the string corresponds to it. */ SingleDerivedPath coerceToSingleDerivedPath(const PosIdx pos, Value & v, std::string_view errorCtx); #if HAVE_BOEHMGC /** A GC root for the baseEnv reference. */ std::shared_ptr<Env *> baseEnvP; #endif public: /** * The base environment, containing the builtin functions and * values. */ Env & baseEnv; /** * The same, but used during parsing to resolve variables. */ std::shared_ptr<StaticEnv> staticBaseEnv; // !!! should be private /** * Internal primops not exposed to the user. */ std::unordered_map<std::string, Value *, std::hash<std::string>, std::equal_to<std::string>, traceable_allocator<std::pair<const std::string, Value *>>> internalPrimOps; /** * Name and documentation about every constant. * * Constants from primops are hard to crawl, and their docs will go * here too. */ std::vector<std::pair<std::string, Constant>> constantInfos; private: unsigned int baseEnvDispl = 0; void createBaseEnv(); Value * addConstant(const std::string & name, Value & v, Constant info); void addConstant(const std::string & name, Value * v, Constant info); Value * addPrimOp(PrimOp && primOp); public: Value & getBuiltin(const std::string & name); struct Doc { Pos pos; std::optional<std::string> name; size_t arity; std::vector<std::string> args; /** * Unlike the other `doc` fields in this file, this one should never be * `null`. */ const char * doc; }; /** * Retrieve the documentation for a value. This will evaluate the value if * it is a thunk, and it will partially apply __functor if applicable. * * @param v The value to get the documentation for. */ std::optional<Doc> getDoc(Value & v); private: inline Value * lookupVar(Env * env, const ExprVar & var, bool noEval); friend struct ExprVar; friend struct ExprAttrs; friend struct ExprLet; Expr * parse( char * text, size_t length, Pos::Origin origin, const SourcePath & basePath, std::shared_ptr<StaticEnv> & staticEnv); /** * Current Nix call stack depth, used with `max-call-depth` setting to throw stack overflow hopefully before we run out of system stack. */ size_t callDepth = 0; public: /** * Check that the call depth is within limits, and increment it, until the returned object is destroyed. */ inline CallDepth addCallDepth(const PosIdx pos); /** * Do a deep equality test between two values. That is, list * elements and attributes are compared recursively. */ bool eqValues(Value & v1, Value & v2, const PosIdx pos, std::string_view errorCtx); /** * Like `eqValues`, but throws an `AssertionError` if not equal. * * WARNING: * Callers should call `eqValues` first and report if `assertEqValues` behaves * incorrectly. (e.g. if it doesn't throw if eqValues returns false or vice versa) */ void assertEqValues(Value & v1, Value & v2, const PosIdx pos, std::string_view errorCtx); bool isFunctor(Value & fun); // FIXME: use std::span void callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos); void callFunction(Value & fun, Value & arg, Value & vRes, const PosIdx pos) { Value * args[] = {&arg}; callFunction(fun, 1, args, vRes, pos); } /** * Automatically call a function for which each argument has a * default value or has a binding in the `args` map. */ void autoCallFunction(const Bindings & args, Value & fun, Value & res); /** * Allocation primitives. */ inline Value * allocValue(); inline Env & allocEnv(size_t size); Bindings * allocBindings(size_t capacity); BindingsBuilder buildBindings(size_t capacity) { return BindingsBuilder(*this, allocBindings(capacity)); } ListBuilder buildList(size_t size) { return ListBuilder(*this, size); } /** * Return a boolean `Value *` without allocating. */ Value *getBool(bool b); void mkThunk_(Value & v, Expr * expr); void mkPos(Value & v, PosIdx pos); /** * Create a string representing a store path. * * The string is the printed store path with a context containing a * single `NixStringContextElem::Opaque` element of that store path. */ void mkStorePathString(const StorePath & storePath, Value & v); /** * Create a string representing a `SingleDerivedPath::Built`. * * The string is the printed store path with a context containing a * single `NixStringContextElem::Built` element of the drv path and * output name. * * @param value Value we are settings * * @param b the drv whose output we are making a string for, and the * output * * @param optStaticOutputPath Optional output path for that string. * Must be passed if and only if output store object is * input-addressed or fixed output. Will be printed to form string * if passed, otherwise a placeholder will be used (see * `DownstreamPlaceholder`). * * @param xpSettings Stop-gap to avoid globals during unit tests. */ void mkOutputString( Value & value, const SingleDerivedPath::Built & b, std::optional<StorePath> optStaticOutputPath, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Create a string representing a `SingleDerivedPath`. * * A combination of `mkStorePathString` and `mkOutputString`. */ void mkSingleDerivedPathString( const SingleDerivedPath & p, Value & v); void concatLists(Value & v, size_t nrLists, Value * const * lists, const PosIdx pos, std::string_view errorCtx); /** * Print statistics, if enabled. * * Performs a full memory GC before printing the statistics, so that the * GC statistics are more accurate. */ void maybePrintStats(); /** * Print statistics, unconditionally, cheaply, without performing a GC first. */ void printStatistics(); /** * Perform a full memory garbage collection - not incremental. * * @return true if Nix was built with GC and a GC was performed, false if not. * The return value is currently not thread safe - just the return value. */ bool fullGC(); /** * Realise the given context * @param[in] context the context to realise * @param[out] maybePaths if not nullptr, all built or referenced store paths will be added to this set * @return a mapping from the placeholders used to construct the associated value to their final store path. */ [[nodiscard]] StringMap realiseContext(const NixStringContext & context, StorePathSet * maybePaths = nullptr, bool isIFD = true); /* Call the binary path filter predicate used builtins.path etc. */ bool callPathFilter( Value * filterFun, const SourcePath & path, std::string_view pathArg, PosIdx pos); DocComment getDocCommentForPos(PosIdx pos); private: /** * Like `mkOutputString` but just creates a raw string, not an * string Value, which would also have a string context. */ std::string mkOutputStringRaw( const SingleDerivedPath::Built & b, std::optional<StorePath> optStaticOutputPath, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); /** * Like `mkSingleDerivedPathStringRaw` but just creates a raw string * Value, which would also have a string context. */ std::string mkSingleDerivedPathStringRaw( const SingleDerivedPath & p); unsigned long nrEnvs = 0; unsigned long nrValuesInEnvs = 0; unsigned long nrValues = 0; unsigned long nrListElems = 0; unsigned long nrLookups = 0; unsigned long nrAttrsets = 0; unsigned long nrAttrsInAttrsets = 0; unsigned long nrAvoided = 0; unsigned long nrOpUpdates = 0; unsigned long nrOpUpdateValuesCopied = 0; unsigned long nrListConcats = 0; unsigned long nrPrimOpCalls = 0; unsigned long nrFunctionCalls = 0; bool countCalls; typedef std::map<std::string, size_t> PrimOpCalls; PrimOpCalls primOpCalls; typedef std::map<ExprLambda *, size_t> FunctionCalls; FunctionCalls functionCalls; void incrFunctionCall(ExprLambda * fun); typedef std::map<PosIdx, size_t> AttrSelects; AttrSelects attrSelects; friend struct ExprOpUpdate; friend struct ExprOpConcatLists; friend struct ExprVar; friend struct ExprString; friend struct ExprInt; friend struct ExprFloat; friend struct ExprPath; friend struct ExprSelect; friend void prim_getAttr(EvalState & state, const PosIdx pos, Value * * args, Value & v); friend void prim_match(EvalState & state, const PosIdx pos, Value * * args, Value & v); friend void prim_split(EvalState & state, const PosIdx pos, Value * * args, Value & v); friend struct Value; friend class ListBuilder; }; struct DebugTraceStacker { DebugTraceStacker(EvalState & evalState, DebugTrace t); ~DebugTraceStacker() { evalState.debugTraces.pop_front(); } EvalState & evalState; DebugTrace trace; }; /** * @return A string representing the type of the value `v`. * * @param withArticle Whether to begin with an english article, e.g. "an * integer" vs "integer". */ std::string_view showType(ValueType type, bool withArticle = true); std::string showType(const Value & v); /** * If `path` refers to a directory, then append "/default.nix". * * @param addDefaultNix Whether to append "/default.nix" after resolving symlinks. */ SourcePath resolveExprPath(SourcePath path, bool addDefaultNix = true); /** * Whether a URI is allowed, assuming restrictEval is enabled */ bool isAllowedURI(std::string_view uri, const Strings & allowedPaths); } #include "eval-inline.hh"
27,346
C++
.h
747
31.271754
174
0.675241
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,296
gc-small-vector.hh
NixOS_nix/src/libexpr/gc-small-vector.hh
#pragma once #include <boost/container/small_vector.hpp> #include "value.hh" namespace nix { /** * A GC compatible vector that may used a reserved portion of `nItems` on the stack instead of allocating on the heap. */ template <typename T, size_t nItems> using SmallVector = boost::container::small_vector<T, nItems, traceable_allocator<T>>; /** * A vector of value pointers. See `SmallVector`. */ template <size_t nItems> using SmallValueVector = SmallVector<Value *, nItems>; /** * A vector of values that must not be referenced after the vector is destroyed. * * See also `SmallValueVector`. */ template <size_t nItems> using SmallTemporaryValueVector = SmallVector<Value, nItems>; }
702
C++
.h
22
30.227273
118
0.762259
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,297
value-to-json.hh
NixOS_nix/src/libexpr/value-to-json.hh
#pragma once ///@file #include "nixexpr.hh" #include "eval.hh" #include <string> #include <map> #include <nlohmann/json_fwd.hpp> namespace nix { nlohmann::json printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, NixStringContext & context, bool copyToStore = true); void printValueAsJSON(EvalState & state, bool strict, Value & v, const PosIdx pos, std::ostream & str, NixStringContext & context, bool copyToStore = true); }
465
C++
.h
13
33.692308
106
0.753363
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,298
get-drvs.hh
NixOS_nix/src/libexpr/get-drvs.hh
#pragma once ///@file #include "eval.hh" #include "path.hh" #include <string> #include <map> namespace nix { /** * A "parsed" package attribute set. */ struct PackageInfo { public: typedef std::map<std::string, std::optional<StorePath>> Outputs; private: EvalState * state; mutable std::string name; mutable std::string system; mutable std::optional<std::optional<StorePath>> drvPath; mutable std::optional<StorePath> outPath; mutable std::string outputName; Outputs outputs; /** * Set if we get an AssertionError */ bool failed = false; const Bindings * attrs = nullptr, * meta = nullptr; const Bindings * getMeta(); bool checkMeta(Value & v); public: /** * path towards the derivation */ std::string attrPath; PackageInfo(EvalState & state) : state(&state) { }; PackageInfo(EvalState & state, std::string attrPath, const Bindings * attrs); PackageInfo(EvalState & state, ref<Store> store, const std::string & drvPathWithOutputs); std::string queryName() const; std::string querySystem() const; std::optional<StorePath> queryDrvPath() const; StorePath requireDrvPath() const; StorePath queryOutPath() const; std::string queryOutputName() const; /** * Return the unordered map of output names to (optional) output paths. * The "outputs to install" are determined by `meta.outputsToInstall`. */ Outputs queryOutputs(bool withPaths = true, bool onlyOutputsToInstall = false); StringSet queryMetaNames(); Value * queryMeta(const std::string & name); std::string queryMetaString(const std::string & name); NixInt queryMetaInt(const std::string & name, NixInt def); NixFloat queryMetaFloat(const std::string & name, NixFloat def); bool queryMetaBool(const std::string & name, bool def); void setMeta(const std::string & name, Value * v); /* MetaInfo queryMetaInfo(EvalState & state) const; MetaValue queryMetaInfo(EvalState & state, const string & name) const; */ void setName(const std::string & s) { name = s; } void setDrvPath(StorePath path) { drvPath = {{std::move(path)}}; } void setOutPath(StorePath path) { outPath = {{std::move(path)}}; } void setFailed() { failed = true; }; bool hasFailed() { return failed; }; }; typedef std::list<PackageInfo, traceable_allocator<PackageInfo>> PackageInfos; /** * If value `v` denotes a derivation, return a PackageInfo object * describing it. Otherwise return nothing. */ std::optional<PackageInfo> getDerivation(EvalState & state, Value & v, bool ignoreAssertionFailures); void getDerivations(EvalState & state, Value & v, const std::string & pathPrefix, Bindings & autoArgs, PackageInfos & drvs, bool ignoreAssertionFailures); }
2,818
C++
.h
76
32.855263
93
0.704085
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,299
function-trace.hh
NixOS_nix/src/libexpr/function-trace.hh
#pragma once ///@file #include "eval.hh" #include <chrono> namespace nix { struct FunctionCallTrace { const Pos pos; FunctionCallTrace(const Pos & pos); ~FunctionCallTrace(); }; }
196
C++
.h
12
14
39
0.727778
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,300
print.hh
NixOS_nix/src/libexpr/print.hh
#pragma once /** * @file * @brief Common printing functions for the Nix language * * While most types come with their own methods for printing, they share some * functions that are placed here. */ #include <iostream> #include "fmt.hh" #include "print-options.hh" namespace nix { class EvalState; struct Value; /** * Print a string as a Nix string literal. * * Quotes and fairly minimal escaping are added. * * @param o The output stream to print to * @param s The logical string */ std::ostream & printLiteralString(std::ostream & o, std::string_view s); inline std::ostream & printLiteralString(std::ostream & o, const char * s) { return printLiteralString(o, std::string_view(s)); } inline std::ostream & printLiteralString(std::ostream & o, const std::string & s) { return printLiteralString(o, std::string_view(s)); } /** Print `true` or `false`. */ std::ostream & printLiteralBool(std::ostream & o, bool b); /** * Print a string as an attribute name in the Nix expression language syntax. * * Prints a quoted string if necessary. */ std::ostream & printAttributeName(std::ostream & o, std::string_view s); /** * Returns `true' is a string is a reserved keyword which requires quotation * when printing attribute set field names. */ bool isReservedKeyword(const std::string_view str); /** * Print a string as an identifier in the Nix expression language syntax. * * FIXME: "identifier" is ambiguous. Identifiers do not have a single * textual representation. They can be used in variable references, * let bindings, left-hand sides or attribute names in a select * expression, or something else entirely, like JSON. Use one of the * `print*` functions instead. */ std::ostream & printIdentifier(std::ostream & o, std::string_view s); void printValue(EvalState & state, std::ostream & str, Value & v, PrintOptions options = PrintOptions {}); /** * A partially-applied form of `printValue` which can be formatted using `<<` * without allocating an intermediate string. */ class ValuePrinter { friend std::ostream & operator << (std::ostream & output, const ValuePrinter & printer); private: EvalState & state; Value & value; PrintOptions options; public: ValuePrinter(EvalState & state, Value & value, PrintOptions options = PrintOptions {}) : state(state), value(value), options(options) { } }; std::ostream & operator<<(std::ostream & output, const ValuePrinter & printer); /** * `ValuePrinter` does its own ANSI formatting, so we don't color it * magenta. */ template<> HintFmt & HintFmt::operator%(const ValuePrinter & value); }
2,649
C++
.h
75
33.173333
106
0.723612
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,301
pos-idx.hh
NixOS_nix/src/libexpr/pos-idx.hh
#pragma once #include <cinttypes> #include <functional> namespace nix { class PosIdx { friend struct LazyPosAcessors; friend class PosTable; friend class std::hash<PosIdx>; private: uint32_t id; explicit PosIdx(uint32_t id) : id(id) { } public: PosIdx() : id(0) { } explicit operator bool() const { return id > 0; } auto operator<=>(const PosIdx other) const { return id <=> other.id; } bool operator==(const PosIdx other) const { return id == other.id; } size_t hash() const noexcept { return std::hash<uint32_t>{}(id); } }; inline PosIdx noPos = {}; } namespace std { template<> struct hash<nix::PosIdx> { std::size_t operator()(nix::PosIdx pos) const noexcept { return pos.hash(); } }; } // namespace std
879
C++
.h
49
13.44898
58
0.601227
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,302
context.hh
NixOS_nix/src/libexpr/value/context.hh
#pragma once ///@file #include "comparator.hh" #include "derived-path.hh" #include "variant-wrapper.hh" #include <nlohmann/json_fwd.hpp> namespace nix { class BadNixStringContextElem : public Error { public: std::string_view raw; template<typename... Args> BadNixStringContextElem(std::string_view raw_, const Args & ... args) : Error("") { raw = raw_; auto hf = HintFmt(args...); err.msg = HintFmt("Bad String Context element: %1%: %2%", Uncolored(hf.str()), raw); } }; struct NixStringContextElem { /** * Plain opaque path to some store object. * * Encoded as just the path: `<path>`. */ using Opaque = SingleDerivedPath::Opaque; /** * Path to a derivation and its entire build closure. * * The path doesn't just refer to derivation itself and its closure, but * also all outputs of all derivations in that closure (including the * root derivation). * * Encoded in the form `=<drvPath>`. */ struct DrvDeep { StorePath drvPath; GENERATE_CMP(DrvDeep, me->drvPath); }; /** * Derivation output. * * Encoded in the form `!<output>!<drvPath>`. */ using Built = SingleDerivedPath::Built; using Raw = std::variant< Opaque, DrvDeep, Built >; Raw raw; GENERATE_CMP(NixStringContextElem, me->raw); MAKE_WRAPPER_CONSTRUCTOR(NixStringContextElem); /** * Decode a context string, one of: * - `<path>` * - `=<path>` * - `!<name>!<path>` * * @param xpSettings Stop-gap to avoid globals during unit tests. */ static NixStringContextElem parse( std::string_view s, const ExperimentalFeatureSettings & xpSettings = experimentalFeatureSettings); std::string to_string() const; }; typedef std::set<NixStringContextElem> NixStringContext; }
1,920
C++
.h
69
22.492754
92
0.634332
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,303
nix_api_external.h
NixOS_nix/src/libexpr-c/nix_api_external.h
#ifndef NIX_API_EXTERNAL_H #define NIX_API_EXTERNAL_H /** @ingroup libexpr * @addtogroup Externals * @brief Deal with external values * @{ */ /** @file * @brief libexpr C bindings dealing with external values */ #include "nix_api_expr.h" #include "nix_api_util.h" #include "nix_api_value.h" #include "stdbool.h" #include "stddef.h" #include "stdint.h" #ifdef __cplusplus extern "C" { #endif // cffi start /** * @brief Represents a string owned by the Nix language evaluator. * @see nix_set_owned_string */ typedef struct nix_string_return nix_string_return; /** * @brief Wraps a stream that can output multiple string pieces. */ typedef struct nix_printer nix_printer; /** * @brief A list of string context items */ typedef struct nix_string_context nix_string_context; /** * @brief Sets the contents of a nix_string_return * * Copies the passed string. * @param[out] str the nix_string_return to write to * @param[in] c The string to copy */ void nix_set_string_return(nix_string_return * str, const char * c); /** * Print to the nix_printer * * @param[out] context Optional, stores error information * @param[out] printer The nix_printer to print to * @param[in] str The string to print * @returns NIX_OK if everything worked */ nix_err nix_external_print(nix_c_context * context, nix_printer * printer, const char * str); /** * Add string context to the nix_string_context object * @param[out] context Optional, stores error information * @param[out] string_context The nix_string_context to add to * @param[in] c The context string to add * @returns NIX_OK if everything worked */ nix_err nix_external_add_string_context(nix_c_context * context, nix_string_context * string_context, const char * c); /** * @brief Definition for a class of external values * * Create and implement one of these, then pass it to nix_create_external_value * Make sure to keep it alive while the external value lives. * * Optional functions can be set to NULL * * @see nix_create_external_value */ typedef struct NixCExternalValueDesc { /** * @brief Called when printing the external value * * @param[in] self the void* passed to nix_create_external_value * @param[out] printer The printer to print to, pass to nix_external_print */ void (*print)(void * self, nix_printer * printer); /** * @brief Called on :t * @param[in] self the void* passed to nix_create_external_value * @param[out] res the return value */ void (*showType)(void * self, nix_string_return * res); /** * @brief Called on `builtins.typeOf` * @param self the void* passed to nix_create_external_value * @param[out] res the return value */ void (*typeOf)(void * self, nix_string_return * res); /** * @brief Called on "${str}" and builtins.toString. * * The latter with coerceMore=true * Optional, the default is to throw an error. * @param[in] self the void* passed to nix_create_external_value * @param[out] c writable string context for the resulting string * @param[in] coerceMore boolean, try to coerce to strings in more cases * instead of throwing an error * @param[in] copyToStore boolean, whether to copy referenced paths to store * or keep them as-is * @param[out] res the return value. Not touching this, or setting it to the * empty string, will make the conversion throw an error. */ void (*coerceToString)( void * self, nix_string_context * c, int coerceMore, int copyToStore, nix_string_return * res); /** * @brief Try to compare two external values * * Optional, the default is always false. * If the other object was not a Nix C external value, this comparison will * also return false * @param[in] self the void* passed to nix_create_external_value * @param[in] other the void* passed to the other object's * nix_create_external_value * @returns true if the objects are deemed to be equal */ int (*equal)(void * self, void * other); /** * @brief Convert the external value to json * * Optional, the default is to throw an error * @param[in] self the void* passed to nix_create_external_value * @param[in] state The evaluator state * @param[in] strict boolean Whether to force the value before printing * @param[out] c writable string context for the resulting string * @param[in] copyToStore whether to copy referenced paths to store or keep * them as-is * @param[out] res the return value. Gets parsed as JSON. Not touching this, * or setting it to the empty string, will make the conversion throw an error. */ void (*printValueAsJSON)( void * self, EvalState * state, bool strict, nix_string_context * c, bool copyToStore, nix_string_return * res); /** * @brief Convert the external value to XML * * Optional, the default is to throw an error * @todo The mechanisms for this call are incomplete. There are no C * bindings to work with XML, pathsets and positions. * @param[in] self the void* passed to nix_create_external_value * @param[in] state The evaluator state * @param[in] strict boolean Whether to force the value before printing * @param[in] location boolean Whether to include position information in the * xml * @param[out] doc XML document to output to * @param[out] c writable string context for the resulting string * @param[in,out] drvsSeen a path set to avoid duplicating derivations * @param[in] pos The position of the call. */ void (*printValueAsXML)( void * self, EvalState * state, int strict, int location, void * doc, nix_string_context * c, void * drvsSeen, int pos); } NixCExternalValueDesc; /** * @brief Create an external value, that can be given to nix_init_external * * Owned by the GC. Use nix_gc_decref when you're done with the pointer. * * @param[out] context Optional, stores error information * @param[in] desc a NixCExternalValueDesc, you should keep this alive as long * as the ExternalValue lives * @param[in] v the value to store * @returns external value, owned by the garbage collector * @see nix_init_external */ ExternalValue * nix_create_external_value(nix_c_context * context, NixCExternalValueDesc * desc, void * v); /** * @brief Extract the pointer from a nix c external value. * @param[out] context Optional, stores error information * @param[in] b The external value * @returns The pointer, or null if the external value was not from nix c. * @see nix_get_external */ void * nix_get_external_value_content(nix_c_context * context, ExternalValue * b); // cffi end #ifdef __cplusplus } #endif /** @} */ #endif // NIX_API_EXTERNAL_H
6,877
C++
.h
185
33.362162
120
0.696752
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,304
nix_api_expr.h
NixOS_nix/src/libexpr-c/nix_api_expr.h
#ifndef NIX_API_EXPR_H #define NIX_API_EXPR_H /** @defgroup libexpr libexpr * @brief Bindings to the Nix language evaluator * * See *[Embedding the Nix Evaluator](@ref nix_evaluator_example)* for an example. * @{ */ /** @file * @brief Main entry for the libexpr C bindings */ #include "nix_api_store.h" #include "nix_api_util.h" #include <stddef.h> #ifndef __has_c_attribute # define __has_c_attribute(x) 0 #endif #if __has_c_attribute(deprecated) # define NIX_DEPRECATED(msg) [[deprecated(msg)]] #else # define NIX_DEPRECATED(msg) #endif #ifdef __cplusplus extern "C" { #endif // cffi start // Type definitions /** * @brief Represents a state of the Nix language evaluator. * * Multiple states can be created for multi-threaded * operation. * @struct EvalState * @see nix_state_create */ typedef struct EvalState EvalState; // nix::EvalState /** @brief A Nix language value, or thunk that may evaluate to a value. * * Values are the primary objects manipulated in the Nix language. * They are considered to be immutable from a user's perspective, but the process of evaluating a value changes its * ValueType if it was a thunk. After a value has been evaluated, its ValueType does not change. * * Evaluation in this context refers to the process of evaluating a single value object, also called "forcing" the * value; see `nix_value_force`. * * The evaluator manages its own memory, but your use of the C API must follow the reference counting rules. * * @see value_manip * @see nix_value_incref, nix_value_decref */ typedef struct nix_value nix_value; NIX_DEPRECATED("use nix_value instead") typedef nix_value Value; // Function prototypes /** * @brief Initialize the Nix language evaluator. * * This function must be called at least once, * at some point before constructing a EvalState for the first time. * This function can be called multiple times, and is idempotent. * * @param[out] context Optional, stores error information * @return NIX_OK if the initialization was successful, an error code otherwise. */ nix_err nix_libexpr_init(nix_c_context * context); /** * @brief Parses and evaluates a Nix expression from a string. * * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[in] expr The Nix expression to parse. * @param[in] path The file path to associate with the expression. * This is required for expressions that contain relative paths (such as `./.`) that are resolved relative to the given * directory. * @param[out] value The result of the evaluation. You must allocate this * yourself. * @return NIX_OK if the evaluation was successful, an error code otherwise. */ nix_err nix_expr_eval_from_string( nix_c_context * context, EvalState * state, const char * expr, const char * path, nix_value * value); /** * @brief Calls a Nix function with an argument. * * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[in] fn The Nix function to call. * @param[in] arg The argument to pass to the function. * @param[out] value The result of the function call. * @return NIX_OK if the function call was successful, an error code otherwise. * @see nix_init_apply() for a similar function that does not performs the call immediately, but stores it as a thunk. * Note the different argument order. */ nix_err nix_value_call(nix_c_context * context, EvalState * state, nix_value * fn, nix_value * arg, nix_value * value); /** * @brief Calls a Nix function with multiple arguments. * * Technically these are functions that return functions. It is common for Nix * functions to be curried, so this function is useful for calling them. * * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[in] fn The Nix function to call. * @param[in] nargs The number of arguments. * @param[in] args The arguments to pass to the function. * @param[out] value The result of the function call. * * @see nix_value_call For the single argument primitive. * @see NIX_VALUE_CALL For a macro that wraps this function for convenience. */ nix_err nix_value_call_multi( nix_c_context * context, EvalState * state, nix_value * fn, size_t nargs, nix_value ** args, nix_value * value); /** * @brief Calls a Nix function with multiple arguments. * * Technically these are functions that return functions. It is common for Nix * functions to be curried, so this function is useful for calling them. * * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[out] value The result of the function call. * @param[in] fn The Nix function to call. * @param[in] ... The arguments to pass to the function. * * @see nix_value_call_multi */ #define NIX_VALUE_CALL(context, state, value, fn, ...) \ do { \ nix_value * args_array[] = {__VA_ARGS__}; \ size_t nargs = sizeof(args_array) / sizeof(args_array[0]); \ nix_value_call_multi(context, state, fn, nargs, args_array, value); \ } while (0) /** * @brief Forces the evaluation of a Nix value. * * The Nix interpreter is lazy, and not-yet-evaluated values can be * of type NIX_TYPE_THUNK instead of their actual value. * * This function mutates such a `nix_value`, so that, if successful, it has its final type. * * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[in,out] value The Nix value to force. * @post value is not of type NIX_TYPE_THUNK * @return NIX_OK if the force operation was successful, an error code * otherwise. */ nix_err nix_value_force(nix_c_context * context, EvalState * state, nix_value * value); /** * @brief Forces the deep evaluation of a Nix value. * * Recursively calls nix_value_force * * @see nix_value_force * @warning Calling this function on a recursive data structure will cause a * stack overflow. * @param[out] context Optional, stores error information * @param[in] state The state of the evaluation. * @param[in,out] value The Nix value to force. * @return NIX_OK if the deep force operation was successful, an error code * otherwise. */ nix_err nix_value_force_deep(nix_c_context * context, EvalState * state, nix_value * value); /** * @brief Create a new Nix language evaluator state. * * @param[out] context Optional, stores error information * @param[in] lookupPath Null-terminated array of strings corresponding to entries in NIX_PATH. * @param[in] store The Nix store to use. * @return A new Nix state or NULL on failure. */ EvalState * nix_state_create(nix_c_context * context, const char ** lookupPath, Store * store); /** * @brief Frees a Nix state. * * Does not fail. * * @param[in] state The state to free. */ void nix_state_free(EvalState * state); /** @addtogroup GC * @brief Reference counting and garbage collector operations * * The Nix language evaluator uses a garbage collector. To ease C interop, we implement * a reference counting scheme, where objects will be deallocated * when there are no references from the Nix side, and the reference count kept * by the C API reaches `0`. * * Functions returning a garbage-collected object will automatically increase * the refcount for you. You should make sure to call `nix_gc_decref` when * you're done with a value returned by the evaluator. * @{ */ // TODO: Deprecate nix_gc_incref in favor of the type-specific reference counting functions? // e.g. nix_value_incref. // It gives implementors more flexibility, and adds safety, so that generated // bindings can be used without fighting the host type system (where applicable). /** * @brief Increment the garbage collector reference counter for the given object. * * The Nix language evaluator C API keeps track of alive objects by reference counting. * When you're done with a refcounted pointer, call nix_gc_decref(). * * @param[out] context Optional, stores error information * @param[in] object The object to keep alive */ nix_err nix_gc_incref(nix_c_context * context, const void * object); /** * @brief Decrement the garbage collector reference counter for the given object * * @param[out] context Optional, stores error information * @param[in] object The object to stop referencing */ nix_err nix_gc_decref(nix_c_context * context, const void * object); /** * @brief Trigger the garbage collector manually * * You should not need to do this, but it can be useful for debugging. */ void nix_gc_now(); /** * @brief Register a callback that gets called when the object is garbage * collected. * @note Objects can only have a single finalizer. This function overwrites existing values * silently. * @param[in] obj the object to watch * @param[in] cd the data to pass to the finalizer * @param[in] finalizer the callback function, called with obj and cd */ void nix_gc_register_finalizer(void * obj, void * cd, void (*finalizer)(void * obj, void * cd)); /** @} */ // cffi end #ifdef __cplusplus } #endif /** @} */ #endif // NIX_API_EXPR_H
9,309
C++
.h
235
37.651064
119
0.72426
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,305
nix_api_value.h
NixOS_nix/src/libexpr-c/nix_api_value.h
#ifndef NIX_API_VALUE_H #define NIX_API_VALUE_H /** @addtogroup libexpr * @{ */ /** @file * @brief libexpr C bindings dealing with values */ #include "nix_api_util.h" #include "nix_api_store.h" #include "stdbool.h" #include "stddef.h" #include "stdint.h" #ifdef __cplusplus extern "C" { #endif // cffi start // Type definitions typedef enum { NIX_TYPE_THUNK, NIX_TYPE_INT, NIX_TYPE_FLOAT, NIX_TYPE_BOOL, NIX_TYPE_STRING, NIX_TYPE_PATH, NIX_TYPE_NULL, NIX_TYPE_ATTRS, NIX_TYPE_LIST, NIX_TYPE_FUNCTION, NIX_TYPE_EXTERNAL } ValueType; // forward declarations typedef struct nix_value nix_value; typedef struct EvalState EvalState; [[deprecated("use nix_value instead")]] typedef nix_value Value; // type defs /** @brief Stores an under-construction set of bindings * @ingroup value_manip * * Do not reuse. * @see nix_make_bindings_builder, nix_bindings_builder_free, nix_make_attrs * @see nix_bindings_builder_insert */ typedef struct BindingsBuilder BindingsBuilder; /** @brief Stores an under-construction list * @ingroup value_manip * * Do not reuse. * @see nix_make_list_builder, nix_list_builder_free, nix_make_list * @see nix_list_builder_insert */ typedef struct ListBuilder ListBuilder; /** @brief PrimOp function * @ingroup primops * * Owned by the GC * @see nix_alloc_primop, nix_init_primop */ typedef struct PrimOp PrimOp; /** @brief External Value * @ingroup Externals * * Owned by the GC */ typedef struct ExternalValue ExternalValue; /** @brief String without placeholders, and realised store paths */ typedef struct nix_realised_string nix_realised_string; /** @defgroup primops Adding primops * @{ */ /** @brief Function pointer for primops * * When you want to return an error, call nix_set_err_msg(context, NIX_ERR_UNKNOWN, "your error message here"). * * @param[in] user_data Arbitrary data that was initially supplied to nix_alloc_primop * @param[out] context Stores error information. * @param[in] state Evaluator state * @param[in] args list of arguments. Note that these can be thunks and should be forced using nix_value_force before * use. * @param[out] ret return value * @see nix_alloc_primop, nix_init_primop */ typedef void (*PrimOpFun)( void * user_data, nix_c_context * context, EvalState * state, nix_value ** args, nix_value * ret); /** @brief Allocate a PrimOp * * Owned by the garbage collector. * Use nix_gc_decref() when you're done with the returned PrimOp. * * @param[out] context Optional, stores error information * @param[in] fun callback * @param[in] arity expected number of function arguments * @param[in] name function name * @param[in] args array of argument names, NULL-terminated * @param[in] doc optional, documentation for this primop * @param[in] user_data optional, arbitrary data, passed to the callback when it's called * @return primop, or null in case of errors * @see nix_init_primop */ PrimOp * nix_alloc_primop( nix_c_context * context, PrimOpFun fun, int arity, const char * name, const char ** args, const char * doc, void * user_data); /** @brief add a primop to the `builtins` attribute set * * Only applies to States created after this call. * * Moves your PrimOp content into the global evaluator * registry, meaning your input PrimOp pointer is no longer usable. * You are free to remove your references to it, * after which it will be garbage collected. * * @param[out] context Optional, stores error information * @return primop, or null in case of errors * */ nix_err nix_register_primop(nix_c_context * context, PrimOp * primOp); /** @} */ // Function prototypes /** @brief Allocate a Nix value * * Owned by the GC. Use nix_gc_decref() when you're done with the pointer * @param[out] context Optional, stores error information * @param[in] state nix evaluator state * @return value, or null in case of errors * */ nix_value * nix_alloc_value(nix_c_context * context, EvalState * state); /** * @brief Increment the garbage collector reference counter for the given `nix_value`. * * The Nix language evaluator C API keeps track of alive objects by reference counting. * When you're done with a refcounted pointer, call nix_value_decref(). * * @param[out] context Optional, stores error information * @param[in] value The object to keep alive */ nix_err nix_value_incref(nix_c_context * context, nix_value * value); /** * @brief Decrement the garbage collector reference counter for the given object * * @param[out] context Optional, stores error information * @param[in] value The object to stop referencing */ nix_err nix_value_decref(nix_c_context * context, nix_value * value); /** @addtogroup value_manip Manipulating values * @brief Functions to inspect and change Nix language values, represented by nix_value. * @{ */ /** @anchor getters * @name Getters */ /**@{*/ /** @brief Get value type * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return type of nix value */ ValueType nix_get_type(nix_c_context * context, const nix_value * value); /** @brief Get type name of value as defined in the evaluator * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return type name, owned string * @todo way to free the result */ const char * nix_get_typename(nix_c_context * context, const nix_value * value); /** @brief Get boolean value * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return true or false, error info via context */ bool nix_get_bool(nix_c_context * context, const nix_value * value); /** @brief Get the raw string * * This may contain placeholders. * * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] callback Called with the string value. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @return string * @return error code, NIX_OK on success. */ nix_err nix_get_string(nix_c_context * context, const nix_value * value, nix_get_string_callback callback, void * user_data); /** @brief Get path as string * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return string * @return NULL in case of error. */ const char * nix_get_path_string(nix_c_context * context, const nix_value * value); /** @brief Get the length of a list * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return length of list, error info via context */ unsigned int nix_get_list_size(nix_c_context * context, const nix_value * value); /** @brief Get the element count of an attrset * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return attrset element count, error info via context */ unsigned int nix_get_attrs_size(nix_c_context * context, const nix_value * value); /** @brief Get float value in 64 bits * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return float contents, error info via context */ double nix_get_float(nix_c_context * context, const nix_value * value); /** @brief Get int value * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return int contents, error info via context */ int64_t nix_get_int(nix_c_context * context, const nix_value * value); /** @brief Get external reference * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @return reference to external, NULL in case of error */ ExternalValue * nix_get_external(nix_c_context * context, nix_value * value); /** @brief Get the ix'th element of a list * * Owned by the GC. Use nix_gc_decref when you're done with the pointer * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] state nix evaluator state * @param[in] ix list element to get * @return value, NULL in case of errors */ nix_value * nix_get_list_byidx(nix_c_context * context, const nix_value * value, EvalState * state, unsigned int ix); /** @brief Get an attr by name * * Owned by the GC. Use nix_gc_decref when you're done with the pointer * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] state nix evaluator state * @param[in] name attribute name * @return value, NULL in case of errors */ nix_value * nix_get_attr_byname(nix_c_context * context, const nix_value * value, EvalState * state, const char * name); /** @brief Check if an attribute name exists on a value * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] state nix evaluator state * @param[in] name attribute name * @return value, error info via context */ bool nix_has_attr_byname(nix_c_context * context, const nix_value * value, EvalState * state, const char * name); /** @brief Get an attribute by index in the sorted bindings * * Also gives you the name. * * Owned by the GC. Use nix_gc_decref when you're done with the pointer * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] state nix evaluator state * @param[in] i attribute index * @param[out] name will store a pointer to the attribute name * @return value, NULL in case of errors */ nix_value * nix_get_attr_byidx( nix_c_context * context, const nix_value * value, EvalState * state, unsigned int i, const char ** name); /** @brief Get an attribute name by index in the sorted bindings * * Useful when you want the name but want to avoid evaluation. * * Owned by the nix EvalState * @param[out] context Optional, stores error information * @param[in] value Nix value to inspect * @param[in] state nix evaluator state * @param[in] i attribute index * @return name, NULL in case of errors */ const char * nix_get_attr_name_byidx(nix_c_context * context, const nix_value * value, EvalState * state, unsigned int i); /**@}*/ /** @name Initializers * * Values are typically "returned" by initializing already allocated memory that serves as the return value. * For this reason, the construction of values is not tied their allocation. * Nix is a language with immutable values. Respect this property by only initializing Values once; and only initialize * Values that are meant to be initialized by you. Failing to adhere to these rules may lead to undefined behavior. */ /**@{*/ /** @brief Set boolean value * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] b the boolean value * @return error code, NIX_OK on success. */ nix_err nix_init_bool(nix_c_context * context, nix_value * value, bool b); /** @brief Set a string * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] str the string, copied * @return error code, NIX_OK on success. */ nix_err nix_init_string(nix_c_context * context, nix_value * value, const char * str); /** @brief Set a path * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] str the path string, copied * @return error code, NIX_OK on success. */ nix_err nix_init_path_string(nix_c_context * context, EvalState * s, nix_value * value, const char * str); /** @brief Set a float * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] d the float, 64-bits * @return error code, NIX_OK on success. */ nix_err nix_init_float(nix_c_context * context, nix_value * value, double d); /** @brief Set an int * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] i the int * @return error code, NIX_OK on success. */ nix_err nix_init_int(nix_c_context * context, nix_value * value, int64_t i); /** @brief Set null * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @return error code, NIX_OK on success. */ nix_err nix_init_null(nix_c_context * context, nix_value * value); /** @brief Set the value to a thunk that will perform a function application when needed. * * Thunks may be put into attribute sets and lists to perform some computation lazily; on demand. * However, note that in some places, a thunk must not be returned, such as in the return value of a PrimOp. * In such cases, you may use nix_value_call() instead (but note the different argument order). * * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] fn function to call * @param[in] arg argument to pass * @return error code, NIX_OK on successful initialization. * @see nix_value_call() for a similar function that performs the call immediately and only stores the return value. * Note the different argument order. */ nix_err nix_init_apply(nix_c_context * context, nix_value * value, nix_value * fn, nix_value * arg); /** @brief Set an external value * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] val the external value to set. Will be GC-referenced by the value. * @return error code, NIX_OK on success. */ nix_err nix_init_external(nix_c_context * context, nix_value * value, ExternalValue * val); /** @brief Create a list from a list builder * @param[out] context Optional, stores error information * @param[in] list_builder list builder to use. Make sure to unref this afterwards. * @param[out] value Nix value to modify * @return error code, NIX_OK on success. */ nix_err nix_make_list(nix_c_context * context, ListBuilder * list_builder, nix_value * value); /** @brief Create a list builder * @param[out] context Optional, stores error information * @param[in] state nix evaluator state * @param[in] capacity how many bindings you'll add. Don't exceed. * @return owned reference to a list builder. Make sure to unref when you're done. */ ListBuilder * nix_make_list_builder(nix_c_context * context, EvalState * state, size_t capacity); /** @brief Insert bindings into a builder * @param[out] context Optional, stores error information * @param[in] list_builder ListBuilder to insert into * @param[in] index index to manipulate * @param[in] value value to insert * @return error code, NIX_OK on success. */ nix_err nix_list_builder_insert(nix_c_context * context, ListBuilder * list_builder, unsigned int index, nix_value * value); /** @brief Free a list builder * * Does not fail. * @param[in] list_builder The builder to free. */ void nix_list_builder_free(ListBuilder * list_builder); /** @brief Create an attribute set from a bindings builder * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] b bindings builder to use. Make sure to unref this afterwards. * @return error code, NIX_OK on success. */ nix_err nix_make_attrs(nix_c_context * context, nix_value * value, BindingsBuilder * b); /** @brief Set primop * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] op primop, will be gc-referenced by the value * @see nix_alloc_primop * @return error code, NIX_OK on success. */ nix_err nix_init_primop(nix_c_context * context, nix_value * value, PrimOp * op); /** @brief Copy from another value * @param[out] context Optional, stores error information * @param[out] value Nix value to modify * @param[in] source value to copy from * @return error code, NIX_OK on success. */ nix_err nix_copy_value(nix_c_context * context, nix_value * value, const nix_value * source); /**@}*/ /** @brief Create a bindings builder * @param[out] context Optional, stores error information * @param[in] state nix evaluator state * @param[in] capacity how many bindings you'll add. Don't exceed. * @return owned reference to a bindings builder. Make sure to unref when you're done. */ BindingsBuilder * nix_make_bindings_builder(nix_c_context * context, EvalState * state, size_t capacity); /** @brief Insert bindings into a builder * @param[out] context Optional, stores error information * @param[in] builder BindingsBuilder to insert into * @param[in] name attribute name, only used for the duration of the call. * @param[in] value value to give the binding * @return error code, NIX_OK on success. */ nix_err nix_bindings_builder_insert(nix_c_context * context, BindingsBuilder * builder, const char * name, nix_value * value); /** @brief Free a bindings builder * * Does not fail. * @param[in] builder the builder to free */ void nix_bindings_builder_free(BindingsBuilder * builder); /**@}*/ /** @brief Realise a string context. * * This will * - realise the store paths referenced by the string's context, and * - perform the replacement of placeholders. * - create temporary garbage collection roots for the store paths, for * the lifetime of the current process. * - log to stderr * * @param[out] context Optional, stores error information * @param[in] value Nix value, which must be a string * @param[in] state Nix evaluator state * @param[in] isIFD If true, disallow derivation outputs if setting `allow-import-from-derivation` is false. You should set this to true when this call is part of a primop. You should set this to false when building for your application's purpose. * @return NULL if failed, are a new nix_realised_string, which must be freed with nix_realised_string_free */ nix_realised_string * nix_string_realise(nix_c_context * context, EvalState * state, nix_value * value, bool isIFD); /** @brief Start of the string * @param[in] realised_string * @return pointer to the start of the string. It may not be null-terminated. */ const char * nix_realised_string_get_buffer_start(nix_realised_string * realised_string); /** @brief Length of the string * @param[in] realised_string * @return length of the string in bytes */ size_t nix_realised_string_get_buffer_size(nix_realised_string * realised_string); /** @brief Number of realised store paths * @param[in] realised_string * @return number of realised store paths that were referenced by the string via its context */ size_t nix_realised_string_get_store_path_count(nix_realised_string * realised_string); /** @brief Get a store path. The store paths are stored in an arbitrary order. * @param[in] realised_string * @param[in] index index of the store path, must be less than the count * @return store path */ const StorePath * nix_realised_string_get_store_path(nix_realised_string * realised_string, size_t index); /** @brief Free a realised string * @param[in] realised_string */ void nix_realised_string_free(nix_realised_string * realised_string); // cffi end #ifdef __cplusplus } #endif /** @} */ #endif // NIX_API_VALUE_H
19,170
C++
.h
479
38.006263
120
0.735806
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,306
nix_api_expr_internal.h
NixOS_nix/src/libexpr-c/nix_api_expr_internal.h
#ifndef NIX_API_EXPR_INTERNAL_H #define NIX_API_EXPR_INTERNAL_H #include "fetch-settings.hh" #include "eval.hh" #include "eval-settings.hh" #include "attr-set.hh" #include "nix_api_value.h" struct EvalState { nix::fetchers::Settings fetchSettings; nix::EvalSettings settings; nix::EvalState state; }; struct BindingsBuilder { nix::BindingsBuilder builder; }; struct ListBuilder { nix::ListBuilder builder; }; struct nix_value { nix::Value value; }; struct nix_string_return { std::string str; }; struct nix_printer { std::ostream & s; }; struct nix_string_context { nix::NixStringContext & ctx; }; struct nix_realised_string { std::string str; std::vector<StorePath> storePaths; }; #endif // NIX_API_EXPR_INTERNAL_H
770
C++
.h
43
15.651163
42
0.739191
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,307
loggers.hh
NixOS_nix/src/libmain/loggers.hh
#pragma once ///@file #include "types.hh" namespace nix { enum class LogFormat { raw, rawWithLogs, internalJSON, bar, barWithLogs, }; void setLogFormat(const std::string & logFormatStr); void setLogFormat(const LogFormat & logFormat); void createDefaultLogger(); }
281
C++
.h
15
16.666667
52
0.776923
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
11,308
plugin.hh
NixOS_nix/src/libmain/plugin.hh
#pragma once ///@file namespace nix { /** * This should be called after settings are initialized, but before * anything else */ void initPlugins(); }
156
C++
.h
9
15.666667
67
0.743056
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,309
shared.hh
NixOS_nix/src/libmain/shared.hh
#pragma once ///@file #include "file-descriptor.hh" #include "processes.hh" #include "args.hh" #include "args/root.hh" #include "common-args.hh" #include "path.hh" #include "derived-path.hh" #include <signal.h> namespace nix { int handleExceptions(const std::string & programName, std::function<void()> fun); /** * Don't forget to call initPlugins() after settings are initialized! * @param loadConfig Whether to load configuration from `nix.conf`, `NIX_CONFIG`, etc. May be disabled for unit tests. */ void initNix(bool loadConfig = true); void parseCmdLine(int argc, char * * argv, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg); void parseCmdLine(const std::string & programName, const Strings & args, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg); void printVersion(const std::string & programName); /** * Ugh. No better place to put this. */ void printGCWarning(); class Store; void printMissing( ref<Store> store, const std::vector<DerivedPath> & paths, Verbosity lvl = lvlInfo); void printMissing(ref<Store> store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, uint64_t downloadSize, uint64_t narSize, Verbosity lvl = lvlInfo); std::string getArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end); template<class N> N getIntArg(const std::string & opt, Strings::iterator & i, const Strings::iterator & end, bool allowUnit) { ++i; if (i == end) throw UsageError("'%1%' requires an argument", opt); return string2IntWithUnitPrefix<N>(*i); } struct LegacyArgs : public MixCommonArgs, public RootArgs { std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg; LegacyArgs(const std::string & programName, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg); bool processFlag(Strings::iterator & pos, Strings::iterator end) override; bool processArgs(const Strings & args, bool finish) override; }; /** * Show the manual page for the specified program. */ void showManPage(const std::string & name); /** * The constructor of this class starts a pager if standard output is a * terminal and $PAGER is set. Standard output is redirected to the * pager. */ class RunPager { public: RunPager(); ~RunPager(); private: #ifndef _WIN32 // TODO re-enable on Windows, once we can start processes. Pid pid; #endif Descriptor std_out; }; extern volatile ::sig_atomic_t blockInt; /* GC helpers. */ std::string showBytes(uint64_t bytes); struct GCResults; struct PrintFreed { bool show; const GCResults & results; PrintFreed(bool show, const GCResults & results) : show(show), results(results) { } ~PrintFreed(); }; #ifndef _WIN32 /** * Install a SIGSEGV handler to detect stack overflows. */ void detectStackOverflow(); /** * Pluggable behavior to run in case of a stack overflow. * * Default value: defaultStackOverflowHandler. * * This is called by the handler installed by detectStackOverflow(). * * This gives Nix library consumers a limit opportunity to report the error * condition. The handler should exit the process. * See defaultStackOverflowHandler() for a reference implementation. * * NOTE: Use with diligence, because this runs in the signal handler, with very * limited stack space and a potentially a corrupted heap, all while the failed * thread is blocked indefinitely. All functions called must be reentrant. */ extern std::function<void(siginfo_t * info, void * ctx)> stackOverflowHandler; /** * The default, robust implementation of stackOverflowHandler. * * Prints an error message directly to stderr using a syscall instead of the * logger. Exits the process immediately after. */ void defaultStackOverflowHandler(siginfo_t * info, void * ctx); #endif }
3,968
C++
.h
113
32.539823
118
0.742999
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,310
common-args.hh
NixOS_nix/src/libmain/common-args.hh
#pragma once ///@file #include "args.hh" #include "repair-flag.hh" namespace nix { //static constexpr auto commonArgsCategory = "Miscellaneous common options"; static constexpr auto loggingCategory = "Logging-related options"; static constexpr auto miscCategory = "Miscellaneous global options"; class MixCommonArgs : public virtual Args { void initialFlagsProcessed() override; public: std::string programName; MixCommonArgs(const std::string & programName); protected: virtual void pluginsInited() {} }; struct MixDryRun : virtual Args { bool dryRun = false; MixDryRun() { addFlag({ .longName = "dry-run", .description = "Show what this command would do without doing it.", //.category = commonArgsCategory, .handler = {&dryRun, true}, }); } }; struct MixJSON : virtual Args { bool json = false; MixJSON() { addFlag({ .longName = "json", .description = "Produce output in JSON format, suitable for consumption by another program.", //.category = commonArgsCategory, .handler = {&json, true}, }); } }; struct MixRepair : virtual Args { RepairFlag repair = NoRepair; MixRepair() { addFlag({ .longName = "repair", .description = "During evaluation, rewrite missing or corrupted files in the Nix store. " "During building, rebuild missing or corrupted store paths.", .category = miscCategory, .handler = {&repair, Repair}, }); } }; }
1,631
C++
.h
59
21.576271
105
0.627162
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,311
progress-bar.hh
NixOS_nix/src/libmain/progress-bar.hh
#pragma once ///@file #include "logging.hh" namespace nix { Logger * makeProgressBar(); void startProgressBar(); void stopProgressBar(); }
145
C++
.h
8
16.375
27
0.778626
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,312
user-env.hh
NixOS_nix/src/nix-env/user-env.hh
#pragma once ///@file #include "get-drvs.hh" namespace nix { PackageInfos queryInstalled(EvalState & state, const Path & userEnv); bool createUserEnv(EvalState & state, PackageInfos & elems, const Path & profile, bool keepDerivations, const std::string & lockToken); }
282
C++
.h
9
28.888889
69
0.761194
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,313
url-name.hh
NixOS_nix/src/libflake/flake/url-name.hh
#include "url.hh" #include "url-parts.hh" #include "util.hh" #include "split.hh" namespace nix { /** * Try to extract a reasonably unique and meaningful, human-readable * name of a flake output from a parsed URL. * When nullopt is returned, the callsite should use information available * to it outside of the URL to determine a useful name. * This is a heuristic approach intended for user interfaces. * @return nullopt if the extracted name is not useful to identify a * flake output, for example because it is empty or "default". * Otherwise returns the extracted name. */ std::optional<std::string> getNameFromURL(const ParsedURL & url); }
656
C++
.h
17
36.882353
74
0.767296
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,314
lockfile.hh
NixOS_nix/src/libflake/flake/lockfile.hh
#pragma once ///@file #include "flakeref.hh" #include <nlohmann/json_fwd.hpp> namespace nix { class Store; class StorePath; } namespace nix::flake { typedef std::vector<FlakeId> InputPath; struct LockedNode; /** * A node in the lock file. It has outgoing edges to other nodes (its * inputs). Only the root node has this type; all other nodes have * type LockedNode. */ struct Node : std::enable_shared_from_this<Node> { typedef std::variant<ref<LockedNode>, InputPath> Edge; std::map<FlakeId, Edge> inputs; virtual ~Node() { } }; /** * A non-root node in the lock file. */ struct LockedNode : Node { FlakeRef lockedRef, originalRef; bool isFlake = true; LockedNode( const FlakeRef & lockedRef, const FlakeRef & originalRef, bool isFlake = true) : lockedRef(lockedRef), originalRef(originalRef), isFlake(isFlake) { } LockedNode( const fetchers::Settings & fetchSettings, const nlohmann::json & json); StorePath computeStorePath(Store & store) const; }; struct LockFile { ref<Node> root = make_ref<Node>(); LockFile() {}; LockFile( const fetchers::Settings & fetchSettings, std::string_view contents, std::string_view path); typedef std::map<ref<const Node>, std::string> KeyMap; std::pair<nlohmann::json, KeyMap> toJSON() const; std::pair<std::string, KeyMap> to_string() const; /** * Check whether this lock file has any unlocked or non-final * inputs. If so, return one. */ std::optional<FlakeRef> isUnlocked() const; bool operator ==(const LockFile & other) const; std::shared_ptr<Node> findInput(const InputPath & path); std::map<InputPath, Node::Edge> getAllInputs() const; static std::string diff(const LockFile & oldLocks, const LockFile & newLocks); /** * Check that every 'follows' input target exists. */ void check(); }; std::ostream & operator <<(std::ostream & stream, const LockFile & lockFile); InputPath parseInputPath(std::string_view s); std::string printInputPath(const InputPath & path); }
2,124
C++
.h
68
27.073529
82
0.689349
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,315
flakeref.hh
NixOS_nix/src/libflake/flake/flakeref.hh
#pragma once ///@file #include <regex> #include "types.hh" #include "fetchers.hh" #include "outputs-spec.hh" namespace nix { class Store; typedef std::string FlakeId; /** * A flake reference specifies how to fetch a flake or raw source * (e.g. from a Git repository). It is created from a URL-like syntax * (e.g. 'github:NixOS/patchelf'), an attrset representation (e.g. '{ * type="github"; owner = "NixOS"; repo = "patchelf"; }'), or a local * path. * * Each flake will have a number of FlakeRef objects: one for each * input to the flake. * * The normal method of constructing a FlakeRef is by starting with an * input description (usually the attrs or a url from the flake file), * locating a fetcher for that input, and then capturing the Input * object that fetcher generates (usually via * FlakeRef::fromAttrs(attrs) or parseFlakeRef(url) calls). * * The actual fetch may not have been performed yet (i.e. a FlakeRef may * be lazy), but the fetcher can be invoked at any time via the * FlakeRef to ensure the store is populated with this input. */ struct FlakeRef { /** * Fetcher-specific representation of the input, sufficient to * perform the fetch operation. */ fetchers::Input input; /** * sub-path within the fetched input that represents this input */ Path subdir; bool operator ==(const FlakeRef & other) const = default; FlakeRef(fetchers::Input && input, const Path & subdir) : input(std::move(input)), subdir(subdir) { } // FIXME: change to operator <<. std::string to_string() const; fetchers::Attrs toAttrs() const; FlakeRef resolve(ref<Store> store) const; static FlakeRef fromAttrs( const fetchers::Settings & fetchSettings, const fetchers::Attrs & attrs); std::pair<StorePath, FlakeRef> fetchTree(ref<Store> store) const; }; std::ostream & operator << (std::ostream & str, const FlakeRef & flakeRef); /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ FlakeRef parseFlakeRef( const fetchers::Settings & fetchSettings, const std::string & url, const std::optional<Path> & baseDir = {}, bool allowMissing = false, bool isFlake = true); /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ std::optional<FlakeRef> maybeParseFlake( const fetchers::Settings & fetchSettings, const std::string & url, const std::optional<Path> & baseDir = {}); /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment( const fetchers::Settings & fetchSettings, const std::string & url, const std::optional<Path> & baseDir = {}, bool allowMissing = false, bool isFlake = true); /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ std::optional<std::pair<FlakeRef, std::string>> maybeParseFlakeRefWithFragment( const fetchers::Settings & fetchSettings, const std::string & url, const std::optional<Path> & baseDir = {}); /** * @param baseDir Optional [base directory](https://nixos.org/manual/nix/unstable/glossary#gloss-base-directory) */ std::tuple<FlakeRef, std::string, ExtendedOutputsSpec> parseFlakeRefWithFragmentAndExtendedOutputsSpec( const fetchers::Settings & fetchSettings, const std::string & url, const std::optional<Path> & baseDir = {}, bool allowMissing = false, bool isFlake = true); const static std::string flakeIdRegexS = "[a-zA-Z][a-zA-Z0-9_-]*"; extern std::regex flakeIdRegex; }
3,759
C++
.h
98
34.94898
112
0.715581
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,316
flake.hh
NixOS_nix/src/libflake/flake/flake.hh
#pragma once ///@file #include "types.hh" #include "flakeref.hh" #include "lockfile.hh" #include "value.hh" namespace nix { class EvalState; namespace flake { struct Settings; /** * Initialize `libnixflake` * * So far, this registers the `builtins.getFlake` primop, which depends * on the choice of `flake:Settings`. */ void initLib(const Settings & settings); struct FlakeInput; typedef std::map<FlakeId, FlakeInput> FlakeInputs; /** * FlakeInput is the 'Flake'-level parsed form of the "input" entries * in the flake file. * * A FlakeInput is normally constructed by the 'parseFlakeInput' * function which parses the input specification in the '.flake' file * to create a 'FlakeRef' (a fetcher, the fetcher-specific * representation of the input specification, and possibly the fetched * local store path result) and then creating this FlakeInput to hold * that FlakeRef, along with anything that might override that * FlakeRef (like command-line overrides or "follows" specifications). * * A FlakeInput is also sometimes constructed directly from a FlakeRef * instead of starting at the flake-file input specification * (e.g. overrides, follows, and implicit inputs). * * A FlakeInput will usually have one of either "ref" or "follows" * set. If not otherwise specified, a "ref" will be generated to a * 'type="indirect"' flake, which is treated as simply the name of a * flake to be resolved in the registry. */ struct FlakeInput { std::optional<FlakeRef> ref; /** * true = process flake to get outputs * * false = (fetched) static source path */ bool isFlake = true; std::optional<InputPath> follows; FlakeInputs overrides; }; struct ConfigFile { using ConfigValue = std::variant<std::string, int64_t, Explicit<bool>, std::vector<std::string>>; std::map<std::string, ConfigValue> settings; void apply(const Settings & settings); }; /** * The contents of a flake.nix file. */ struct Flake { /** * The original flake specification (by the user) */ FlakeRef originalRef; /** * registry references and caching resolved to the specific underlying flake */ FlakeRef resolvedRef; /** * the specific local store result of invoking the fetcher */ FlakeRef lockedRef; /** * The path of `flake.nix`. */ SourcePath path; /** * pretend that 'lockedRef' is dirty */ bool forceDirty = false; std::optional<std::string> description; FlakeInputs inputs; /** * 'nixConfig' attribute */ ConfigFile config; ~Flake(); SourcePath lockFilePath() { return path.parent() / "flake.lock"; } }; Flake getFlake(EvalState & state, const FlakeRef & flakeRef, bool allowLookup); /** * Fingerprint of a locked flake; used as a cache key. */ typedef Hash Fingerprint; struct LockedFlake { Flake flake; LockFile lockFile; /** * Source tree accessors for nodes that have been fetched in * lockFlake(); in particular, the root node and the overriden * inputs. */ std::map<ref<Node>, SourcePath> nodePaths; std::optional<Fingerprint> getFingerprint(ref<Store> store) const; }; struct LockFlags { /** * Whether to ignore the existing lock file, creating a new one * from scratch. */ bool recreateLockFile = false; /** * Whether to update the lock file at all. If set to false, if any * change to the lock file is needed (e.g. when an input has been * added to flake.nix), you get a fatal error. */ bool updateLockFile = true; /** * Whether to write the lock file to disk. If set to true, if the * any changes to the lock file are needed and the flake is not * writable (i.e. is not a local Git working tree or similar), you * get a fatal error. If set to false, Nix will use the modified * lock file in memory only, without writing it to disk. */ bool writeLockFile = true; /** * Whether to use the registries to lookup indirect flake * references like 'nixpkgs'. */ std::optional<bool> useRegistries = std::nullopt; /** * Whether to apply flake's nixConfig attribute to the configuration */ bool applyNixConfig = false; /** * Whether unlocked flake references (i.e. those without a Git * revision or similar) without a corresponding lock are * allowed. Unlocked flake references with a lock are always * allowed. */ bool allowUnlocked = true; /** * Whether to commit changes to flake.lock. */ bool commitLockFile = false; /** * The path to a lock file to read instead of the `flake.lock` file in the top-level flake */ std::optional<SourcePath> referenceLockFilePath; /** * The path to a lock file to write to instead of the `flake.lock` file in the top-level flake */ std::optional<Path> outputLockFilePath; /** * Flake inputs to be overridden. */ std::map<InputPath, FlakeRef> inputOverrides; /** * Flake inputs to be updated. This means that any existing lock * for those inputs will be ignored. */ std::set<InputPath> inputUpdates; }; LockedFlake lockFlake( const Settings & settings, EvalState & state, const FlakeRef & flakeRef, const LockFlags & lockFlags); void callFlake( EvalState & state, const LockedFlake & lockedFlake, Value & v); /** * Map a `SourcePath` to the corresponding store path. This is a * temporary hack to support chroot stores while we don't have full * lazy trees. FIXME: Remove this once we can pass a sourcePath rather * than a storePath to call-flake.nix. */ std::pair<StorePath, Path> sourcePathToStorePath( ref<Store> store, const SourcePath & path); } void emitTreeAttrs( EvalState & state, const StorePath & storePath, const fetchers::Input & input, Value & v, bool emptyRevFallback = false, bool forceDirty = false); /** * An internal builtin similar to `fetchTree`, except that it * always treats the input as final (i.e. no attributes can be * added/removed/changed). */ void prim_fetchFinalTree(EvalState & state, const PosIdx pos, Value * * args, Value & v); }
6,298
C++
.h
204
26.794118
101
0.6926
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,317
settings.hh
NixOS_nix/src/libflake/flake/settings.hh
#pragma once ///@file #include "types.hh" #include "config.hh" #include "util.hh" #include <map> #include <limits> #include <sys/types.h> namespace nix::flake { struct Settings : public Config { Settings(); Setting<bool> useRegistries{ this, true, "use-registries", "Whether to use flake registries to resolve flake references.", {}, true, Xp::Flakes}; Setting<bool> acceptFlakeConfig{ this, false, "accept-flake-config", "Whether to accept nix configuration from a flake without prompting.", {}, true, Xp::Flakes}; Setting<std::string> commitLockFileSummary{ this, "", "commit-lock-file-summary", R"( The commit summary to use when committing changed flake lock files. If empty, the summary is generated based on the action performed. )", {"commit-lockfile-summary"}, true, Xp::Flakes}; }; }
1,014
C++
.h
41
18.341463
80
0.603734
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,318
nix_api_main.h
NixOS_nix/src/libmain-c/nix_api_main.h
#ifndef NIX_API_MAIN_H #define NIX_API_MAIN_H /** * @defgroup libmain libmain * @brief C bindings for nix libmain * * libmain has misc utilities for CLI commands * @{ */ /** @file * @brief Main entry for the libmain C bindings */ #include "nix_api_util.h" #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif // cffi start /** * @brief Loads the plugins specified in Nix's plugin-files setting. * * Call this once, after calling your desired init functions and setting * relevant settings. * * @param[out] context Optional, stores error information * @return NIX_OK if the initialization was successful, an error code otherwise. */ nix_err nix_init_plugins(nix_c_context * context); // cffi end #ifdef __cplusplus } #endif /** * @} */ #endif // NIX_API_MAIN_H
789
C++
.h
36
20.305556
80
0.724967
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,319
nix_api_util.h
NixOS_nix/src/libutil-c/nix_api_util.h
#ifndef NIX_API_UTIL_H #define NIX_API_UTIL_H /** * @defgroup libutil libutil * @brief C bindings for nix libutil * * libutil is used for functionality shared between * different Nix modules. * @{ */ /** @file * @brief Main entry for the libutil C bindings * * Also contains error handling utilities */ #ifdef __cplusplus extern "C" { #endif // cffi start /** @defgroup errors Handling errors * @brief Dealing with errors from the Nix side * * To handle errors that can be returned from the Nix API, * a nix_c_context can be passed to any function that potentially returns an * error. * * Error information will be stored in this context, and can be retrieved * using nix_err_code and nix_err_msg. * * Passing NULL instead will cause the API to throw C++ errors. * * Example: * @code{.c} * int main() { * nix_c_context* ctx = nix_c_context_create(); * nix_libutil_init(ctx); * if (nix_err_code(ctx) != NIX_OK) { * printf("error: %s\n", nix_err_msg(NULL, ctx, NULL)); * return 1; * } * return 0; * } * @endcode * @{ */ // Error codes /** * @brief Type for error codes in the NIX system * * This type can have one of several predefined constants: * - NIX_OK: No error occurred (0) * - NIX_ERR_UNKNOWN: An unknown error occurred (-1) * - NIX_ERR_OVERFLOW: An overflow error occurred (-2) * - NIX_ERR_KEY: A key error occurred (-3) * - NIX_ERR_NIX_ERROR: A generic Nix error occurred (-4) */ enum nix_err { /** * @brief No error occurred. * * This error code is returned when no error has occurred during the function * execution. */ NIX_OK = 0, /** * @brief An unknown error occurred. * * This error code is returned when an unknown error occurred during the * function execution. */ NIX_ERR_UNKNOWN = -1, /** * @brief An overflow error occurred. * * This error code is returned when an overflow error occurred during the * function execution. */ NIX_ERR_OVERFLOW = -2, /** * @brief A key error occurred. * * This error code is returned when a key error occurred during the function * execution. */ NIX_ERR_KEY = -3, /** * @brief A generic Nix error occurred. * * This error code is returned when a generic Nix error occurred during the * function execution. */ NIX_ERR_NIX_ERROR = -4, }; typedef enum nix_err nix_err; /** * @brief This object stores error state. * @struct nix_c_context * * Passed as a first parameter to functions that can fail, to store error * information. * * Optional wherever it can be used, passing NULL instead will throw a C++ * exception. * * The struct is laid out so that it can also be cast to nix_err* to inspect * directly: * @code{.c} * assert(*(nix_err*)ctx == NIX_OK); * @endcode * @note These can be reused between different function calls, * but make sure not to use them for multiple calls simultaneously (which can * happen in callbacks). */ typedef struct nix_c_context nix_c_context; /** * @brief Called to get the value of a string owned by Nix. * * @param[in] start the string to copy. * @param[in] n the string length. * @param[in] user_data optional, arbitrary data, passed to the nix_get_string_callback when it's called. */ typedef void (*nix_get_string_callback)(const char * start, unsigned int n, void * user_data); // Function prototypes /** * @brief Allocate a new nix_c_context. * @throws std::bad_alloc * @return allocated nix_c_context, owned by the caller. Free using * `nix_c_context_free`. */ nix_c_context * nix_c_context_create(); /** * @brief Free a nix_c_context. Does not fail. * @param[out] context The context to free, mandatory. */ void nix_c_context_free(nix_c_context * context); /** * @} */ /** * @brief Initializes nix_libutil and its dependencies. * * This function can be called multiple times, but should be called at least * once prior to any other nix function. * * @param[out] context Optional, stores error information * @return NIX_OK if the initialization is successful, or an error code * otherwise. */ nix_err nix_libutil_init(nix_c_context * context); /** @defgroup settings Nix configuration settings * @{ */ /** * @brief Retrieves a setting from the nix global configuration. * * This function requires nix_libutil_init() to be called at least once prior to * its use. * * @param[out] context optional, Stores error information * @param[in] key The key of the setting to retrieve. * @param[in] callback Called with the setting value. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @see nix_get_string_callback * @return NIX_ERR_KEY if the setting is unknown, or NIX_OK if the setting was retrieved * successfully. */ nix_err nix_setting_get(nix_c_context * context, const char * key, nix_get_string_callback callback, void * user_data); /** * @brief Sets a setting in the nix global configuration. * * Use "extra-<setting name>" to append to the setting's value. * * Settings only apply for new State%s. Call nix_plugins_init() when you are * done with the settings to load any plugins. * * @param[out] context optional, Stores error information * @param[in] key The key of the setting to set. * @param[in] value The value to set for the setting. * @return NIX_ERR_KEY if the setting is unknown, or NIX_OK if the setting was * set successfully. */ nix_err nix_setting_set(nix_c_context * context, const char * key, const char * value); /** * @} */ // todo: nix_plugins_init() /** * @brief Retrieves the nix library version. * * Does not fail. * @return A static string representing the version of the nix library. */ const char * nix_version_get(); /** @addtogroup errors * @{ */ /** * @brief Retrieves the most recent error message from a context. * * @pre This function should only be called after a previous nix function has * returned an error. * * @param[out] context optional, the context to store errors in if this function * fails * @param[in] ctx the context to retrieve the error message from * @param[out] n optional: a pointer to an unsigned int that is set to the * length of the error. * @return nullptr if no error message was ever set, * a borrowed pointer to the error message otherwise, which is valid * until the next call to a Nix function, or until the context is * destroyed. */ const char * nix_err_msg(nix_c_context * context, const nix_c_context * ctx, unsigned int * n); /** * @brief Retrieves the error message from errorInfo in a context. * * Used to inspect nix Error messages. * * @pre This function should only be called after a previous nix function has * returned a NIX_ERR_NIX_ERROR * * @param[out] context optional, the context to store errors in if this function * fails * @param[in] read_context the context to retrieve the error message from. * @param[in] callback Called with the error message. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @see nix_get_string_callback * @return NIX_OK if there were no errors, an error code otherwise. */ nix_err nix_err_info_msg( nix_c_context * context, const nix_c_context * read_context, nix_get_string_callback callback, void * user_data); /** * @brief Retrieves the error name from a context. * * Used to inspect nix Error messages. * * @pre This function should only be called after a previous nix function has * returned a NIX_ERR_NIX_ERROR * * @param context optional, the context to store errors in if this function * fails * @param[in] read_context the context to retrieve the error message from * @param[in] callback Called with the error name. * @param[in] user_data optional, arbitrary data, passed to the callback when it's called. * @see nix_get_string_callback * @return NIX_OK if there were no errors, an error code otherwise. */ nix_err nix_err_name( nix_c_context * context, const nix_c_context * read_context, nix_get_string_callback callback, void * user_data); /** * @brief Retrieves the most recent error code from a nix_c_context * * Equivalent to reading the first field of the context. * * Does not fail * * @param[in] read_context the context to retrieve the error message from * @return most recent error code stored in the context. */ nix_err nix_err_code(const nix_c_context * read_context); /** * @brief Set an error message on a nix context. * * This should be used when you want to throw an error from a PrimOp callback. * * All other use is internal to the API. * * @param context context to write the error message to, required unless C++ exceptions are supported * @param err The error code to set and return * @param msg The error message to set. This string is copied. * @returns the error code set */ nix_err nix_set_err_msg(nix_c_context * context, nix_err err, const char * msg); /** * @brief Clear the error message from a nix context. * * This is performed implicitly by all functions that accept a context, so * this won't be necessary in most cases. * However, if you want to clear the error message without calling another * function, you can use this. * * Example use case: a higher order function that helps with error handling, * to make it more robust in the following scenario: * * 1. A previous call failed, and the error was caught and handled. * 2. The context is reused with our error handling helper function. * 3. The callback passed to the helper function doesn't actually make a call to * a Nix function. * 4. The handled error is raised again, from an unrelated call. * * This failure can be avoided by clearing the error message after handling it. */ void nix_clear_err(nix_c_context * context); /** * @} */ // cffi end #ifdef __cplusplus } #endif /** @} */ #endif // NIX_API_UTIL_H
9,972
C++
.h
302
30.662252
119
0.709323
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,320
nix_api_util_internal.h
NixOS_nix/src/libutil-c/nix_api_util_internal.h
#ifndef NIX_API_UTIL_INTERNAL_H #define NIX_API_UTIL_INTERNAL_H #include <string> #include <optional> #include "error.hh" #include "nix_api_util.h" struct nix_c_context { nix_err last_err_code = NIX_OK; /** The last error message. Always check last_err_code. This may not have been cleared, so that clearing is fast. */ std::optional<std::string> last_err = {}; std::optional<nix::ErrorInfo> info = {}; std::string name = ""; }; nix_err nix_context_error(nix_c_context * context); /** * Internal use only. * * Helper to invoke nix_get_string_callback * @param context optional, the context to store errors in if this function * fails * @param str The string to observe * @param callback Called with the observed string. * @param user_data optional, arbitrary data, passed to the callback when it's called. * @return NIX_OK if there were no errors. * @see nix_get_string_callback */ nix_err call_nix_get_string_callback(const std::string str, nix_get_string_callback callback, void * user_data); #define NIXC_CATCH_ERRS \ catch (...) \ { \ return nix_context_error(context); \ } \ return NIX_OK; #define NIXC_CATCH_ERRS_RES(def) \ catch (...) \ { \ nix_context_error(context); \ return def; \ } #define NIXC_CATCH_ERRS_NULL NIXC_CATCH_ERRS_RES(nullptr) #endif // NIX_API_UTIL_INTERNAL_H
1,377
C++
.h
42
29.619048
120
0.693293
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,321
cache.hh
NixOS_nix/src/libfetchers/cache.hh
#pragma once ///@file #include "fetchers.hh" #include "path.hh" namespace nix::fetchers { /** * A cache for arbitrary `Attrs` -> `Attrs` mappings with a timestamp * for expiration. */ struct Cache { virtual ~Cache() { } /** * A domain is a partition of the key/value cache for a particular * purpose, e.g. git revision to revcount. */ using Domain = std::string_view; /** * A cache key is a domain and an arbitrary set of attributes. */ using Key = std::pair<Domain, Attrs>; /** * Add a key/value pair to the cache. */ virtual void upsert( const Key & key, const Attrs & value) = 0; /** * Look up a key with infinite TTL. */ virtual std::optional<Attrs> lookup( const Key & key) = 0; /** * Look up a key. Return nothing if its TTL has exceeded * `settings.tarballTTL`. */ virtual std::optional<Attrs> lookupWithTTL( const Key & key) = 0; struct Result { bool expired = false; Attrs value; }; /** * Look up a key. Return a bool denoting whether its TTL has * exceeded `settings.tarballTTL`. */ virtual std::optional<Result> lookupExpired( const Key & key) = 0; /** * Insert a cache entry that has a store path associated with * it. Such cache entries are always considered stale if the * associated store path is invalid. */ virtual void upsert( Key key, Store & store, Attrs value, const StorePath & storePath) = 0; struct ResultWithStorePath : Result { StorePath storePath; }; /** * Look up a store path in the cache. The returned store path will * be valid, but it may be expired. */ virtual std::optional<ResultWithStorePath> lookupStorePath( Key key, Store & store) = 0; /** * Look up a store path in the cache. Return nothing if its TTL * has exceeded `settings.tarballTTL`. */ virtual std::optional<ResultWithStorePath> lookupStorePathWithTTL( Key key, Store & store) = 0; }; ref<Cache> getCache(); }
2,179
C++
.h
80
21.5875
70
0.614498
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,322
fetchers.hh
NixOS_nix/src/libfetchers/fetchers.hh
#pragma once ///@file #include "types.hh" #include "hash.hh" #include "canon-path.hh" #include "json-impls.hh" #include "attrs.hh" #include "url.hh" #include <memory> #include <nlohmann/json_fwd.hpp> #include "ref.hh" namespace nix { class Store; class StorePath; struct SourceAccessor; } namespace nix::fetchers { struct InputScheme; struct Settings; /** * The `Input` object is generated by a specific fetcher, based on * user-supplied information, and contains * the information that the specific fetcher needs to perform the * actual fetch. The Input object is most commonly created via the * `fromURL()` or `fromAttrs()` static functions. */ struct Input { friend struct InputScheme; const Settings * settings; Input(const Settings & settings) : settings{&settings} { } std::shared_ptr<InputScheme> scheme; // note: can be null Attrs attrs; /** * path of the parent of this input, used for relative path resolution */ std::optional<Path> parent; public: /** * Create an `Input` from a URL. * * The URL indicate which sort of fetcher, and provides information to that fetcher. */ static Input fromURL( const Settings & settings, const std::string & url, bool requireTree = true); static Input fromURL( const Settings & settings, const ParsedURL & url, bool requireTree = true); /** * Create an `Input` from a an `Attrs`. * * The URL indicate which sort of fetcher, and provides information to that fetcher. */ static Input fromAttrs( const Settings & settings, Attrs && attrs); ParsedURL toURL() const; std::string toURLString(const std::map<std::string, std::string> & extraQuery = {}) const; std::string to_string() const; Attrs toAttrs() const; /** * Return whether this is a "direct" input, that is, not * one that goes through a registry. */ bool isDirect() const; /** * Return whether this is a "locked" input, that is, it has * attributes like a Git revision or NAR hash that uniquely * identify its contents. */ bool isLocked() const; /** * Return whether this is a "final" input, meaning that fetching * it will not add, remove or change any attributes. (See * `checkLocks()` for the semantics.) Only "final" inputs can be * substituted from a binary cache. * * The "final" state is denoted by the presence of an attribute * `__final = true`. This attribute is currently undocumented and * for internal use only. */ bool isFinal() const; bool operator ==(const Input & other) const noexcept; bool contains(const Input & other) const; /** * Fetch the entire input into the Nix store, returning the * location in the Nix store and the locked input. */ std::pair<StorePath, Input> fetchToStore(ref<Store> store) const; /** * Check the locking attributes in `result` against * `specified`. E.g. if `specified` has a `rev` attribute, then * `result` must have the same `rev` attribute. Throw an exception * if there is a mismatch. * * If `specified` is marked final (i.e. has the `__final` * attribute), then the intersection of attributes in `specified` * and `result` must be equal, and `final.attrs` is set to * `specified.attrs` (i.e. we discard any new attributes). */ static void checkLocks(Input specified, Input & result); /** * Return a `SourceAccessor` that allows access to files in the * input without copying it to the store. Also return a possibly * unlocked input. */ std::pair<ref<SourceAccessor>, Input> getAccessor(ref<Store> store) const; private: std::pair<ref<SourceAccessor>, Input> getAccessorUnchecked(ref<Store> store) const; public: Input applyOverrides( std::optional<std::string> ref, std::optional<Hash> rev) const; void clone(const Path & destDir) const; std::optional<Path> getSourcePath() const; /** * Write a file to this input, for input types that support * writing. Optionally commit the change (for e.g. Git inputs). */ void putFile( const CanonPath & path, std::string_view contents, std::optional<std::string> commitMsg) const; std::string getName() const; StorePath computeStorePath(Store & store) const; // Convenience functions for common attributes. std::string getType() const; std::optional<Hash> getNarHash() const; std::optional<std::string> getRef() const; std::optional<Hash> getRev() const; std::optional<uint64_t> getRevCount() const; std::optional<time_t> getLastModified() const; /** * For locked inputs, return a string that uniquely specifies the * content of the input (typically a commit hash or content hash). * * Only known-equivalent inputs should return the same fingerprint. * * This is not a stable identifier between Nix versions, but not guaranteed to change either. */ std::optional<std::string> getFingerprint(ref<Store> store) const; }; /** * The `InputScheme` represents a type of fetcher. Each fetcher * registers with nix at startup time. When processing an `Input`, * each scheme is given an opportunity to "recognize" that * input from the user-provided url or attributes * and return an `Input` object to represent the input if it is * recognized. The `Input` object contains the information the fetcher * needs to actually perform the `fetch()` when called. */ struct InputScheme { virtual ~InputScheme() { } virtual std::optional<Input> inputFromURL( const Settings & settings, const ParsedURL & url, bool requireTree) const = 0; virtual std::optional<Input> inputFromAttrs( const Settings & settings, const Attrs & attrs) const = 0; /** * What is the name of the scheme? * * The `type` attribute is used to select which input scheme is * used, and then the other fields are forwarded to that input * scheme. */ virtual std::string_view schemeName() const = 0; /** * Allowed attributes in an attribute set that is converted to an * input. * * `type` is not included from this set, because the `type` field is parsed first to choose which scheme; `type` is always required. */ virtual StringSet allowedAttrs() const = 0; virtual ParsedURL toURL(const Input & input) const; virtual Input applyOverrides( const Input & input, std::optional<std::string> ref, std::optional<Hash> rev) const; virtual void clone(const Input & input, const Path & destDir) const; virtual std::optional<Path> getSourcePath(const Input & input) const; virtual void putFile( const Input & input, const CanonPath & path, std::string_view contents, std::optional<std::string> commitMsg) const; virtual std::pair<ref<SourceAccessor>, Input> getAccessor(ref<Store> store, const Input & input) const = 0; /** * Is this `InputScheme` part of an experimental feature? */ virtual std::optional<ExperimentalFeature> experimentalFeature() const; virtual bool isDirect(const Input & input) const { return true; } virtual std::optional<std::string> getFingerprint(ref<Store> store, const Input & input) const { return std::nullopt; } virtual bool isLocked(const Input & input) const { return false; } }; void registerInputScheme(std::shared_ptr<InputScheme> && fetcher); nlohmann::json dumpRegisterInputSchemeInfo(); struct PublicKey { std::string type = "ssh-ed25519"; std::string key; auto operator <=>(const PublicKey &) const = default; }; std::string publicKeys_to_string(const std::vector<PublicKey>&); } JSON_IMPL(fetchers::PublicKey)
7,977
C++
.h
211
32.606635
111
0.682455
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,323
fetch-settings.hh
NixOS_nix/src/libfetchers/fetch-settings.hh
#pragma once ///@file #include "types.hh" #include "config.hh" #include <map> #include <limits> #include <sys/types.h> namespace nix::fetchers { struct Settings : public Config { Settings(); Setting<StringMap> accessTokens{this, {}, "access-tokens", R"( Access tokens used to access protected GitHub, GitLab, or other locations requiring token-based authentication. Access tokens are specified as a string made up of space-separated `host=token` values. The specific token used is selected by matching the `host` portion against the "host" specification of the input. The actual use of the `token` value is determined by the type of resource being accessed: * Github: the token value is the OAUTH-TOKEN string obtained as the Personal Access Token from the Github server (see https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps). * Gitlab: the token value is either the OAuth2 token or the Personal Access Token (these are different types tokens for gitlab, see https://docs.gitlab.com/12.10/ee/api/README.html#authentication). The `token` value should be `type:tokenstring` where `type` is either `OAuth2` or `PAT` to indicate which type of token is being specified. Example `~/.config/nix/nix.conf`: ``` access-tokens = github.com=23ac...b289 gitlab.mycompany.com=PAT:A123Bp_Cd..EfG gitlab.com=OAuth2:1jklw3jk ``` Example `~/code/flake.nix`: ```nix input.foo = { type = "gitlab"; host = "gitlab.mycompany.com"; owner = "mycompany"; repo = "pro"; }; ``` This example specifies three tokens, one each for accessing github.com, gitlab.mycompany.com, and gitlab.com. The `input.foo` uses the "gitlab" fetcher, which might requires specifying the token type along with the token value. )"}; Setting<bool> allowDirty{this, true, "allow-dirty", "Whether to allow dirty Git/Mercurial trees."}; Setting<bool> warnDirty{this, true, "warn-dirty", "Whether to warn about dirty Git/Mercurial trees."}; Setting<bool> trustTarballsFromGitForges{ this, true, "trust-tarballs-from-git-forges", R"( If enabled (the default), Nix will consider tarballs from GitHub and similar Git forges to be locked if a Git revision is specified, e.g. `github:NixOS/patchelf/7c2f768bf9601268a4e71c2ebe91e2011918a70f`. This requires Nix to trust that the provider will return the correct contents for the specified Git revision. If disabled, such tarballs are only considered locked if a `narHash` attribute is specified, e.g. `github:NixOS/patchelf/7c2f768bf9601268a4e71c2ebe91e2011918a70f?narHash=sha256-PPXqKY2hJng4DBVE0I4xshv/vGLUskL7jl53roB8UdU%3D`. )"}; Setting<std::string> flakeRegistry{this, "https://channels.nixos.org/flake-registry.json", "flake-registry", R"( Path or URI of the global flake registry. When empty, disables the global flake registry. )", {}, true, Xp::Flakes}; }; }
3,420
C++
.h
75
36.306667
142
0.647006
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,324
fetch-to-store.hh
NixOS_nix/src/libfetchers/fetch-to-store.hh
#pragma once #include "source-path.hh" #include "store-api.hh" #include "file-system.hh" #include "repair-flag.hh" #include "file-content-address.hh" namespace nix { enum struct FetchMode { DryRun, Copy }; /** * Copy the `path` to the Nix store. */ StorePath fetchToStore( Store & store, const SourcePath & path, FetchMode mode, std::string_view name = "source", ContentAddressMethod method = ContentAddressMethod::Raw::NixArchive, PathFilter * filter = nullptr, RepairFlag repair = NoRepair); }
531
C++
.h
20
23.8
72
0.727273
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,325
store-path-accessor.hh
NixOS_nix/src/libfetchers/store-path-accessor.hh
#pragma once #include "source-path.hh" namespace nix { class StorePath; class Store; ref<SourceAccessor> makeStorePathAccessor(ref<Store> store, const StorePath & storePath); SourcePath getUnfilteredRootPath(CanonPath path); }
233
C++
.h
8
27.375
89
0.835616
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,326
mounted-source-accessor.hh
NixOS_nix/src/libfetchers/mounted-source-accessor.hh
#pragma once #include "source-accessor.hh" namespace nix { ref<SourceAccessor> makeMountedSourceAccessor(std::map<CanonPath, ref<SourceAccessor>> mounts); }
161
C++
.h
5
30.4
95
0.822368
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,327
filtering-source-accessor.hh
NixOS_nix/src/libfetchers/filtering-source-accessor.hh
#pragma once #include "source-path.hh" namespace nix { /** * A function that returns an exception of type * `RestrictedPathError` explaining that access to `path` is * forbidden. */ typedef std::function<RestrictedPathError(const CanonPath & path)> MakeNotAllowedError; /** * An abstract wrapping `SourceAccessor` that performs access * control. Subclasses should override `isAllowed()` to implement an * access control policy. The error message is customized at construction. */ struct FilteringSourceAccessor : SourceAccessor { ref<SourceAccessor> next; CanonPath prefix; MakeNotAllowedError makeNotAllowedError; FilteringSourceAccessor(const SourcePath & src, MakeNotAllowedError && makeNotAllowedError) : next(src.accessor) , prefix(src.path) , makeNotAllowedError(std::move(makeNotAllowedError)) { displayPrefix.clear(); } std::optional<std::filesystem::path> getPhysicalPath(const CanonPath & path) override; std::string readFile(const CanonPath & path) override; bool pathExists(const CanonPath & path) override; std::optional<Stat> maybeLstat(const CanonPath & path) override; DirEntries readDirectory(const CanonPath & path) override; std::string readLink(const CanonPath & path) override; std::string showPath(const CanonPath & path) override; /** * Call `makeNotAllowedError` to throw a `RestrictedPathError` * exception if `isAllowed()` returns `false` for `path`. */ void checkAccess(const CanonPath & path); /** * Return `true` iff access to path is allowed. */ virtual bool isAllowed(const CanonPath & path) = 0; }; /** * A wrapping `SourceAccessor` that checks paths against a set of * allowed prefixes. */ struct AllowListSourceAccessor : public FilteringSourceAccessor { /** * Grant access to the specified prefix. */ virtual void allowPrefix(CanonPath prefix) = 0; static ref<AllowListSourceAccessor> create( ref<SourceAccessor> next, std::set<CanonPath> && allowedPrefixes, MakeNotAllowedError && makeNotAllowedError); using FilteringSourceAccessor::FilteringSourceAccessor; }; /** * A wrapping `SourceAccessor` mix-in where `isAllowed()` caches the result of virtual `isAllowedUncached()`. */ struct CachingFilteringSourceAccessor : FilteringSourceAccessor { std::map<CanonPath, bool> cache; using FilteringSourceAccessor::FilteringSourceAccessor; bool isAllowed(const CanonPath & path) override; virtual bool isAllowedUncached(const CanonPath & path) = 0; }; }
2,609
C++
.h
70
33.042857
109
0.740961
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,328
attrs.hh
NixOS_nix/src/libfetchers/attrs.hh
#pragma once ///@file #include "types.hh" #include "hash.hh" #include <variant> #include <nlohmann/json_fwd.hpp> #include <optional> namespace nix::fetchers { typedef std::variant<std::string, uint64_t, Explicit<bool>> Attr; /** * An `Attrs` can be thought of a JSON object restricted or simplified * to be "flat", not containing any subcontainers (arrays or objects) * and also not containing any `null`s. */ typedef std::map<std::string, Attr> Attrs; Attrs jsonToAttrs(const nlohmann::json & json); nlohmann::json attrsToJSON(const Attrs & attrs); std::optional<std::string> maybeGetStrAttr(const Attrs & attrs, const std::string & name); std::string getStrAttr(const Attrs & attrs, const std::string & name); std::optional<uint64_t> maybeGetIntAttr(const Attrs & attrs, const std::string & name); uint64_t getIntAttr(const Attrs & attrs, const std::string & name); std::optional<bool> maybeGetBoolAttr(const Attrs & attrs, const std::string & name); bool getBoolAttr(const Attrs & attrs, const std::string & name); std::map<std::string, std::string> attrsToQuery(const Attrs & attrs); Hash getRevAttr(const Attrs & attrs, const std::string & name); }
1,176
C++
.h
26
43.384615
90
0.750883
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
11,329
git-utils.hh
NixOS_nix/src/libfetchers/git-utils.hh
#pragma once #include "filtering-source-accessor.hh" #include "fs-sink.hh" namespace nix { namespace fetchers { struct PublicKey; } /** * A sink that writes into a Git repository. Note that nothing may be written * until `flush()` is called. */ struct GitFileSystemObjectSink : ExtendedFileSystemObjectSink { /** * Flush builder and return a final Git hash. */ virtual Hash flush() = 0; }; struct GitRepo { virtual ~GitRepo() { } static ref<GitRepo> openRepo(const std::filesystem::path & path, bool create = false, bool bare = false); virtual uint64_t getRevCount(const Hash & rev) = 0; virtual uint64_t getLastModified(const Hash & rev) = 0; virtual bool isShallow() = 0; /* Return the commit hash to which a ref points. */ virtual Hash resolveRef(std::string ref) = 0; virtual void setRemote(const std::string & name, const std::string & url) = 0; /** * Info about a submodule. */ struct Submodule { CanonPath path; std::string url; std::string branch; }; struct WorkdirInfo { bool isDirty = false; /* The checked out commit, or nullopt if there are no commits in the repo yet. */ std::optional<Hash> headRev; /* All files in the working directory that are unchanged, modified or added, but excluding deleted files. */ std::set<CanonPath> files; /* The submodules listed in .gitmodules of this workdir. */ std::vector<Submodule> submodules; }; virtual WorkdirInfo getWorkdirInfo() = 0; /* Get the ref that HEAD points to. */ virtual std::optional<std::string> getWorkdirRef() = 0; /** * Return the submodules of this repo at the indicated revision, * along with the revision of each submodule. */ virtual std::vector<std::tuple<Submodule, Hash>> getSubmodules(const Hash & rev, bool exportIgnore) = 0; virtual std::string resolveSubmoduleUrl(const std::string & url) = 0; virtual bool hasObject(const Hash & oid) = 0; virtual ref<SourceAccessor> getAccessor(const Hash & rev, bool exportIgnore) = 0; virtual ref<SourceAccessor> getAccessor(const WorkdirInfo & wd, bool exportIgnore, MakeNotAllowedError makeNotAllowedError) = 0; virtual ref<GitFileSystemObjectSink> getFileSystemObjectSink() = 0; virtual void flush() = 0; virtual void fetch( const std::string & url, const std::string & refspec, bool shallow) = 0; /** * Verify that commit `rev` is signed by one of the keys in * `publicKeys`. Throw an error if it isn't. */ virtual void verifyCommit( const Hash & rev, const std::vector<fetchers::PublicKey> & publicKeys) = 0; /** * Given a Git tree hash, compute the hash of its NAR * serialisation. This is memoised on-disk. */ virtual Hash treeHashToNarHash(const Hash & treeHash) = 0; /** * If the specified Git object is a directory with a single entry * that is a directory, return the ID of that object. * Otherwise, return the passed ID unchanged. */ virtual Hash dereferenceSingletonDirectory(const Hash & oid) = 0; }; ref<GitRepo> getTarballCache(); }
3,272
C++
.h
87
31.954023
132
0.670894
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,330
registry.hh
NixOS_nix/src/libfetchers/registry.hh
#pragma once ///@file #include "types.hh" #include "fetchers.hh" namespace nix { class Store; } namespace nix::fetchers { struct Registry { const Settings & settings; enum RegistryType { Flag = 0, User = 1, System = 2, Global = 3, Custom = 4, }; RegistryType type; struct Entry { Input from, to; Attrs extraAttrs; bool exact = false; }; std::vector<Entry> entries; Registry(const Settings & settings, RegistryType type) : settings{settings} , type{type} { } static std::shared_ptr<Registry> read( const Settings & settings, const Path & path, RegistryType type); void write(const Path & path); void add( const Input & from, const Input & to, const Attrs & extraAttrs); void remove(const Input & input); }; typedef std::vector<std::shared_ptr<Registry>> Registries; std::shared_ptr<Registry> getUserRegistry(const Settings & settings); std::shared_ptr<Registry> getCustomRegistry(const Settings & settings, const Path & p); Path getUserRegistryPath(); Registries getRegistries(const Settings & settings, ref<Store> store); void overrideRegistry( const Input & from, const Input & to, const Attrs & extraAttrs); std::pair<Input, Attrs> lookupInRegistries( ref<Store> store, const Input & input); }
1,413
C++
.h
51
22.45098
87
0.659955
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,331
tarball.hh
NixOS_nix/src/libfetchers/tarball.hh
#pragma once #include <optional> #include "hash.hh" #include "path.hh" #include "ref.hh" #include "types.hh" namespace nix { class Store; struct SourceAccessor; } namespace nix::fetchers { struct Settings; struct DownloadFileResult { StorePath storePath; std::string etag; std::string effectiveUrl; std::optional<std::string> immutableUrl; }; DownloadFileResult downloadFile( ref<Store> store, const std::string & url, const std::string & name, const Headers & headers = {}); struct DownloadTarballResult { Hash treeHash; time_t lastModified; std::optional<std::string> immutableUrl; ref<SourceAccessor> accessor; }; /** * Download and import a tarball into the Git cache. The result is the * Git tree hash of the root directory. */ ref<SourceAccessor> downloadTarball( ref<Store> store, const Settings & settings, const std::string & url); }
916
C++
.h
40
20.075
70
0.735566
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,354
mindmapeditorconfig.cpp
vnotex_vnote/src/core/mindmapeditorconfig.cpp
#include "mindmapeditorconfig.h" #include "mainconfig.h" #define READSTR(key) readString(appObj, userObj, (key)) #define READBOOL(key) readBool(appObj, userObj, (key)) #define READINT(key) readInt(appObj, userObj, (key)) using namespace vnotex; MindMapEditorConfig::MindMapEditorConfig(ConfigMgr *p_mgr, IConfig *p_topConfig) : IConfig(p_mgr, p_topConfig) { m_sessionName = QStringLiteral("mindmap_editor"); } void MindMapEditorConfig::init(const QJsonObject &p_app, const QJsonObject &p_user) { const auto appObj = p_app.value(m_sessionName).toObject(); const auto userObj = p_user.value(m_sessionName).toObject(); loadEditorResource(appObj, userObj); } QJsonObject MindMapEditorConfig::toJson() const { QJsonObject obj; obj[QStringLiteral("editor_resource")] = saveEditorResource(); return obj; } void MindMapEditorConfig::loadEditorResource(const QJsonObject &p_app, const QJsonObject &p_user) { const QString name(QStringLiteral("editor_resource")); if (MainConfig::isVersionChanged()) { bool needOverride = p_app[QStringLiteral("override_editor_resource")].toBool(); if (needOverride) { qInfo() << "override \"editor_resource\" in user configuration due to version change"; m_editorResource.init(p_app[name].toObject()); return; } } if (p_user.contains(name)) { m_editorResource.init(p_user[name].toObject()); } else { m_editorResource.init(p_app[name].toObject()); } } QJsonObject MindMapEditorConfig::saveEditorResource() const { return m_editorResource.toJson(); } const WebResource &MindMapEditorConfig::getEditorResource() const { return m_editorResource; }
1,751
C++
.cpp
49
31
98
0.712426
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,360
pdfviewerconfig.cpp
vnotex_vnote/src/core/pdfviewerconfig.cpp
#include "pdfviewerconfig.h" #include "mainconfig.h" #define READSTR(key) readString(appObj, userObj, (key)) #define READBOOL(key) readBool(appObj, userObj, (key)) #define READINT(key) readInt(appObj, userObj, (key)) using namespace vnotex; PdfViewerConfig::PdfViewerConfig(ConfigMgr *p_mgr, IConfig *p_topConfig) : IConfig(p_mgr, p_topConfig) { m_sessionName = QStringLiteral("pdf_viewer"); } void PdfViewerConfig::init(const QJsonObject &p_app, const QJsonObject &p_user) { const auto appObj = p_app.value(m_sessionName).toObject(); const auto userObj = p_user.value(m_sessionName).toObject(); loadViewerResource(appObj, userObj); } QJsonObject PdfViewerConfig::toJson() const { QJsonObject obj; obj[QStringLiteral("viewer_resource")] = saveViewerResource(); return obj; } void PdfViewerConfig::loadViewerResource(const QJsonObject &p_app, const QJsonObject &p_user) { const QString name(QStringLiteral("viewer_resource")); if (MainConfig::isVersionChanged()) { bool needOverride = p_app[QStringLiteral("override_viewer_resource")].toBool(); if (needOverride) { qInfo() << "override \"viewer_resource\" in user configuration due to version change"; m_viewerResource.init(p_app[name].toObject()); return; } } if (p_user.contains(name)) { m_viewerResource.init(p_user[name].toObject()); } else { m_viewerResource.init(p_app[name].toObject()); } } QJsonObject PdfViewerConfig::saveViewerResource() const { return m_viewerResource.toJson(); } const WebResource &PdfViewerConfig::getViewerResource() const { return m_viewerResource; }
1,711
C++
.cpp
49
30.265306
98
0.707879
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,387
pdfbufferfactory.cpp
vnotex_vnote/src/core/buffer/pdfbufferfactory.cpp
#include "pdfbufferfactory.h" #include "pdfbuffer.h" #include "urlbasedbufferprovider.h" using namespace vnotex; Buffer *PdfBufferFactory::createBuffer(const BufferParameters &p_parameters, QObject *p_parent) { BufferParameters paras; paras.m_provider = QSharedPointer<UrlBasedBufferProvider>::create(p_parameters.m_provider); return new PdfBuffer(paras, p_parent); } bool PdfBufferFactory::isBufferCreatedByFactory(const Buffer *p_buffer) const { return dynamic_cast<const PdfBuffer *>(p_buffer) != nullptr; }
571
C++
.cpp
15
33.066667
95
0.742754
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,452
pdfviewwindow.cpp
vnotex_vnote/src/widgets/pdfviewwindow.cpp
#include "pdfviewwindow.h" #include <core/vnotex.h> #include <core/thememgr.h> #include <core/htmltemplatehelper.h> #include <core/configmgr.h> #include <core/editorconfig.h> #include <core/pdfviewerconfig.h> #include <utils/pathutils.h> #include "editors/pdfviewer.h" #include "editors/pdfvieweradapter.h" using namespace vnotex; PdfViewWindow::PdfViewWindow(QWidget *p_parent) : ViewWindow(p_parent) { m_mode = ViewWindowMode::Read; setupUI(); } void PdfViewWindow::setupUI() { setupViewer(); setCentralWidget(m_viewer); setupToolBar(); } void PdfViewWindow::setupToolBar() { auto toolBar = createToolBar(this); addToolBar(toolBar); addAction(toolBar, ViewWindowToolBarHelper::Tag); } void PdfViewWindow::setupViewer() { Q_ASSERT(!m_viewer); const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); const auto &pdfViewerConfig = editorConfig.getPdfViewerConfig(); updateConfigRevision(); HtmlTemplateHelper::updatePdfViewerTemplate(pdfViewerConfig); auto adapter = new PdfViewerAdapter(nullptr); m_viewer = new PdfViewer(adapter, VNoteX::getInst().getThemeMgr().getBaseBackground(), 1.0, this); } QString PdfViewWindow::getLatestContent() const { return NULL; } QString PdfViewWindow::selectedText() const { return QString(); } void PdfViewWindow::setMode(ViewWindowMode p_mode) { Q_UNUSED(p_mode); Q_ASSERT(false); } void PdfViewWindow::openTwice(const QSharedPointer<FileOpenParameters> &p_paras) { Q_UNUSED(p_paras); } ViewWindowSession PdfViewWindow::saveSession() const { auto session = ViewWindow::saveSession(); return session; } void PdfViewWindow::applySnippet(const QString &p_name) { Q_UNUSED(p_name); } void PdfViewWindow::applySnippet() { } void PdfViewWindow::fetchWordCountInfo(const std::function<void(const WordCountInfo &)> &p_callback) const { Q_UNUSED(p_callback); } void PdfViewWindow::handleEditorConfigChange() { if (updateConfigRevision()) { const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); const auto &pdfViewerConfig = editorConfig.getPdfViewerConfig(); HtmlTemplateHelper::updatePdfViewerTemplate(pdfViewerConfig); } } void PdfViewWindow::setModified(bool p_modified) { Q_UNUSED(p_modified); } void PdfViewWindow::print() { } void PdfViewWindow::syncEditorFromBuffer() { auto buffer = getBuffer(); if (buffer) { const auto url = PathUtils::pathToUrl(buffer->getContentPath()); // Solution to ASCII problems, like these file names with these symbols # + &. const auto urlStr = QUrl::toPercentEncoding(url.toString(QUrl::FullyDecoded)); auto templateUrl = PathUtils::pathToUrl(HtmlTemplateHelper::getPdfViewerTemplatePath()); templateUrl.setQuery("file=" + urlStr); m_viewer->setHtml(HtmlTemplateHelper::getPdfViewerTemplate(), templateUrl); } else { m_viewer->setHtml(""); } } void PdfViewWindow::syncEditorFromBufferContent() { } void PdfViewWindow::scrollUp() { } void PdfViewWindow::scrollDown() { } void PdfViewWindow::zoom(bool p_zoomIn) { Q_UNUSED(p_zoomIn); } PdfViewerAdapter *PdfViewWindow::adapter() const { if (m_viewer) { return dynamic_cast<PdfViewerAdapter *>(m_viewer->adapter()); } return nullptr; } bool PdfViewWindow::updateConfigRevision() { bool changed = false; const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); if (m_editorConfigRevision != editorConfig.revision()) { changed = true; m_editorConfigRevision = editorConfig.revision(); } if (m_viewerConfigRevision != editorConfig.getPdfViewerConfig().revision()) { changed = true; m_viewerConfigRevision = editorConfig.getPdfViewerConfig().revision(); } return changed; }
3,932
C++
.cpp
138
24.478261
106
0.722651
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,471
mindmapviewwindow.cpp
vnotex_vnote/src/widgets/mindmapviewwindow.cpp
#include "mindmapviewwindow.h" #include <QToolBar> #include <QSplitter> #include <core/vnotex.h> #include <core/thememgr.h> #include <core/htmltemplatehelper.h> #include <core/configmgr.h> #include <core/editorconfig.h> #include <core/mindmapeditorconfig.h> #include <utils/utils.h> #include <utils/pathutils.h> #include "toolbarhelper.h" #include "findandreplacewidget.h" #include "editors/mindmapeditor.h" #include "editors/mindmapeditoradapter.h" using namespace vnotex; MindMapViewWindow::MindMapViewWindow(QWidget *p_parent) : ViewWindow(p_parent) { m_mode = ViewWindowMode::Edit; setupUI(); } void MindMapViewWindow::setupUI() { setupEditor(); setCentralWidget(m_editor); setupToolBar(); } void MindMapViewWindow::setupEditor() { Q_ASSERT(!m_editor); const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); const auto &mindMapEditorConfig = editorConfig.getMindMapEditorConfig(); updateConfigRevision(); HtmlTemplateHelper::updateMindMapEditorTemplate(mindMapEditorConfig); auto adapter = new MindMapEditorAdapter(nullptr); m_editor = new MindMapEditor(adapter, VNoteX::getInst().getThemeMgr().getBaseBackground(), 1.0, this); connect(m_editor, &MindMapEditor::contentsChanged, this, [this]() { getBuffer()->setModified(m_editor->isModified()); getBuffer()->invalidateContent( this, [this](int p_revision) { this->setBufferRevisionAfterInvalidation(p_revision); }); }); } QString MindMapViewWindow::getLatestContent() const { QString content; adapter()->saveData([&content](const QString &p_data) { content = p_data; }); while (content.isNull()) { Utils::sleepWait(50); } return content; } QString MindMapViewWindow::selectedText() const { return m_editor->selectedText(); } void MindMapViewWindow::setMode(ViewWindowMode p_mode) { Q_UNUSED(p_mode); Q_ASSERT(false); } void MindMapViewWindow::openTwice(const QSharedPointer<FileOpenParameters> &p_paras) { Q_UNUSED(p_paras); } ViewWindowSession MindMapViewWindow::saveSession() const { auto session = ViewWindow::saveSession(); return session; } void MindMapViewWindow::applySnippet(const QString &p_name) { Q_UNUSED(p_name); } void MindMapViewWindow::applySnippet() { } void MindMapViewWindow::fetchWordCountInfo(const std::function<void(const WordCountInfo &)> &p_callback) const { Q_UNUSED(p_callback); } void MindMapViewWindow::handleEditorConfigChange() { if (updateConfigRevision()) { const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); const auto &mindMapEditorConfig = editorConfig.getMindMapEditorConfig(); HtmlTemplateHelper::updateMindMapEditorTemplate(mindMapEditorConfig); } } void MindMapViewWindow::setModified(bool p_modified) { m_editor->setModified(p_modified); } void MindMapViewWindow::print() { } void MindMapViewWindow::syncEditorFromBuffer() { auto buffer = getBuffer(); if (buffer) { m_editor->setHtml(HtmlTemplateHelper::getMindMapEditorTemplate(), PathUtils::pathToUrl(buffer->getContentPath())); adapter()->setData(buffer->getContent()); m_editor->setModified(buffer->isModified()); } else { m_editor->setHtml(""); adapter()->setData(""); m_editor->setModified(false); } m_bufferRevision = buffer ? buffer->getRevision() : 0; } void MindMapViewWindow::syncEditorFromBufferContent() { auto buffer = getBuffer(); Q_ASSERT(buffer); adapter()->setData(buffer->getContent()); m_editor->setModified(buffer->isModified()); m_bufferRevision = buffer->getRevision(); } void MindMapViewWindow::scrollUp() { } void MindMapViewWindow::scrollDown() { } void MindMapViewWindow::zoom(bool p_zoomIn) { Q_UNUSED(p_zoomIn); } MindMapEditorAdapter *MindMapViewWindow::adapter() const { if (m_editor) { return dynamic_cast<MindMapEditorAdapter *>(m_editor->adapter()); } return nullptr; } bool MindMapViewWindow::updateConfigRevision() { bool changed = false; const auto &editorConfig = ConfigMgr::getInst().getEditorConfig(); if (m_editorConfigRevision != editorConfig.revision()) { changed = true; m_editorConfigRevision = editorConfig.revision(); } if (m_editorConfigRevision != editorConfig.getMindMapEditorConfig().revision()) { changed = true; m_editorConfigRevision = editorConfig.getMindMapEditorConfig().revision(); } return changed; } void MindMapViewWindow::setupToolBar() { auto toolBar = createToolBar(this); addToolBar(toolBar); addAction(toolBar, ViewWindowToolBarHelper::Save); toolBar->addSeparator(); addAction(toolBar, ViewWindowToolBarHelper::Attachment); addAction(toolBar, ViewWindowToolBarHelper::Tag); ToolBarHelper::addSpacer(toolBar); addAction(toolBar, ViewWindowToolBarHelper::FindAndReplace); addAction(toolBar, ViewWindowToolBarHelper::Debug); } void MindMapViewWindow::toggleDebug() { if (m_debugViewer) { bool shouldEnable = !m_debugViewer->isVisible(); m_debugViewer->setVisible(shouldEnable); m_editor->page()->setDevToolsPage(shouldEnable ? m_debugViewer->page() : nullptr); } else { setupDebugViewer(); m_editor->page()->setDevToolsPage(m_debugViewer->page()); } } void MindMapViewWindow::setupDebugViewer() { Q_ASSERT(!m_debugViewer); // Need a vertical QSplitter to hold the original QSplitter and the debug viewer. auto mainSplitter = new QSplitter(this); mainSplitter->setContentsMargins(0, 0, 0, 0); mainSplitter->setOrientation(Qt::Vertical); replaceCentralWidget(mainSplitter); mainSplitter->addWidget(m_editor); mainSplitter->setFocusProxy(m_editor); m_debugViewer = new WebViewer(VNoteX::getInst().getThemeMgr().getBaseBackground(), this); m_debugViewer->resize(m_editor->width(), m_editor->height() / 2); mainSplitter->addWidget(m_debugViewer); } void MindMapViewWindow::handleFindTextChanged(const QString &p_text, FindOptions p_options) { if (p_options & FindOption::IncrementalSearch) { m_editor->findText(p_text, p_options); } } void MindMapViewWindow::handleFindNext(const QStringList &p_texts, FindOptions p_options) { // We do not use mark.js for searching as the contents are mainly SVG. m_editor->findText(p_texts.empty() ? QString() : p_texts[0], p_options); } void MindMapViewWindow::handleReplace(const QString &p_text, FindOptions p_options, const QString &p_replaceText) { Q_UNUSED(p_text); Q_UNUSED(p_options); Q_UNUSED(p_replaceText); showMessage(tr("Replace is not supported yet")); } void MindMapViewWindow::handleReplaceAll(const QString &p_text, FindOptions p_options, const QString &p_replaceText) { Q_UNUSED(p_text); Q_UNUSED(p_options); Q_UNUSED(p_replaceText); showMessage(tr("Replace is not supported yet")); } void MindMapViewWindow::handleFindAndReplaceWidgetClosed() { m_editor->findText(QString(), FindOption::FindNone); } void MindMapViewWindow::showFindAndReplaceWidget() { bool isFirstTime = !m_findAndReplace; ViewWindow::showFindAndReplaceWidget(); if (isFirstTime) { m_findAndReplace->setReplaceEnabled(false); m_findAndReplace->setOptionsEnabled(FindOption::WholeWordOnly | FindOption::RegularExpression, false); } }
7,652
C++
.cpp
233
28.133047
116
0.71481
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,473
webviewer.cpp
vnotex_vnote/src/widgets/webviewer.cpp
#include "webviewer.h" #include "webpage.h" #include <QWebEnginePage> #include <utils/utils.h> using namespace vnotex; WebViewer::WebViewer(const QColor &p_background, qreal p_zoomFactor, QWidget *p_parent) : QWebEngineView(p_parent) { setAcceptDrops(false); auto viewPage = new WebPage(this); setPage(viewPage); connect(viewPage, &QWebEnginePage::linkHovered, this, &WebViewer::linkHovered); // Avoid white flash before loading content. // Setting Qt::transparent will force GrayScale antialias rendering. if (p_background.isValid()) { viewPage->setBackgroundColor(p_background); } if (!Utils::fuzzyEqual(p_zoomFactor, 1.0)) { setZoomFactor(p_zoomFactor); } } WebViewer::WebViewer(const QColor &p_background, QWidget *p_parent) : WebViewer(p_background, 1.0, p_parent) { } WebViewer::~WebViewer() { } void WebViewer::findText(const QString &p_text, FindOptions p_options) { if (p_options & FindOption::RegularExpression) { return; } QWebEnginePage::FindFlags flags; if (p_options & FindOption::FindBackward) { flags |= QWebEnginePage::FindFlag::FindBackward; } if (p_options & FindOption::CaseSensitive) { flags |= QWebEnginePage::FindFlag::FindCaseSensitively; } QWebEngineView::findText(p_text, flags); }
1,396
C++
.cpp
45
25.844444
72
0.68736
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,499
notetemplateselector.cpp
vnotex_vnote/src/widgets/dialogs/notetemplateselector.cpp
#include "notetemplateselector.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QComboBox> #include <QPlainTextEdit> #include <QPushButton> #include <core/templatemgr.h> #include <core/exception.h> #include <utils/fileutils.h> #include <utils/widgetutils.h> #include <widgets/widgetsfactory.h> using namespace vnotex; NoteTemplateSelector::NoteTemplateSelector(QWidget *p_parent) : QWidget(p_parent) { setupUI(); } void NoteTemplateSelector::setupUI() { auto mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0, 0, 0, 0); auto selectorLayout = new QHBoxLayout(); mainLayout->addLayout(selectorLayout); setupTemplateComboBox(this); selectorLayout->addWidget(m_templateComboBox, 1); auto manageBtn = new QPushButton(tr("Manage"), this); selectorLayout->addWidget(manageBtn); connect(manageBtn, &QPushButton::clicked, this, []() { WidgetUtils::openUrlByDesktop(QUrl::fromLocalFile(TemplateMgr::getInst().getTemplateFolder())); }); m_templateTextEdit = WidgetsFactory::createPlainTextConsole(this); mainLayout->addWidget(m_templateTextEdit); m_templateTextEdit->hide(); } void NoteTemplateSelector::setupTemplateComboBox(QWidget *p_parent) { m_templateComboBox = WidgetsFactory::createComboBox(p_parent); // None. m_templateComboBox->addItem(tr("None"), ""); int idx = 1; auto templates = TemplateMgr::getInst().getTemplates(); for (const auto &temp : templates) { m_templateComboBox->addItem(temp, temp); m_templateComboBox->setItemData(idx++, temp, Qt::ToolTipRole); } m_templateComboBox->setCurrentIndex(0); connect(m_templateComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &NoteTemplateSelector::updateCurrentTemplate); } void NoteTemplateSelector::updateCurrentTemplate() { m_templateContent.clear(); m_templateTextEdit->clear(); auto templateName = m_templateComboBox->currentData().toString(); if (templateName.isEmpty()) { m_templateTextEdit->hide(); emit templateChanged(); return; } const auto filePath = TemplateMgr::getInst().getTemplateFilePath(templateName); try { m_templateContent = FileUtils::readTextFile(filePath); m_templateTextEdit->setPlainText(m_templateContent); } catch (Exception &p_e) { QString msg = tr("Failed to load template (%1) (%2).") .arg(filePath, p_e.what()); qCritical() << msg; m_templateTextEdit->setPlainText(msg); } m_templateTextEdit->show(); emit templateChanged(); } QString NoteTemplateSelector::getCurrentTemplate() const { return m_templateComboBox->currentData().toString(); } bool NoteTemplateSelector::setCurrentTemplate(const QString &p_template) { int idx = m_templateComboBox->findData(p_template); if (idx != -1) { m_templateComboBox->setCurrentIndex(idx); return true; } else { return false; } } const QString& NoteTemplateSelector::getTemplateContent() const { return m_templateContent; }
3,139
C++
.cpp
91
29.659341
111
0.713578
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,504
newnotedialog.cpp
vnotex_vnote/src/widgets/dialogs/newnotedialog.cpp
#include "newnotedialog.h" #include <QHBoxLayout> #include <QLineEdit> #include <QComboBox> #include <QFormLayout> #include <QPushButton> #include <QPlainTextEdit> #include "notebook/notebook.h" #include "notebook/node.h" #include "../widgetsfactory.h" #include <utils/pathutils.h> #include <utils/fileutils.h> #include "exception.h" #include "nodeinfowidget.h" #include "notetemplateselector.h" #include <utils/widgetutils.h> #include <core/templatemgr.h> #include <core/configmgr.h> #include <core/widgetconfig.h> #include <snippet/snippetmgr.h> #include <buffer/filetypehelper.h> using namespace vnotex; QString NewNoteDialog::s_lastTemplate; NewNoteDialog::NewNoteDialog(Node *p_node, QWidget *p_parent) : ScrollDialog(p_parent) { Q_ASSERT(p_node && p_node->isLoaded()); setupUI(p_node); initDefaultValues(p_node); m_infoWidget->getNameLineEdit()->setFocus(); } void NewNoteDialog::setupUI(const Node *p_node) { setupNodeInfoWidget(p_node, this); setCentralWidget(m_infoWidget); auto infoLayout = m_infoWidget->getMainLayout(); m_templateSelector = new NoteTemplateSelector(m_infoWidget); infoLayout->addRow(tr("Template:"), m_templateSelector); setDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); setWindowTitle(tr("New Note")); } void NewNoteDialog::setupNodeInfoWidget(const Node *p_node, QWidget *p_parent) { m_infoWidget = new NodeInfoWidget(p_node, Node::Flag::Content, p_parent); } bool NewNoteDialog::validateInputs() { bool valid = true; QString msg; valid = valid && validateNameInput(msg); setInformationText(msg, valid ? ScrollDialog::InformationLevel::Info : ScrollDialog::InformationLevel::Error); return valid; } bool NewNoteDialog::validateNameInput(QString &p_msg) { p_msg.clear(); auto name = m_infoWidget->getName(); if (name.isEmpty() || !PathUtils::isLegalFileName(name)) { p_msg = tr("Please specify a valid name for the note."); return false; } if (!m_infoWidget->getParentNode()->isLegalNameForNewChild(name)) { p_msg = tr("Name conflicts with existing or built-in note."); return false; } return true; } void NewNoteDialog::acceptedButtonClicked() { s_lastTemplate = m_templateSelector->getCurrentTemplate(); { auto fileType = FileTypeHelper::getInst().getFileTypeByName(m_infoWidget->getFileType()).m_type; ConfigMgr::getInst().getWidgetConfig().setNewNoteDefaultFileType(static_cast<int>(fileType)); } if (validateInputs()) { Notebook *notebook = const_cast<Notebook *>(m_infoWidget->getNotebook()); Node *parentNode = const_cast<Node *>(m_infoWidget->getParentNode()); QString errMsg; m_newNode = newNote(notebook, parentNode, m_infoWidget->getName(), m_templateSelector->getTemplateContent(), errMsg); if (!m_newNode) { setInformationText(errMsg, ScrollDialog::InformationLevel::Error); return; } accept(); } } QSharedPointer<Node> NewNoteDialog::newNote(Notebook *p_notebook, Node *p_parentNode, const QString &p_name, const QString &p_templateContent, QString &p_errMsg) { Q_ASSERT(p_notebook && p_parentNode); QSharedPointer<Node> newNode; p_errMsg.clear(); try { newNode = p_notebook->newNode(p_parentNode, Node::Flag::Content, p_name, evaluateTemplateContent(p_templateContent, p_name)); } catch (Exception &p_e) { p_errMsg = tr("Failed to create note under (%1) in (%2) (%3).").arg(p_parentNode->getName(), p_notebook->getName(), p_e.what()); qCritical() << p_errMsg; return nullptr; } emit p_notebook->nodeUpdated(newNode.data()); return newNode; } const QSharedPointer<Node> &NewNoteDialog::getNewNode() const { return m_newNode; } void NewNoteDialog::initDefaultValues(const Node *p_node) { { int defaultType = ConfigMgr::getInst().getWidgetConfig().getNewNoteDefaultFileType(); const auto &fileType = FileTypeHelper::getInst().getFileType(defaultType); m_infoWidget->setFileType(fileType.m_typeName); auto lineEdit = m_infoWidget->getNameLineEdit(); auto defaultName = FileUtils::generateFileNameWithSequence(p_node->fetchAbsolutePath(), tr("note"), fileType.preferredSuffix()); lineEdit->setText(defaultName); WidgetUtils::selectBaseName(lineEdit); } if (!s_lastTemplate.isEmpty()) { // Restore. if (!m_templateSelector->setCurrentTemplate(s_lastTemplate)) { s_lastTemplate.clear(); } } } QString NewNoteDialog::evaluateTemplateContent(const QString &p_content, const QString &p_name) { int cursorOffset = 0; return SnippetMgr::getInst().applySnippetBySymbol(p_content, QString(), cursorOffset, SnippetMgr::generateOverrides(p_name)); }
5,746
C++
.cpp
147
28.918367
104
0.602299
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,525
quickaccesspage.cpp
vnotex_vnote/src/widgets/dialogs/settings/quickaccesspage.cpp
#include "quickaccesspage.h" #include <QVBoxLayout> #include <QFormLayout> #include <QGroupBox> #include <QPlainTextEdit> #include <QDebug> #include <QFileDialog> #include <QCheckBox> #include <QPushButton> #include <QComboBox> #include <QLineEdit> #include <QInputDialog> #include <core/sessionconfig.h> #include <core/coreconfig.h> #include <core/configmgr.h> #include <core/notebookmgr.h> #include <core/vnotex.h> #include <utils/widgetutils.h> #include <widgets/locationinputwithbrowsebutton.h> #include <widgets/lineeditwithsnippet.h> #include <widgets/widgetsfactory.h> #include <widgets/messageboxhelper.h> #include "../notetemplateselector.h" using namespace vnotex; QuickAccessPage::QuickAccessPage(QWidget *p_parent) : SettingsPage(p_parent) { setupUI(); } void QuickAccessPage::setupUI() { auto mainLayout = new QVBoxLayout(this); auto flashPageBox = setupFlashPageGroup(); mainLayout->addWidget(flashPageBox); auto quickAccessBox = setupQuickAccessGroup(); mainLayout->addWidget(quickAccessBox); auto quickNoteBox = setupQuickNoteGroup(); mainLayout->addWidget(quickNoteBox); mainLayout->addStretch(); } void QuickAccessPage::loadInternal() { const auto &sessionConfig = ConfigMgr::getInst().getSessionConfig(); m_flashPageInput->setText(sessionConfig.getFlashPage()); { const auto &quickAccess = sessionConfig.getQuickAccessFiles(); if (!quickAccess.isEmpty()) { m_quickAccessTextEdit->setPlainText(quickAccess.join(QChar('\n'))); } } loadQuickNoteSchemes(); } void QuickAccessPage::loadQuickNoteSchemes() { const auto &sessionConfig = ConfigMgr::getInst().getSessionConfig(); m_quickNoteSchemes = sessionConfig.getQuickNoteSchemes(); m_quickNoteCurrentIndex = -1; m_quickNoteSchemeComboBox->clear(); for (const auto &scheme : m_quickNoteSchemes) { m_quickNoteSchemeComboBox->addItem(scheme.m_name); } if (m_quickNoteSchemeComboBox->count() > 0) { m_quickNoteSchemeComboBox->setCurrentIndex(0); // Manually call the handler. setCurrentQuickNote(0); } } bool QuickAccessPage::saveInternal() { auto &sessionConfig = ConfigMgr::getInst().getSessionConfig(); sessionConfig.setFlashPage(m_flashPageInput->text()); { auto text = m_quickAccessTextEdit->toPlainText(); if (!text.isEmpty()) { sessionConfig.setQuickAccessFiles(text.split(QChar('\n'))); } } saveQuickNoteSchemes(); return true; } void QuickAccessPage::saveQuickNoteSchemes() { // Save current quick note scheme from inputs. saveCurrentQuickNote(); auto &sessionConfig = ConfigMgr::getInst().getSessionConfig(); sessionConfig.setQuickNoteSchemes(m_quickNoteSchemes); } QString QuickAccessPage::title() const { return tr("Quick Access"); } QGroupBox *QuickAccessPage::setupFlashPageGroup() { auto box = new QGroupBox(tr("Flash Page"), this); auto layout = WidgetsFactory::createFormLayout(box); { m_flashPageInput = new LocationInputWithBrowseButton(box); m_flashPageInput->setToolTip(tr("Flash Page location (user could copy the path of one note and paste it here)")); const QString label(tr("Flash Page:")); layout->addRow(label, m_flashPageInput); addSearchItem(label, m_flashPageInput->toolTip(), m_flashPageInput); connect(m_flashPageInput, &LocationInputWithBrowseButton::textChanged, this, &QuickAccessPage::pageIsChanged); connect(m_flashPageInput, &LocationInputWithBrowseButton::clicked, this, [this]() { auto filePath = QFileDialog::getOpenFileName(this, tr("Select Flash Page File"), QDir::homePath()); if (!filePath.isEmpty()) { m_flashPageInput->setText(filePath); } }); } return box; } QGroupBox *QuickAccessPage::setupQuickAccessGroup() { auto box = new QGroupBox(tr("Quick Access"), this); auto layout = WidgetsFactory::createFormLayout(box); { m_quickAccessTextEdit = WidgetsFactory::createPlainTextEdit(box); m_quickAccessTextEdit->setToolTip(tr("Edit the files pinned to Quick Access (one file per line)")); m_quickAccessTextEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); const QString label(tr("Quick Access:")); layout->addRow(label, m_quickAccessTextEdit); addSearchItem(label, m_quickAccessTextEdit->toolTip(), m_quickAccessTextEdit); connect(m_quickAccessTextEdit, &QPlainTextEdit::textChanged, this, &QuickAccessPage::pageIsChanged); } return box; } QString QuickAccessPage::getDefaultQuickNoteFolderPath() { auto defaultPath = QDir::homePath(); auto currentNotebook = VNoteX::getInst().getNotebookMgr().getCurrentNotebook(); if (currentNotebook) { defaultPath = currentNotebook->getRootFolderAbsolutePath(); } return defaultPath; } QGroupBox *QuickAccessPage::setupQuickNoteGroup() { auto box = new QGroupBox(tr("Quick Note"), this); auto mainLayout = WidgetsFactory::createFormLayout(box); { auto selectorLayout = new QHBoxLayout(); // Add items in loadInternal(). m_quickNoteSchemeComboBox = WidgetsFactory::createComboBox(box); selectorLayout->addWidget(m_quickNoteSchemeComboBox, 1); m_quickNoteSchemeComboBox->setPlaceholderText(tr("No scheme to show")); auto newBtn = new QPushButton(tr("New"), box); connect(newBtn, &QPushButton::clicked, this, &QuickAccessPage::newQuickNoteScheme); selectorLayout->addWidget(newBtn); auto deleteBtn = new QPushButton(tr("Delete"), box); deleteBtn->setEnabled(false); connect(deleteBtn, &QPushButton::clicked, this, &QuickAccessPage::removeQuickNoteScheme); selectorLayout->addWidget(deleteBtn); const QString label(tr("Scheme:")); mainLayout->addRow(label, selectorLayout); addSearchItem(label, m_quickNoteSchemeComboBox); connect(m_quickNoteSchemeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &QuickAccessPage::pageIsChanged); connect(m_quickNoteSchemeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [deleteBtn](int idx) { deleteBtn->setEnabled(idx > -1); }); } m_quickNoteInfoGroupBox = new QGroupBox(box); mainLayout->addRow(m_quickNoteInfoGroupBox); auto infoLayout = WidgetsFactory::createFormLayout(m_quickNoteInfoGroupBox); { const QString label(tr("Folder:")); m_quickNoteFolderPathInput = new LocationInputWithBrowseButton(m_quickNoteInfoGroupBox); m_quickNoteFolderPathInput->setPlaceholderText(tr("Empty to use current explored folder dynamically")); infoLayout->addRow(label, m_quickNoteFolderPathInput); addSearchItem(label, m_quickNoteFolderPathInput); connect(m_quickNoteFolderPathInput, &LocationInputWithBrowseButton::textChanged, this, &QuickAccessPage::pageIsChanged); connect(m_quickNoteFolderPathInput, &LocationInputWithBrowseButton::clicked, this, [this]() { auto folderPath = QFileDialog::getExistingDirectory(this, tr("Select Quick Note Folder"), getDefaultQuickNoteFolderPath()); if (!folderPath.isEmpty()) { m_quickNoteFolderPathInput->setText(folderPath); } }); } { const QString label(tr("Note name:")); m_quickNoteNoteNameLineEdit = WidgetsFactory::createLineEditWithSnippet(m_quickNoteInfoGroupBox); infoLayout->addRow(label, m_quickNoteNoteNameLineEdit); connect(m_quickNoteNoteNameLineEdit, &QLineEdit::textChanged, this, &QuickAccessPage::pageIsChanged); } { const QString label(tr("Note template:")); m_quickNoteTemplateSelector = new NoteTemplateSelector(m_quickNoteInfoGroupBox); infoLayout->addRow(label, m_quickNoteTemplateSelector); connect(m_quickNoteTemplateSelector, &NoteTemplateSelector::templateChanged, this, &QuickAccessPage::pageIsChanged); } m_quickNoteInfoGroupBox->setVisible(false); connect(m_quickNoteSchemeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int idx) { if (isLoading()) { return; } setCurrentQuickNote(idx); }); return box; } void QuickAccessPage::newQuickNoteScheme() { bool isDuplicated = false; QString schemeName; do { schemeName = QInputDialog::getText(this, tr("Quick Note Scheme"), isDuplicated ? tr("Scheme name already exists! Try again:") : tr("Scheme name:")); if (schemeName.isEmpty()) { return; } isDuplicated = m_quickNoteSchemeComboBox->findText(schemeName) != -1; } while (isDuplicated); SessionConfig::QuickNoteScheme scheme; scheme.m_name = schemeName; scheme.m_folderPath = getDefaultQuickNoteFolderPath(); scheme.m_noteName = tr("quick_note_%da%.md"); m_quickNoteSchemes.push_back(scheme); m_quickNoteSchemeComboBox->addItem(schemeName); m_quickNoteSchemeComboBox->setCurrentText(schemeName); emit pageIsChanged(); } void QuickAccessPage::removeQuickNoteScheme() { int idx = m_quickNoteSchemeComboBox->currentIndex(); Q_ASSERT(idx > -1); auto& scheme = m_quickNoteSchemes[idx]; int ret = MessageBoxHelper::questionOkCancel(MessageBoxHelper::Type::Question, tr("Delete quick note scheme (%1)?").arg(scheme.m_name)); if (ret != QMessageBox::Ok) { return; } m_quickNoteCurrentIndex = -1; m_quickNoteSchemes.removeAt(idx); m_quickNoteSchemeComboBox->removeItem(idx); emit pageIsChanged(); } void QuickAccessPage::saveCurrentQuickNote() { if (m_quickNoteCurrentIndex < 0) { return; } Q_ASSERT(m_quickNoteCurrentIndex < m_quickNoteSchemes.size()); auto& scheme = m_quickNoteSchemes[m_quickNoteCurrentIndex]; scheme.m_folderPath = m_quickNoteFolderPathInput->text(); // No need to apply the snippet for now. scheme.m_noteName = m_quickNoteNoteNameLineEdit->text(); scheme.m_template = m_quickNoteTemplateSelector->getCurrentTemplate(); } void QuickAccessPage::loadCurrentQuickNote() { if (m_quickNoteCurrentIndex < 0) { m_quickNoteFolderPathInput->setText(QString()); m_quickNoteNoteNameLineEdit->setText(QString()); m_quickNoteTemplateSelector->setCurrentTemplate(QString()); return; } Q_ASSERT(m_quickNoteCurrentIndex < m_quickNoteSchemes.size()); const auto& scheme = m_quickNoteSchemes[m_quickNoteCurrentIndex]; m_quickNoteFolderPathInput->setText(scheme.m_folderPath); m_quickNoteNoteNameLineEdit->setText(scheme.m_noteName); m_quickNoteTemplateSelector->setCurrentTemplate(scheme.m_template); } void QuickAccessPage::setCurrentQuickNote(int idx) { saveCurrentQuickNote(); m_quickNoteCurrentIndex = idx; loadCurrentQuickNote(); m_quickNoteInfoGroupBox->setVisible(idx > -1); }
11,688
C++
.cpp
283
33.597173
121
0.681325
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,538
mindmapeditoradapter.cpp
vnotex_vnote/src/widgets/editors/mindmapeditoradapter.cpp
#include "mindmapeditoradapter.h" using namespace vnotex; MindMapEditorAdapter::MindMapEditorAdapter(QObject *p_parent) : WebViewAdapter(p_parent) { } void MindMapEditorAdapter::setData(const QString &p_data) { if (isReady()) { emit dataUpdated(p_data); } else { pendAction(std::bind(&MindMapEditorAdapter::setData, this, p_data)); } } void MindMapEditorAdapter::saveData(const std::function<void(const QString &)> &p_callback) { if (isReady()) { const quint64 id = addCallback([p_callback](void *data) { p_callback(*reinterpret_cast<const QString *>(data)); }); emit saveDataRequested(id); } else { pendAction(std::bind(&MindMapEditorAdapter::saveData, this, p_callback)); } } void MindMapEditorAdapter::setSavedData(quint64 p_id, const QString &p_data) { invokeCallback(p_id, (void *)&p_data); } void MindMapEditorAdapter::notifyContentsChanged() { emit contentsChanged(); }
979
C++
.cpp
33
25.575758
91
0.701064
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,539
pdfvieweradapter.cpp
vnotex_vnote/src/widgets/editors/pdfvieweradapter.cpp
#include "pdfvieweradapter.h" using namespace vnotex; PdfViewerAdapter::PdfViewerAdapter(QObject *p_parent) : WebViewAdapter(p_parent) { } void PdfViewerAdapter::setUrl(const QString &p_url) { // TODO: Not supported yet. Q_ASSERT(false); if (isReady()) { emit urlUpdated(p_url); } else { pendAction(std::bind(&PdfViewerAdapter::setUrl, this, p_url)); } }
398
C++
.cpp
16
21.1875
70
0.691293
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,542
pdfviewer.cpp
vnotex_vnote/src/widgets/editors/pdfviewer.cpp
#include "pdfviewer.h" #include <QWebChannel> #include "pdfvieweradapter.h" using namespace vnotex; PdfViewer::PdfViewer(PdfViewerAdapter *p_adapter, const QColor &p_background, qreal p_zoomFactor, QWidget *p_parent) : WebViewer(p_background, p_zoomFactor, p_parent), m_adapter(p_adapter) { m_adapter->setParent(this); auto channel = new QWebChannel(this); channel->registerObject(QStringLiteral("vxAdapter"), m_adapter); page()->setWebChannel(channel); } PdfViewerAdapter *PdfViewer::adapter() const { return m_adapter; }
623
C++
.cpp
20
25.15
68
0.677852
vnotex/vnote
11,753
1,213
637
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false