parse_tree_test.cpp 34 KB

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