Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/CLI/src/Ast.cpp
2725 views
1
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2
#include <optional>
3
4
#include "Luau/Common.h"
5
#include "Luau/Ast.h"
6
#include "Luau/AstJsonEncoder.h"
7
#include "Luau/Parser.h"
8
#include "Luau/ParseOptions.h"
9
#include "Luau/ToString.h"
10
11
#include "Luau/FileUtils.h"
12
13
static void displayHelp(const char* argv0)
14
{
15
printf("Usage: %s [file]\n", argv0);
16
}
17
18
static int assertionHandler(const char* expr, const char* file, int line, const char* function)
19
{
20
printf("%s(%d): ASSERTION FAILED: %s\n", file, line, expr);
21
return 1;
22
}
23
24
int main(int argc, char** argv)
25
{
26
Luau::assertHandler() = assertionHandler;
27
28
for (Luau::FValue<bool>* flag = Luau::FValue<bool>::list; flag; flag = flag->next)
29
if (strncmp(flag->name, "Luau", 4) == 0)
30
flag->value = true;
31
32
if (argc >= 2 && strcmp(argv[1], "--help") == 0)
33
{
34
displayHelp(argv[0]);
35
return 0;
36
}
37
else if (argc < 2)
38
{
39
displayHelp(argv[0]);
40
return 1;
41
}
42
43
const char* name = argv[1];
44
std::optional<std::string> maybeSource = std::nullopt;
45
if (strcmp(name, "-") == 0)
46
{
47
maybeSource = readStdin();
48
}
49
else
50
{
51
maybeSource = readFile(name);
52
}
53
54
if (!maybeSource)
55
{
56
fprintf(stderr, "Couldn't read source %s\n", name);
57
return 1;
58
}
59
60
std::string source = *maybeSource;
61
62
Luau::Allocator allocator;
63
Luau::AstNameTable names(allocator);
64
65
Luau::ParseOptions options;
66
options.captureComments = true;
67
options.allowDeclarationSyntax = true;
68
69
Luau::ParseResult parseResult = Luau::Parser::parse(source.data(), source.size(), names, allocator, std::move(options));
70
71
if (parseResult.errors.size() > 0)
72
{
73
fprintf(stderr, "Parse errors were encountered:\n");
74
for (const Luau::ParseError& error : parseResult.errors)
75
{
76
fprintf(stderr, " %s - %s\n", toString(error.getLocation()).c_str(), error.getMessage().c_str());
77
}
78
fprintf(stderr, "\n");
79
}
80
81
printf("%s", Luau::toJson(parseResult.root, parseResult.commentLocations).c_str());
82
83
return parseResult.errors.size() > 0 ? 1 : 0;
84
}
85
86