parse_tree_test.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 "parser/parse_tree.h"
  5. #include <forward_list>
  6. #include "diagnostics/diagnostic_emitter.h"
  7. #include "gmock/gmock.h"
  8. #include "gtest/gtest.h"
  9. #include "lexer/tokenized_buffer.h"
  10. #include "lexer/tokenized_buffer_test_helpers.h"
  11. #include "llvm/ADT/Sequence.h"
  12. #include "llvm/Support/SourceMgr.h"
  13. #include "llvm/Support/YAMLParser.h"
  14. #include "parser/parse_node_kind.h"
  15. #include "parser/parse_test_helpers.h"
  16. namespace Carbon {
  17. namespace {
  18. using Carbon::Testing::ExpectedNode;
  19. using Carbon::Testing::IsKeyValueScalars;
  20. using Carbon::Testing::MatchParseTreeNodes;
  21. using namespace Carbon::Testing::NodeMatchers;
  22. using ::testing::Eq;
  23. using ::testing::Ne;
  24. using ::testing::NotNull;
  25. using ::testing::StrEq;
  26. struct ParseTreeTest : ::testing::Test {
  27. std::forward_list<SourceBuffer> source_storage;
  28. std::forward_list<TokenizedBuffer> token_storage;
  29. DiagnosticConsumer& consumer = ConsoleDiagnosticConsumer();
  30. auto GetSourceBuffer(llvm::Twine t) -> SourceBuffer& {
  31. source_storage.push_front(SourceBuffer::CreateFromText(t.str()));
  32. return source_storage.front();
  33. }
  34. auto GetTokenizedBuffer(llvm::Twine t) -> TokenizedBuffer& {
  35. token_storage.push_front(
  36. TokenizedBuffer::Lex(GetSourceBuffer(t), consumer));
  37. return token_storage.front();
  38. }
  39. };
  40. TEST_F(ParseTreeTest, Empty) {
  41. TokenizedBuffer tokens = GetTokenizedBuffer("");
  42. ParseTree tree = ParseTree::Parse(tokens, consumer);
  43. EXPECT_FALSE(tree.HasErrors());
  44. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFileEnd()}));
  45. }
  46. TEST_F(ParseTreeTest, EmptyDeclaration) {
  47. TokenizedBuffer tokens = GetTokenizedBuffer(";");
  48. ParseTree tree = ParseTree::Parse(tokens, consumer);
  49. EXPECT_FALSE(tree.HasErrors());
  50. auto it = tree.Postorder().begin();
  51. auto end = tree.Postorder().end();
  52. ASSERT_THAT(it, Ne(end));
  53. ParseTree::Node n = *it++;
  54. ASSERT_THAT(it, Ne(end));
  55. ParseTree::Node eof = *it++;
  56. EXPECT_THAT(it, Eq(end));
  57. // Directly test the main API so that we get easier to understand errors in
  58. // simple cases than what the custom matcher will produce.
  59. EXPECT_FALSE(tree.HasErrorInNode(n));
  60. EXPECT_FALSE(tree.HasErrorInNode(eof));
  61. EXPECT_THAT(tree.GetNodeKind(n), Eq(ParseNodeKind::EmptyDeclaration()));
  62. EXPECT_THAT(tree.GetNodeKind(eof), Eq(ParseNodeKind::FileEnd()));
  63. auto t = tree.GetNodeToken(n);
  64. ASSERT_THAT(tokens.Tokens().begin(), Ne(tokens.Tokens().end()));
  65. EXPECT_THAT(t, Eq(*tokens.Tokens().begin()));
  66. EXPECT_THAT(tokens.GetTokenText(t), Eq(";"));
  67. EXPECT_THAT(tree.Children(n).begin(), Eq(tree.Children(n).end()));
  68. EXPECT_THAT(tree.Children(eof).begin(), Eq(tree.Children(eof).end()));
  69. EXPECT_THAT(tree.Postorder().begin(), Eq(tree.Postorder(n).begin()));
  70. EXPECT_THAT(tree.Postorder(n).end(), Eq(tree.Postorder(eof).begin()));
  71. EXPECT_THAT(tree.Postorder(eof).end(), Eq(tree.Postorder().end()));
  72. }
  73. TEST_F(ParseTreeTest, BasicFunctionDeclaration) {
  74. TokenizedBuffer tokens = GetTokenizedBuffer("fn F();");
  75. ParseTree tree = ParseTree::Parse(tokens, consumer);
  76. EXPECT_FALSE(tree.HasErrors());
  77. EXPECT_THAT(tree, MatchParseTreeNodes(
  78. {MatchFunctionDeclaration("fn", MatchDeclaredName("F"),
  79. MatchParameters(),
  80. MatchDeclarationEnd(";")),
  81. MatchFileEnd()}));
  82. }
  83. TEST_F(ParseTreeTest, NoDeclarationIntroducerOrSemi) {
  84. TokenizedBuffer tokens = GetTokenizedBuffer("foo bar baz");
  85. ParseTree tree = ParseTree::Parse(tokens, consumer);
  86. EXPECT_TRUE(tree.HasErrors());
  87. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFileEnd()}));
  88. }
  89. TEST_F(ParseTreeTest, NoDeclarationIntroducerWithSemi) {
  90. TokenizedBuffer tokens = GetTokenizedBuffer("foo;");
  91. ParseTree tree = ParseTree::Parse(tokens, consumer);
  92. EXPECT_TRUE(tree.HasErrors());
  93. EXPECT_THAT(tree, MatchParseTreeNodes({MatchEmptyDeclaration(";", HasError),
  94. MatchFileEnd()}));
  95. }
  96. TEST_F(ParseTreeTest, JustFunctionIntroducerAndSemi) {
  97. TokenizedBuffer tokens = GetTokenizedBuffer("fn;");
  98. ParseTree tree = ParseTree::Parse(tokens, consumer);
  99. EXPECT_TRUE(tree.HasErrors());
  100. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFunctionDeclaration(
  101. HasError, MatchDeclarationEnd()),
  102. MatchFileEnd()}));
  103. }
  104. TEST_F(ParseTreeTest, RepeatedFunctionIntroducerAndSemi) {
  105. TokenizedBuffer tokens = GetTokenizedBuffer("fn fn;");
  106. ParseTree tree = ParseTree::Parse(tokens, consumer);
  107. EXPECT_TRUE(tree.HasErrors());
  108. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFunctionDeclaration(
  109. HasError, MatchDeclarationEnd()),
  110. MatchFileEnd()}));
  111. }
  112. TEST_F(ParseTreeTest, FunctionDeclarationWithNoSignatureOrSemi) {
  113. TokenizedBuffer tokens = GetTokenizedBuffer("fn foo");
  114. ParseTree tree = ParseTree::Parse(tokens, consumer);
  115. EXPECT_TRUE(tree.HasErrors());
  116. EXPECT_THAT(tree,
  117. MatchParseTreeNodes(
  118. {MatchFunctionDeclaration(HasError, MatchDeclaredName("foo")),
  119. MatchFileEnd()}));
  120. }
  121. TEST_F(ParseTreeTest,
  122. FunctionDeclarationWithIdentifierInsteadOfSignatureAndSemi) {
  123. TokenizedBuffer tokens = GetTokenizedBuffer("fn foo bar;");
  124. ParseTree tree = ParseTree::Parse(tokens, consumer);
  125. EXPECT_TRUE(tree.HasErrors());
  126. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFunctionDeclaration(
  127. HasError, MatchDeclaredName("foo"),
  128. MatchDeclarationEnd()),
  129. MatchFileEnd()}));
  130. }
  131. TEST_F(ParseTreeTest, FunctionDeclarationWithSingleIdentifierParameterList) {
  132. TokenizedBuffer tokens = GetTokenizedBuffer("fn foo(bar);");
  133. ParseTree tree = ParseTree::Parse(tokens, consumer);
  134. // Note: this might become valid depending on the parameter syntax, this test
  135. // shouldn't be taken as a sign it should remain invalid.
  136. EXPECT_TRUE(tree.HasErrors());
  137. EXPECT_THAT(tree,
  138. MatchParseTreeNodes(
  139. {MatchFunctionDeclaration(
  140. HasError, MatchDeclaredName("foo"),
  141. MatchParameterList(HasError, MatchParameterListEnd()),
  142. MatchDeclarationEnd()),
  143. MatchFileEnd()}));
  144. }
  145. TEST_F(ParseTreeTest, FunctionDeclarationWithoutName) {
  146. TokenizedBuffer tokens = GetTokenizedBuffer("fn ();");
  147. ParseTree tree = ParseTree::Parse(tokens, consumer);
  148. EXPECT_TRUE(tree.HasErrors());
  149. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFunctionDeclaration(
  150. HasError, MatchDeclarationEnd()),
  151. MatchFileEnd()}));
  152. }
  153. TEST_F(ParseTreeTest,
  154. FunctionDeclarationWithoutNameAndManyTokensToSkipInGroupedSymbols) {
  155. TokenizedBuffer tokens = GetTokenizedBuffer(
  156. "fn (a tokens c d e f g h i j k l m n o p q r s t u v w x y z);");
  157. ParseTree tree = ParseTree::Parse(tokens, consumer);
  158. EXPECT_TRUE(tree.HasErrors());
  159. EXPECT_THAT(tree, MatchParseTreeNodes({MatchFunctionDeclaration(
  160. HasError, MatchDeclarationEnd()),
  161. MatchFileEnd()}));
  162. }
  163. TEST_F(ParseTreeTest, FunctionDeclarationSkipToNewlineWithoutSemi) {
  164. TokenizedBuffer tokens = GetTokenizedBuffer(
  165. "fn ()\n"
  166. "fn F();");
  167. ParseTree tree = ParseTree::Parse(tokens, consumer);
  168. EXPECT_TRUE(tree.HasErrors());
  169. EXPECT_THAT(
  170. tree, MatchParseTreeNodes({MatchFunctionDeclaration(HasError),
  171. MatchFunctionDeclaration(
  172. MatchDeclaredName("F"), MatchParameters(),
  173. MatchDeclarationEnd()),
  174. MatchFileEnd()}));
  175. }
  176. TEST_F(ParseTreeTest, FunctionDeclarationSkipIndentedNewlineWithSemi) {
  177. TokenizedBuffer tokens = GetTokenizedBuffer(
  178. "fn (x,\n"
  179. " y,\n"
  180. " z);\n"
  181. "fn F();");
  182. ParseTree tree = ParseTree::Parse(tokens, consumer);
  183. EXPECT_TRUE(tree.HasErrors());
  184. EXPECT_THAT(
  185. tree,
  186. MatchParseTreeNodes(
  187. {MatchFunctionDeclaration(HasError, MatchDeclarationEnd()),
  188. MatchFunctionDeclaration(MatchDeclaredName("F"), MatchParameters(),
  189. MatchDeclarationEnd()),
  190. MatchFileEnd()}));
  191. }
  192. TEST_F(ParseTreeTest, FunctionDeclarationSkipIndentedNewlineWithoutSemi) {
  193. TokenizedBuffer tokens = GetTokenizedBuffer(
  194. "fn (x,\n"
  195. " y,\n"
  196. " z)\n"
  197. "fn F();");
  198. ParseTree tree = ParseTree::Parse(tokens, consumer);
  199. EXPECT_TRUE(tree.HasErrors());
  200. EXPECT_THAT(
  201. tree, MatchParseTreeNodes({MatchFunctionDeclaration(HasError),
  202. MatchFunctionDeclaration(
  203. MatchDeclaredName("F"), MatchParameters(),
  204. MatchDeclarationEnd()),
  205. MatchFileEnd()}));
  206. }
  207. TEST_F(ParseTreeTest, FunctionDeclarationSkipIndentedNewlineUntilOutdent) {
  208. TokenizedBuffer tokens = GetTokenizedBuffer(
  209. " fn (x,\n"
  210. " y,\n"
  211. " z)\n"
  212. "fn F();");
  213. ParseTree tree = ParseTree::Parse(tokens, consumer);
  214. EXPECT_TRUE(tree.HasErrors());
  215. EXPECT_THAT(
  216. tree, MatchParseTreeNodes({MatchFunctionDeclaration(HasError),
  217. MatchFunctionDeclaration(
  218. MatchDeclaredName("F"), MatchParameters(),
  219. MatchDeclarationEnd()),
  220. MatchFileEnd()}));
  221. }
  222. TEST_F(ParseTreeTest, FunctionDeclarationSkipWithoutSemiToCurly) {
  223. // FIXME: We don't have a grammar construct that uses curlies yet so this just
  224. // won't parse at all. Once it does, we should ensure that the close brace
  225. // gets properly parsed for the struct (or whatever other curly-braced syntax
  226. // we have grouping function declarations) despite the invalid function
  227. // declaration missing a semicolon.
  228. TokenizedBuffer tokens = GetTokenizedBuffer(
  229. "struct X { fn () }\n"
  230. "fn F();");
  231. ParseTree tree = ParseTree::Parse(tokens, consumer);
  232. EXPECT_TRUE(tree.HasErrors());
  233. }
  234. TEST_F(ParseTreeTest, BasicFunctionDefinition) {
  235. TokenizedBuffer tokens = GetTokenizedBuffer(
  236. "fn F() {\n"
  237. "}");
  238. ParseTree tree = ParseTree::Parse(tokens, consumer);
  239. EXPECT_FALSE(tree.HasErrors());
  240. EXPECT_THAT(tree, MatchParseTreeNodes(
  241. {MatchFunctionDeclaration(
  242. MatchDeclaredName("F"), MatchParameters(),
  243. MatchCodeBlock("{", MatchCodeBlockEnd("}"))),
  244. MatchFileEnd()}));
  245. }
  246. TEST_F(ParseTreeTest, FunctionDefinitionWithNestedBlocks) {
  247. TokenizedBuffer tokens = GetTokenizedBuffer(
  248. "fn F() {\n"
  249. " {\n"
  250. " {{}}\n"
  251. " }\n"
  252. "}");
  253. ParseTree tree = ParseTree::Parse(tokens, consumer);
  254. EXPECT_FALSE(tree.HasErrors());
  255. EXPECT_THAT(
  256. tree, MatchParseTreeNodes(
  257. {MatchFunctionDeclaration(
  258. MatchDeclaredName("F"), MatchParameters(),
  259. MatchCodeBlock(
  260. MatchCodeBlock(
  261. MatchCodeBlock(MatchCodeBlock(MatchCodeBlockEnd()),
  262. MatchCodeBlockEnd()),
  263. MatchCodeBlockEnd()),
  264. MatchCodeBlockEnd())),
  265. MatchFileEnd()}));
  266. }
  267. TEST_F(ParseTreeTest, FunctionDefinitionWithIdenifierInStatements) {
  268. TokenizedBuffer tokens = GetTokenizedBuffer(
  269. "fn F() {\n"
  270. " bar\n"
  271. "}");
  272. ParseTree tree = ParseTree::Parse(tokens, consumer);
  273. // Note: this might become valid depending on the expression syntax. This test
  274. // shouldn't be taken as a sign it should remain invalid.
  275. EXPECT_TRUE(tree.HasErrors());
  276. EXPECT_THAT(tree, MatchParseTreeNodes(
  277. {MatchFunctionDeclaration(
  278. MatchDeclaredName("F"), MatchParameters(),
  279. MatchCodeBlock(HasError, MatchNameReference("bar"),
  280. MatchCodeBlockEnd())),
  281. MatchFileEnd()}));
  282. }
  283. TEST_F(ParseTreeTest, FunctionDefinitionWithIdenifierInNestedBlock) {
  284. TokenizedBuffer tokens = GetTokenizedBuffer(
  285. "fn F() {\n"
  286. " {bar}\n"
  287. "}");
  288. ParseTree tree = ParseTree::Parse(tokens, consumer);
  289. // Note: this might become valid depending on the expression syntax. This test
  290. // shouldn't be taken as a sign it should remain invalid.
  291. EXPECT_TRUE(tree.HasErrors());
  292. EXPECT_THAT(tree,
  293. MatchParseTreeNodes(
  294. {MatchFunctionDeclaration(
  295. MatchDeclaredName("F"), MatchParameters(),
  296. MatchCodeBlock(
  297. MatchCodeBlock(HasError, MatchNameReference("bar"),
  298. MatchCodeBlockEnd()),
  299. MatchCodeBlockEnd())),
  300. MatchFileEnd()}));
  301. }
  302. TEST_F(ParseTreeTest, FunctionDefinitionWithFunctionCall) {
  303. TokenizedBuffer tokens = GetTokenizedBuffer(
  304. "fn F() {\n"
  305. " a.b.f(c.d, (e)).g();\n"
  306. "}");
  307. ParseTree tree = ParseTree::Parse(tokens, consumer);
  308. EXPECT_FALSE(tree.HasErrors());
  309. ExpectedNode call_to_f = MatchCallExpression(
  310. MatchDesignator(MatchDesignator(MatchNameReference("a"), "b"), "f"),
  311. MatchDesignator(MatchNameReference("c"), "d"), MatchCallExpressionComma(),
  312. MatchParenExpression(MatchNameReference("e"), MatchParenExpressionEnd()),
  313. MatchCallExpressionEnd());
  314. ExpectedNode statement = MatchExpressionStatement(MatchCallExpression(
  315. MatchDesignator(call_to_f, "g"), MatchCallExpressionEnd()));
  316. EXPECT_THAT(tree, MatchParseTreeNodes(
  317. {MatchFunctionWithBody(statement), MatchFileEnd()}));
  318. }
  319. TEST_F(ParseTreeTest, InvalidDesignators) {
  320. TokenizedBuffer tokens = GetTokenizedBuffer(
  321. "fn F() {\n"
  322. " a.;\n"
  323. " a.fn;\n"
  324. " a.42;\n"
  325. "}");
  326. ParseTree tree = ParseTree::Parse(tokens, consumer);
  327. EXPECT_TRUE(tree.HasErrors());
  328. EXPECT_THAT(tree, MatchParseTreeNodes(
  329. {MatchFunctionWithBody(
  330. MatchExpressionStatement(
  331. MatchDesignatorExpression(
  332. MatchNameReference("a"), ".", HasError),
  333. ";"),
  334. MatchExpressionStatement(
  335. MatchDesignatorExpression(
  336. MatchNameReference("a"), ".", HasError),
  337. ";"),
  338. MatchExpressionStatement(
  339. MatchDesignatorExpression(
  340. MatchNameReference("a"), ".", HasError),
  341. HasError, ";")),
  342. MatchFileEnd()}));
  343. }
  344. TEST_F(ParseTreeTest, Operators) {
  345. TokenizedBuffer tokens = GetTokenizedBuffer(
  346. "fn F() {\n"
  347. " n = a * b + c * d = d * d << e & f - not g;\n"
  348. " ++++n;\n"
  349. " n++++;\n"
  350. " a and b and c;\n"
  351. " a and b or c;\n"
  352. " a or b and c;\n"
  353. " not a and not b and not c;\n"
  354. "}");
  355. ParseTree tree = ParseTree::Parse(tokens, consumer);
  356. EXPECT_TRUE(tree.HasErrors());
  357. EXPECT_THAT(
  358. tree,
  359. MatchParseTreeNodes(
  360. {MatchFunctionWithBody(
  361. MatchExpressionStatement(MatchInfixOperator(
  362. MatchNameReference("n"), "=",
  363. MatchInfixOperator(
  364. MatchInfixOperator(
  365. MatchInfixOperator(MatchNameReference("a"), "*",
  366. MatchNameReference("b")),
  367. "+",
  368. MatchInfixOperator(MatchNameReference("c"), "*",
  369. MatchNameReference("d"))),
  370. "=",
  371. MatchInfixOperator(
  372. HasError,
  373. MatchInfixOperator(
  374. HasError,
  375. MatchInfixOperator(
  376. HasError,
  377. MatchInfixOperator(MatchNameReference("d"),
  378. "*",
  379. MatchNameReference("d")),
  380. "<<", MatchNameReference("e")),
  381. "&", MatchNameReference("f")),
  382. "-",
  383. MatchPrefixOperator("not",
  384. MatchNameReference("g")))))),
  385. MatchExpressionStatement(MatchPrefixOperator(
  386. "++", MatchPrefixOperator("++", MatchNameReference("n")))),
  387. MatchExpressionStatement(MatchPostfixOperator(
  388. MatchPostfixOperator(MatchNameReference("n"), "++"), "++")),
  389. MatchExpressionStatement(MatchInfixOperator(
  390. MatchInfixOperator(MatchNameReference("a"), "and",
  391. MatchNameReference("b")),
  392. "and", MatchNameReference("c"))),
  393. MatchExpressionStatement(MatchInfixOperator(
  394. HasError,
  395. MatchInfixOperator(MatchNameReference("a"), "and",
  396. MatchNameReference("b")),
  397. "or", MatchNameReference("c"))),
  398. MatchExpressionStatement(MatchInfixOperator(
  399. HasError,
  400. MatchInfixOperator(MatchNameReference("a"), "or",
  401. MatchNameReference("b")),
  402. "and", MatchNameReference("c"))),
  403. MatchExpressionStatement(MatchInfixOperator(
  404. MatchInfixOperator(
  405. MatchPrefixOperator("not", MatchNameReference("a")),
  406. "and",
  407. MatchPrefixOperator("not", MatchNameReference("b"))),
  408. "and",
  409. MatchPrefixOperator("not", MatchNameReference("c"))))),
  410. MatchFileEnd()}));
  411. }
  412. TEST_F(ParseTreeTest, VariableDeclarations) {
  413. TokenizedBuffer tokens = GetTokenizedBuffer(
  414. "var Int v = 0;\n"
  415. "var Int w;\n"
  416. "fn F() {\n"
  417. " var String s = \"hello\";\n"
  418. "}");
  419. ParseTree tree = ParseTree::Parse(tokens, consumer);
  420. EXPECT_FALSE(tree.HasErrors());
  421. EXPECT_THAT(tree,
  422. MatchParseTreeNodes(
  423. {MatchVariableDeclaration(
  424. MatchNameReference("Int"), MatchDeclaredName("v"),
  425. MatchVariableInitializer(MatchLiteral("0")),
  426. MatchDeclarationEnd()),
  427. MatchVariableDeclaration(MatchNameReference("Int"),
  428. MatchDeclaredName("w"),
  429. MatchDeclarationEnd()),
  430. MatchFunctionWithBody(MatchVariableDeclaration(
  431. MatchNameReference("String"), MatchDeclaredName("s"),
  432. MatchVariableInitializer(MatchLiteral("\"hello\"")),
  433. MatchDeclarationEnd())),
  434. MatchFileEnd()}));
  435. }
  436. TEST_F(ParseTreeTest, IfNoElse) {
  437. TokenizedBuffer tokens = GetTokenizedBuffer(
  438. "fn F() {\n"
  439. " if (a)\n"
  440. " if (b)\n"
  441. " if (c)\n"
  442. " d;\n"
  443. "}");
  444. ParseTree tree = ParseTree::Parse(tokens, consumer);
  445. EXPECT_FALSE(tree.HasErrors());
  446. EXPECT_THAT(
  447. tree,
  448. MatchParseTreeNodes(
  449. {MatchFunctionWithBody(MatchIfStatement(
  450. MatchCondition(MatchNameReference("a"), MatchConditionEnd()),
  451. MatchIfStatement(
  452. MatchCondition(MatchNameReference("b"), MatchConditionEnd()),
  453. MatchIfStatement(
  454. MatchCondition(MatchNameReference("c"),
  455. MatchConditionEnd()),
  456. MatchExpressionStatement(MatchNameReference("d")))))),
  457. MatchFileEnd()}));
  458. }
  459. TEST_F(ParseTreeTest, IfElse) {
  460. TokenizedBuffer tokens = GetTokenizedBuffer(
  461. "fn F() {\n"
  462. " if (a)\n"
  463. " if (b)\n"
  464. " c;\n"
  465. " else\n"
  466. " d;\n"
  467. " else\n"
  468. " e;\n"
  469. " if (x) { G(1); }\n"
  470. " else if (x) { G(2); }\n"
  471. " else { G(3); }\n"
  472. "}");
  473. ParseTree tree = ParseTree::Parse(tokens, consumer);
  474. EXPECT_FALSE(tree.HasErrors());
  475. EXPECT_THAT(
  476. tree,
  477. MatchParseTreeNodes(
  478. {MatchFunctionWithBody(
  479. MatchIfStatement(
  480. MatchCondition(MatchNameReference("a"), MatchConditionEnd()),
  481. MatchIfStatement(
  482. MatchCondition(MatchNameReference("b"),
  483. MatchConditionEnd()),
  484. MatchExpressionStatement(MatchNameReference("c")),
  485. MatchIfStatementElse(),
  486. MatchExpressionStatement(MatchNameReference("d"))),
  487. MatchIfStatementElse(),
  488. MatchExpressionStatement(MatchNameReference("e"))),
  489. MatchIfStatement(
  490. MatchCondition(MatchNameReference("x"), MatchConditionEnd()),
  491. MatchCodeBlock(
  492. MatchExpressionStatement(MatchCallExpression(
  493. MatchNameReference("G"), MatchLiteral("1"),
  494. MatchCallExpressionEnd())),
  495. MatchCodeBlockEnd()),
  496. MatchIfStatementElse(),
  497. MatchIfStatement(
  498. MatchCondition(MatchNameReference("x"),
  499. MatchConditionEnd()),
  500. MatchCodeBlock(
  501. MatchExpressionStatement(MatchCallExpression(
  502. MatchNameReference("G"), MatchLiteral("2"),
  503. MatchCallExpressionEnd())),
  504. MatchCodeBlockEnd()),
  505. MatchIfStatementElse(),
  506. MatchCodeBlock(
  507. MatchExpressionStatement(MatchCallExpression(
  508. MatchNameReference("G"), MatchLiteral("3"),
  509. MatchCallExpressionEnd())),
  510. MatchCodeBlockEnd())))),
  511. MatchFileEnd()}));
  512. }
  513. TEST_F(ParseTreeTest, IfError) {
  514. TokenizedBuffer tokens = GetTokenizedBuffer(
  515. "fn F() {\n"
  516. " if a {}\n"
  517. " if () {}\n"
  518. " if (b c) {}\n"
  519. " if (d)\n"
  520. "}");
  521. ParseTree tree = ParseTree::Parse(tokens, consumer);
  522. EXPECT_TRUE(tree.HasErrors());
  523. EXPECT_THAT(
  524. tree,
  525. MatchParseTreeNodes(
  526. {MatchFunctionWithBody(
  527. MatchIfStatement(HasError, MatchNameReference("a"),
  528. MatchCodeBlock(MatchCodeBlockEnd())),
  529. MatchIfStatement(MatchCondition(HasError, MatchConditionEnd()),
  530. MatchCodeBlock(MatchCodeBlockEnd())),
  531. MatchIfStatement(
  532. MatchCondition(HasError, MatchNameReference("b"),
  533. MatchConditionEnd()),
  534. MatchCodeBlock(MatchCodeBlockEnd())),
  535. MatchIfStatement(HasError,
  536. MatchCondition(MatchNameReference("d"),
  537. MatchConditionEnd()))),
  538. MatchFileEnd()}));
  539. }
  540. TEST_F(ParseTreeTest, WhileBreakContinue) {
  541. TokenizedBuffer tokens = GetTokenizedBuffer(
  542. "fn F() {\n"
  543. " while (a) {\n"
  544. " if (b)\n"
  545. " break;\n"
  546. " if (c)\n"
  547. " continue;\n"
  548. "}");
  549. ParseTree tree = ParseTree::Parse(tokens, consumer);
  550. EXPECT_FALSE(tree.HasErrors());
  551. EXPECT_THAT(
  552. tree,
  553. MatchParseTreeNodes(
  554. {MatchFunctionWithBody(MatchWhileStatement(
  555. MatchCondition(MatchNameReference("a"), MatchConditionEnd()),
  556. MatchCodeBlock(
  557. MatchIfStatement(MatchCondition(MatchNameReference("b"),
  558. MatchConditionEnd()),
  559. MatchBreakStatement(MatchStatementEnd())),
  560. MatchIfStatement(
  561. MatchCondition(MatchNameReference("c"),
  562. MatchConditionEnd()),
  563. MatchContinueStatement(MatchStatementEnd())),
  564. MatchCodeBlockEnd()))),
  565. MatchFileEnd()}));
  566. }
  567. auto GetAndDropLine(llvm::StringRef& s) -> std::string {
  568. auto newline_offset = s.find_first_of('\n');
  569. llvm::StringRef line = s.slice(0, newline_offset);
  570. if (newline_offset != llvm::StringRef::npos) {
  571. s = s.substr(newline_offset + 1);
  572. } else {
  573. s = "";
  574. }
  575. return line.str();
  576. }
  577. TEST_F(ParseTreeTest, Printing) {
  578. TokenizedBuffer tokens = GetTokenizedBuffer("fn F();");
  579. ParseTree tree = ParseTree::Parse(tokens, consumer);
  580. EXPECT_FALSE(tree.HasErrors());
  581. std::string print_storage;
  582. llvm::raw_string_ostream print_stream(print_storage);
  583. tree.Print(print_stream);
  584. llvm::StringRef print = print_stream.str();
  585. EXPECT_THAT(GetAndDropLine(print), StrEq("["));
  586. EXPECT_THAT(GetAndDropLine(print),
  587. StrEq("{node_index: 4, kind: 'FunctionDeclaration', text: 'fn', "
  588. "subtree_size: 5, children: ["));
  589. EXPECT_THAT(GetAndDropLine(print),
  590. StrEq(" {node_index: 0, kind: 'DeclaredName', text: 'F'},"));
  591. EXPECT_THAT(GetAndDropLine(print),
  592. StrEq(" {node_index: 2, kind: 'ParameterList', text: '(', "
  593. "subtree_size: 2, children: ["));
  594. EXPECT_THAT(GetAndDropLine(print),
  595. StrEq(" {node_index: 1, kind: 'ParameterListEnd', "
  596. "text: ')'}]},"));
  597. EXPECT_THAT(GetAndDropLine(print),
  598. StrEq(" {node_index: 3, kind: 'DeclarationEnd', text: ';'}]},"));
  599. EXPECT_THAT(GetAndDropLine(print),
  600. StrEq("{node_index: 5, kind: 'FileEnd', text: ''},"));
  601. EXPECT_THAT(GetAndDropLine(print), StrEq("]"));
  602. EXPECT_TRUE(print.empty()) << print;
  603. }
  604. TEST_F(ParseTreeTest, PrintingAsYAML) {
  605. TokenizedBuffer tokens = GetTokenizedBuffer("fn F();");
  606. ParseTree tree = ParseTree::Parse(tokens, consumer);
  607. EXPECT_FALSE(tree.HasErrors());
  608. std::string print_output;
  609. llvm::raw_string_ostream print_stream(print_output);
  610. tree.Print(print_stream);
  611. print_stream.flush();
  612. // Parse the output into a YAML stream. This will print errors to stderr.
  613. llvm::SourceMgr source_manager;
  614. llvm::yaml::Stream yaml_stream(print_output, source_manager);
  615. auto di = yaml_stream.begin();
  616. auto* root_node = llvm::dyn_cast<llvm::yaml::SequenceNode>(di->getRoot());
  617. ASSERT_THAT(root_node, NotNull());
  618. // The root node is just an array of top-level parse nodes.
  619. auto ni = root_node->begin();
  620. auto ne = root_node->end();
  621. auto* node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ni);
  622. ASSERT_THAT(node, NotNull());
  623. auto nkvi = node->begin();
  624. auto nkve = node->end();
  625. EXPECT_THAT(&*nkvi, IsKeyValueScalars("node_index", "4"));
  626. ++nkvi;
  627. EXPECT_THAT(&*nkvi, IsKeyValueScalars("kind", "FunctionDeclaration"));
  628. ++nkvi;
  629. EXPECT_THAT(&*nkvi, IsKeyValueScalars("text", "fn"));
  630. ++nkvi;
  631. EXPECT_THAT(&*nkvi, IsKeyValueScalars("subtree_size", "5"));
  632. ++nkvi;
  633. auto* children_node = llvm::dyn_cast<llvm::yaml::KeyValueNode>(&*nkvi);
  634. ASSERT_THAT(children_node, NotNull());
  635. auto* children_key_node =
  636. llvm::dyn_cast<llvm::yaml::ScalarNode>(children_node->getKey());
  637. ASSERT_THAT(children_key_node, NotNull());
  638. EXPECT_THAT(children_key_node->getRawValue(), StrEq("children"));
  639. auto* children_value_node =
  640. llvm::dyn_cast<llvm::yaml::SequenceNode>(children_node->getValue());
  641. ASSERT_THAT(children_value_node, NotNull());
  642. auto ci = children_value_node->begin();
  643. auto ce = children_value_node->end();
  644. ASSERT_THAT(ci, Ne(ce));
  645. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  646. ASSERT_THAT(node, NotNull());
  647. auto ckvi = node->begin();
  648. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "0"));
  649. ++ckvi;
  650. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "DeclaredName"));
  651. ++ckvi;
  652. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", "F"));
  653. ++ckvi;
  654. EXPECT_THAT(ckvi, Eq(node->end()));
  655. ++ci;
  656. ASSERT_THAT(ci, Ne(ce));
  657. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  658. ASSERT_THAT(node, NotNull());
  659. ckvi = node->begin();
  660. auto ckve = node->end();
  661. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "2"));
  662. ++ckvi;
  663. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "ParameterList"));
  664. ++ckvi;
  665. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", "("));
  666. ++ckvi;
  667. EXPECT_THAT(&*ckvi, IsKeyValueScalars("subtree_size", "2"));
  668. ++ckvi;
  669. children_node = llvm::dyn_cast<llvm::yaml::KeyValueNode>(&*ckvi);
  670. ASSERT_THAT(children_node, NotNull());
  671. children_key_node =
  672. llvm::dyn_cast<llvm::yaml::ScalarNode>(children_node->getKey());
  673. ASSERT_THAT(children_key_node, NotNull());
  674. EXPECT_THAT(children_key_node->getRawValue(), StrEq("children"));
  675. children_value_node =
  676. llvm::dyn_cast<llvm::yaml::SequenceNode>(children_node->getValue());
  677. ASSERT_THAT(children_value_node, NotNull());
  678. auto c2_i = children_value_node->begin();
  679. auto c2_e = children_value_node->end();
  680. ASSERT_THAT(c2_i, Ne(c2_e));
  681. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*c2_i);
  682. ASSERT_THAT(node, NotNull());
  683. auto c2_kvi = node->begin();
  684. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("node_index", "1"));
  685. ++c2_kvi;
  686. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("kind", "ParameterListEnd"));
  687. ++c2_kvi;
  688. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("text", ")"));
  689. ++c2_kvi;
  690. EXPECT_THAT(c2_kvi, Eq(node->end()));
  691. ++c2_i;
  692. EXPECT_THAT(c2_i, Eq(c2_e));
  693. ++ckvi;
  694. EXPECT_THAT(ckvi, Eq(ckve));
  695. ++ci;
  696. ASSERT_THAT(ci, Ne(ce));
  697. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  698. ASSERT_THAT(node, NotNull());
  699. ckvi = node->begin();
  700. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "3"));
  701. ++ckvi;
  702. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "DeclarationEnd"));
  703. ++ckvi;
  704. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", ";"));
  705. ++ckvi;
  706. EXPECT_THAT(ckvi, Eq(node->end()));
  707. ++ci;
  708. EXPECT_THAT(ci, Eq(ce));
  709. ++nkvi;
  710. EXPECT_THAT(nkvi, Eq(nkve));
  711. ++ni;
  712. ASSERT_THAT(ni, Ne(ne));
  713. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ni);
  714. ASSERT_THAT(node, NotNull());
  715. nkvi = node->begin();
  716. EXPECT_THAT(&*nkvi, IsKeyValueScalars("node_index", "5"));
  717. ++nkvi;
  718. EXPECT_THAT(&*nkvi, IsKeyValueScalars("kind", "FileEnd"));
  719. ++nkvi;
  720. EXPECT_THAT(&*nkvi, IsKeyValueScalars("text", ""));
  721. ++nkvi;
  722. EXPECT_THAT(nkvi, Eq(node->end()));
  723. ++ni;
  724. EXPECT_THAT(ni, Eq(ne));
  725. ++di;
  726. EXPECT_THAT(di, Eq(yaml_stream.end()));
  727. }
  728. } // namespace
  729. } // namespace Carbon