aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/position.hh
blob: a184997ed857e104ace093c2ff994253331389ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#pragma once
/**
 * @file
 *
 * @brief Pos and AbstractPos
 */

#include <cstdint>
#include <string>

#include "source-path.hh"

namespace nix {

/**
 * A position and an origin for that position (like a source file).
 */
struct Pos
{
    uint32_t line = 0;
    uint32_t column = 0;

    struct Stdin {
        ref<std::string> source;
        bool operator==(const Stdin & rhs) const
        { return *source == *rhs.source; }
        bool operator!=(const Stdin & rhs) const
        { return *source != *rhs.source; }
        bool operator<(const Stdin & rhs) const
        { return *source < *rhs.source; }
    };
    struct String {
        ref<std::string> source;
        bool operator==(const String & rhs) const
        { return *source == *rhs.source; }
        bool operator!=(const String & rhs) const
        { return *source != *rhs.source; }
        bool operator<(const String & rhs) const
        { return *source < *rhs.source; }
    };

    typedef std::variant<std::monostate, Stdin, String, SourcePath> Origin;

    Origin origin = std::monostate();

    Pos() { }
    Pos(uint32_t line, uint32_t column, Origin origin)
        : line(line), column(column), origin(origin) { }
    Pos(Pos & other) = default;
    Pos(const Pos & other) = default;
    Pos(Pos && other) = default;
    Pos(const Pos * other);

    explicit operator bool() const { return line > 0; }

    operator std::shared_ptr<Pos>() const;

    /**
     * Return the contents of the source file.
     */
    std::optional<std::string> getSource() const;

    void print(std::ostream & out, bool showOrigin) const;

    std::optional<LinesOfCode> getCodeLines() const;

    bool operator==(const Pos & rhs) const = default;
    bool operator!=(const Pos & rhs) const = default;
    bool operator<(const Pos & rhs) const;
};

std::ostream & operator<<(std::ostream & str, const Pos & pos);

}