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
18namespace lld::elf {
19struct Ctx;
20
21class ScriptLexer {
22protected:
23 struct Buffer {
24 // The remaining content to parse and the filename.
25 StringRef s, filename;
26 const char *begin = nullptr;
27 size_t lineNumber = 1;
28 // True if the script is opened as an absolute path under the --sysroot
29 // directory.
30 bool isUnderSysroot = false;
31
32 Buffer() = default;
33 Buffer(Ctx &ctx, MemoryBufferRef mb);
34 };
35 Ctx &ctx;
36 // The currently lexed buffer. INCLUDE runs a nested parse on a new `Buffer`,
37 // similar to a call stack frame.
38 Buffer curBuf;
39
40 // Used to detect INCLUDE() cycles.
41 llvm::DenseSet<StringRef> activeFilenames;
42
43 enum class State {
44 Script,
45 Expr,
46 // Used by version node and dynamic list parsing.
47 VersionNode,
48 };
49
50 struct Token {
51 StringRef str;
52 explicit operator bool() const { return !str.empty(); }
53 operator StringRef() const { return str; }
54 };
55
56 // The token before the last next().
57 StringRef prevTok;
58 // Rules for what is a token are different when we are in an expression.
59 // curTok holds the cached return value of peek() and is invalid when the
60 // expression state changes.
61 StringRef curTok;
62 size_t prevTokLine = 1;
63 // The lex state when curTok is cached.
64 State curTokState = State::Script;
65 State lexState = State::Script;
66 bool eof = false;
67
68public:
69 explicit ScriptLexer(Ctx &ctx, MemoryBufferRef mb);
70
71 void setError(const Twine &msg);
72 void lex();
73 StringRef skipSpace(StringRef s);
74 bool atEOF();
75 StringRef next();
76 StringRef peek();
77 void skip();
78 bool consume(StringRef tok);
79 void expect(StringRef expect);
80 Token till(StringRef tok);
81 std::string getCurrentLocation();
82
83private:
84 StringRef getLine();
85 size_t getColumnNumber();
86};
87
88} // namespace lld::elf
89
90#endif
91