1//===- ScriptLexer.h --------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLD_ELF_SCRIPT_LEXER_H
10#define LLD_ELF_SCRIPT_LEXER_H
11
12#include "lld/Common/LLVM.h"
13#include "llvm/ADT/DenseSet.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/Support/MemoryBufferRef.h"
17#include <vector>
18
19namespace lld::elf {
20struct Ctx;
21
22class ScriptLexer {
23protected:
24 struct Buffer {
25 // The remaining content to parse and the filename.
26 StringRef s, filename;
27 const char *begin = nullptr;
28 size_t lineNumber = 1;
29 // True if the script is opened as an absolute path under the --sysroot
30 // directory.
31 bool isUnderSysroot = false;
32
33 Buffer() = default;
34 Buffer(Ctx &ctx, MemoryBufferRef mb);
35 };
36 Ctx &ctx;
37 // The current buffer and parent buffers due to INCLUDE.
38 Buffer curBuf;
39 SmallVector<Buffer, 0> buffers;
40
41 // Used to detect INCLUDE() cycles.
42 llvm::DenseSet<StringRef> activeFilenames;
43
44 enum class State {
45 Script,
46 Expr,
47 // Used by version node and dynamic list parsing.
48 VersionNode,
49 };
50
51 struct Token {
52 StringRef str;
53 explicit operator bool() const { return !str.empty(); }
54 operator StringRef() const { return str; }
55 };
56
57 // The token before the last next().
58 StringRef prevTok;
59 // Rules for what is a token are different when we are in an expression.
60 // curTok holds the cached return value of peek() and is invalid when the
61 // expression state changes.
62 StringRef curTok;
63 size_t prevTokLine = 1;
64 // The lex state when curTok is cached.
65 State curTokState = State::Script;
66 State lexState = State::Script;
67 bool eof = false;
68
69public:
70 explicit ScriptLexer(Ctx &ctx, MemoryBufferRef mb);
71
72 void setError(const Twine &msg);
73 void lex();
74 StringRef skipSpace(StringRef s);
75 bool atEOF();
76 StringRef next();
77 StringRef peek();
78 void skip();
79 bool consume(StringRef tok);
80 void expect(StringRef expect);
81 Token till(StringRef tok);
82 std::string getCurrentLocation();
83 MemoryBufferRef getCurrentMB();
84
85 std::vector<MemoryBufferRef> mbs;
86
87private:
88 StringRef getLine();
89 size_t getColumnNumber();
90};
91
92} // namespace lld::elf
93
94#endif
95