precedence.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/parser/precedence.h"
  5. #include <utility>
  6. namespace Carbon {
  7. namespace {
  8. enum PrecedenceLevel : int8_t {
  9. // Sentinel representing the absence of any operator.
  10. Highest,
  11. // Terms.
  12. TermPrefix,
  13. // Numeric.
  14. NumericPrefix,
  15. NumericPostfix,
  16. Modulo,
  17. Multiplicative,
  18. Additive,
  19. // Bitwise.
  20. BitwisePrefix,
  21. BitwiseAnd,
  22. BitwiseOr,
  23. BitwiseXor,
  24. BitShift,
  25. // Type formation.
  26. TypePostfix,
  27. // Sentinel representing a type context.
  28. Type,
  29. // Logical.
  30. LogicalPrefix,
  31. Relational,
  32. LogicalAnd,
  33. LogicalOr,
  34. // Assignment.
  35. SimpleAssignment,
  36. CompoundAssignment,
  37. // Sentinel representing a context in which any operator can appear.
  38. Lowest,
  39. };
  40. constexpr int8_t NumPrecedenceLevels = Lowest + 1;
  41. // A precomputed lookup table determining the relative precedence of two
  42. // precedence groups.
  43. struct OperatorPriorityTable {
  44. constexpr OperatorPriorityTable() : table() {
  45. // Start with a list of <higher precedence>, <lower precedence>
  46. // relationships.
  47. MarkHigherThan({Highest}, {TermPrefix});
  48. MarkHigherThan({TermPrefix}, {NumericPrefix, BitwisePrefix, LogicalPrefix,
  49. NumericPostfix, TypePostfix});
  50. MarkHigherThan({NumericPrefix, NumericPostfix},
  51. {Modulo, Multiplicative, BitShift});
  52. MarkHigherThan({Multiplicative}, {Additive});
  53. MarkHigherThan({BitwisePrefix},
  54. {BitwiseAnd, BitwiseOr, BitwiseXor, BitShift});
  55. MarkHigherThan({TypePostfix}, {Type});
  56. MarkHigherThan(
  57. {Modulo, Additive, BitwiseAnd, BitwiseOr, BitwiseXor, BitShift, Type},
  58. {SimpleAssignment, CompoundAssignment, Relational});
  59. MarkHigherThan({Relational, LogicalPrefix}, {LogicalAnd, LogicalOr});
  60. MarkHigherThan(
  61. {SimpleAssignment, CompoundAssignment, LogicalAnd, LogicalOr},
  62. {Lowest});
  63. // Compute the transitive closure of the above relationships: if we parse
  64. // `a $ b @ c` as `(a $ b) @ c` and parse `b @ c % d` as `(b @ c) % d`,
  65. // then we will parse `a $ b @ c % d` as `((a $ b) @ c) % d` and should
  66. // also parse `a $ bc % d` as `(a $ bc) % d`.
  67. MakeTransitivelyClosed();
  68. // Make the relation symmetric. If we parse `a $ b @ c` as `(a $ b) @ c`
  69. // then we want to parse `a @ b $ c` as `a @ (b $ c)`.
  70. MakeSymmetric();
  71. // Fill in the diagonal, which represents operator associativity.
  72. AddAssociativityRules();
  73. ConsistencyCheck();
  74. }
  75. constexpr void MarkHigherThan(
  76. std::initializer_list<PrecedenceLevel> higher_group,
  77. std::initializer_list<PrecedenceLevel> lower_group) {
  78. for (auto higher : higher_group) {
  79. for (auto lower : lower_group) {
  80. table[higher][lower] = OperatorPriority::LeftFirst;
  81. }
  82. }
  83. }
  84. constexpr void MakeTransitivelyClosed() {
  85. // A naive algorithm compiles acceptably fast for now (~0.5s). This should
  86. // be revisited if we see compile time problems after adding precedence
  87. // groups; it's easy to do this faster.
  88. bool changed = false;
  89. do {
  90. changed = false;
  91. // NOLINTNEXTLINE(modernize-loop-convert)
  92. for (int8_t a = 0; a != NumPrecedenceLevels; ++a) {
  93. for (int8_t b = 0; b != NumPrecedenceLevels; ++b) {
  94. if (table[a][b] == OperatorPriority::LeftFirst) {
  95. for (int8_t c = 0; c != NumPrecedenceLevels; ++c) {
  96. if (table[b][c] == OperatorPriority::LeftFirst &&
  97. table[a][c] != OperatorPriority::LeftFirst) {
  98. table[a][c] = OperatorPriority::LeftFirst;
  99. changed = true;
  100. }
  101. }
  102. }
  103. }
  104. }
  105. } while (changed);
  106. }
  107. constexpr void MakeSymmetric() {
  108. for (int8_t a = 0; a != NumPrecedenceLevels; ++a) {
  109. for (int8_t b = 0; b != NumPrecedenceLevels; ++b) {
  110. if (table[a][b] == OperatorPriority::LeftFirst) {
  111. if (table[b][a] == OperatorPriority::LeftFirst) {
  112. throw "inconsistent lookup table entries";
  113. }
  114. table[b][a] = OperatorPriority::RightFirst;
  115. }
  116. }
  117. }
  118. }
  119. constexpr void AddAssociativityRules() {
  120. // Associativity rules occupy the diagonal
  121. // For prefix operators, RightFirst would mean `@@x` is `@(@x)` and
  122. // Ambiguous would mean it's an error. LeftFirst is meaningless. For now we
  123. // allow all prefix operators to be repeated.
  124. for (PrecedenceLevel prefix :
  125. {TermPrefix, NumericPrefix, BitwisePrefix, LogicalPrefix}) {
  126. table[prefix][prefix] = OperatorPriority::RightFirst;
  127. }
  128. // Postfix operators are symmetric with prefix operators.
  129. for (PrecedenceLevel postfix : {NumericPostfix, TypePostfix}) {
  130. table[postfix][postfix] = OperatorPriority::LeftFirst;
  131. }
  132. // Traditionally-associative operators are given left-to-right
  133. // associativity.
  134. for (PrecedenceLevel assoc :
  135. {Multiplicative, Additive, BitwiseAnd, BitwiseOr, BitwiseXor,
  136. LogicalAnd, LogicalOr}) {
  137. table[assoc][assoc] = OperatorPriority::LeftFirst;
  138. }
  139. // Assignment is given right-to-left associativity in order to support
  140. // chained assignment.
  141. table[SimpleAssignment][SimpleAssignment] = OperatorPriority::RightFirst;
  142. // For other operators, there isn't an obvious answer and we require
  143. // explicit parentheses.
  144. }
  145. constexpr void ConsistencyCheck() {
  146. for (int8_t level = 0; level != NumPrecedenceLevels; ++level) {
  147. if (level != Highest) {
  148. if (table[Highest][level] != OperatorPriority::LeftFirst ||
  149. table[level][Highest] != OperatorPriority::RightFirst) {
  150. throw "Highest is not highest priority";
  151. }
  152. }
  153. if (level != Lowest) {
  154. if (table[Lowest][level] != OperatorPriority::RightFirst ||
  155. table[level][Lowest] != OperatorPriority::LeftFirst) {
  156. throw "Lowest is not lowest priority";
  157. }
  158. }
  159. }
  160. }
  161. OperatorPriority table[NumPrecedenceLevels][NumPrecedenceLevels];
  162. };
  163. } // namespace
  164. auto PrecedenceGroup::ForPostfixExpression() -> PrecedenceGroup {
  165. return PrecedenceGroup(Highest);
  166. }
  167. auto PrecedenceGroup::ForTopLevelExpression() -> PrecedenceGroup {
  168. return PrecedenceGroup(Lowest);
  169. }
  170. auto PrecedenceGroup::ForType() -> PrecedenceGroup {
  171. return PrecedenceGroup(Type);
  172. }
  173. auto PrecedenceGroup::ForLeading(TokenKind kind)
  174. -> llvm::Optional<PrecedenceGroup> {
  175. switch (kind) {
  176. case TokenKind::Star():
  177. return PrecedenceGroup(TermPrefix);
  178. case TokenKind::NotKeyword():
  179. return PrecedenceGroup(LogicalPrefix);
  180. case TokenKind::Minus():
  181. case TokenKind::MinusMinus():
  182. case TokenKind::PlusPlus():
  183. return PrecedenceGroup(NumericPrefix);
  184. case TokenKind::Tilde():
  185. return PrecedenceGroup(BitwisePrefix);
  186. default:
  187. return llvm::None;
  188. }
  189. }
  190. auto PrecedenceGroup::ForTrailing(TokenKind kind, bool infix)
  191. -> llvm::Optional<Trailing> {
  192. switch (kind) {
  193. // Assignment operators.
  194. case TokenKind::Equal():
  195. return Trailing{.level = SimpleAssignment, .is_binary = true};
  196. case TokenKind::PlusEqual():
  197. case TokenKind::MinusEqual():
  198. case TokenKind::StarEqual():
  199. case TokenKind::SlashEqual():
  200. case TokenKind::PercentEqual():
  201. case TokenKind::AmpEqual():
  202. case TokenKind::PipeEqual():
  203. case TokenKind::GreaterGreaterEqual():
  204. case TokenKind::LessLessEqual():
  205. return Trailing{.level = CompoundAssignment, .is_binary = true};
  206. // Logical operators.
  207. case TokenKind::AndKeyword():
  208. return Trailing{.level = LogicalAnd, .is_binary = true};
  209. case TokenKind::OrKeyword():
  210. return Trailing{.level = LogicalOr, .is_binary = true};
  211. // Bitwise operators.
  212. case TokenKind::Amp():
  213. return Trailing{.level = BitwiseAnd, .is_binary = true};
  214. case TokenKind::Pipe():
  215. return Trailing{.level = BitwiseOr, .is_binary = true};
  216. case TokenKind::XorKeyword():
  217. return Trailing{.level = BitwiseXor, .is_binary = true};
  218. case TokenKind::GreaterGreater():
  219. case TokenKind::LessLess():
  220. return Trailing{.level = BitShift, .is_binary = true};
  221. // Relational operators.
  222. case TokenKind::EqualEqual():
  223. case TokenKind::ExclaimEqual():
  224. case TokenKind::Less():
  225. case TokenKind::LessEqual():
  226. case TokenKind::Greater():
  227. case TokenKind::GreaterEqual():
  228. case TokenKind::LessEqualGreater():
  229. return Trailing{.level = Relational, .is_binary = true};
  230. // Addative operators.
  231. case TokenKind::Plus():
  232. case TokenKind::Minus():
  233. return Trailing{.level = Additive, .is_binary = true};
  234. // Multiplicative operators.
  235. case TokenKind::Slash():
  236. return Trailing{.level = Multiplicative, .is_binary = true};
  237. case TokenKind::Percent():
  238. return Trailing{.level = Modulo, .is_binary = true};
  239. // `*` could be multiplication or pointer type formation.
  240. case TokenKind::Star():
  241. return infix ? Trailing{.level = Multiplicative, .is_binary = true}
  242. : Trailing{.level = TypePostfix, .is_binary = false};
  243. // Postfix operators.
  244. case TokenKind::MinusMinus():
  245. case TokenKind::PlusPlus():
  246. return Trailing{.level = NumericPostfix, .is_binary = false};
  247. // Prefix-only operators.
  248. case TokenKind::Tilde():
  249. case TokenKind::NotKeyword():
  250. break;
  251. // Symbolic tokens that might be operators eventually.
  252. case TokenKind::Backslash():
  253. case TokenKind::Caret():
  254. case TokenKind::CaretEqual():
  255. case TokenKind::Comma():
  256. case TokenKind::TildeEqual():
  257. case TokenKind::Exclaim():
  258. case TokenKind::LessGreater():
  259. case TokenKind::Question():
  260. case TokenKind::Colon():
  261. break;
  262. // Symbolic tokens that are intentionally not operators.
  263. case TokenKind::At():
  264. case TokenKind::LessMinus():
  265. case TokenKind::MinusGreater():
  266. case TokenKind::EqualGreater():
  267. case TokenKind::ColonEqual():
  268. case TokenKind::Period():
  269. case TokenKind::Semi():
  270. break;
  271. default:
  272. break;
  273. }
  274. return llvm::None;
  275. }
  276. auto PrecedenceGroup::GetPriority(PrecedenceGroup left, PrecedenceGroup right)
  277. -> OperatorPriority {
  278. static constexpr OperatorPriorityTable Lookup;
  279. return Lookup.table[left.level][right.level];
  280. }
  281. } // namespace Carbon