Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/Compiler/src/Utils.h
2725 views
1
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2
#pragma once
3
4
#include "Luau/Ast.h"
5
#include "Luau/DenseHash.h"
6
7
#include "ConstantFolding.h"
8
9
namespace Luau
10
{
11
namespace Compile
12
{
13
14
inline bool isConstantTrue(const DenseHashMap<AstExpr*, Constant>& constants, AstExpr* node)
15
{
16
const Constant* cv = constants.find(node);
17
18
return cv && cv->type != Constant::Type_Unknown && cv->isTruthful();
19
}
20
21
inline bool isConstantFalse(const DenseHashMap<AstExpr*, Constant>& constants, AstExpr* node)
22
{
23
const Constant* cv = constants.find(node);
24
25
return cv && cv->type != Constant::Type_Unknown && !cv->isTruthful();
26
}
27
28
// true iff all execution paths through node subtree result in return/break/continue
29
// note: because this function doesn't visit loop nodes, it (correctly) only detects break/continue that refer to the outer control flow
30
inline bool alwaysTerminates(const DenseHashMap<AstExpr*, Constant>& constants, AstStat* node)
31
{
32
if (AstStatBlock* stat = node->as<AstStatBlock>())
33
{
34
for (size_t i = 0; i < stat->body.size; ++i)
35
{
36
if (alwaysTerminates(constants, stat->body.data[i]))
37
return true;
38
}
39
40
return false;
41
}
42
43
if (node->is<AstStatReturn>())
44
return true;
45
46
if (node->is<AstStatBreak>() || node->is<AstStatContinue>())
47
return true;
48
49
if (AstStatIf* stat = node->as<AstStatIf>())
50
{
51
if (isConstantTrue(constants, stat->condition))
52
return alwaysTerminates(constants, stat->thenbody);
53
54
if (isConstantFalse(constants, stat->condition) && stat->elsebody)
55
return alwaysTerminates(constants, stat->elsebody);
56
57
return stat->elsebody && alwaysTerminates(constants, stat->thenbody) && alwaysTerminates(constants, stat->elsebody);
58
}
59
60
return false;
61
}
62
63
} // namespace Compile
64
} // namespace Luau
65
66