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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* expand/include.cpp
* - include!/include_str!/include_bytes! support
*/
#include <synext_macro.hpp>
#include <synext.hpp> // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp> // Lexer (new files)
#include <ast/expr.hpp>
namespace {
::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
{
auto n = Parse_ExprVal(lex);
ASSERT_BUG(sp, n, "No expression returned");
Expand_BareExpr(crate, mod, n);
auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
if( !string_np ) {
ERROR(sp, E0000, "include! requires a string literal - got " << *n);
}
return mv$( string_np->m_value );
}
::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
{
DEBUG(base_path << ", " << path);
if( path[0] == '/' || path[0] == '\\' ) {
return path;
}
else if( base_path.size() == 0 ) {
return path;
}
else if( base_path.back() == '/' || base_path.back() == '\\' ) {
return base_path + path;
}
else {
auto slash = ::std::min( base_path.find_last_of('/'), base_path.find_last_of('\\') );
if( slash == ::std::string::npos )
{
return path;
}
else
{
slash += 1;
::std::string rv;
rv.reserve( slash + path.size() );
rv.append( base_path.begin(), base_path.begin() + slash );
rv.append( path.begin(), path.end() );
return rv;
}
}
}
};
class CIncludeExpander:
public ExpandProcMacro
{
::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
{
if( ident != "" )
ERROR(sp, E0000, "include! doesn't take an ident");
Token tok;
auto lex = TTStream(tt);
auto path = get_string(sp, lex, crate, mod);
GET_CHECK_TOK(tok, lex, TOK_EOF);
::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
try {
return box$( Lexer(file_path) );
}
catch(::std::runtime_error& e)
{
ERROR(sp, E0000, e.what());
}
}
};
// TODO: include_str! and include_bytes!
STATIC_MACRO("include", CIncludeExpander);
|