parse_tree_test.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. auto GetAndDropLine(llvm::StringRef& s) -> std::string {
  447. auto newline_offset = s.find_first_of('\n');
  448. llvm::StringRef line = s.slice(0, newline_offset);
  449. if (newline_offset != llvm::StringRef::npos) {
  450. s = s.substr(newline_offset + 1);
  451. } else {
  452. s = "";
  453. }
  454. return line.str();
  455. }
  456. TEST_F(ParseTreeTest, Printing) {
  457. TokenizedBuffer tokens = GetTokenizedBuffer("fn F();");
  458. ParseTree tree = ParseTree::Parse(tokens, consumer);
  459. EXPECT_FALSE(tree.HasErrors());
  460. std::string print_storage;
  461. llvm::raw_string_ostream print_stream(print_storage);
  462. tree.Print(print_stream);
  463. llvm::StringRef print = print_stream.str();
  464. EXPECT_THAT(GetAndDropLine(print), StrEq("["));
  465. EXPECT_THAT(GetAndDropLine(print),
  466. StrEq("{node_index: 4, kind: 'FunctionDeclaration', text: 'fn', "
  467. "subtree_size: 5, children: ["));
  468. EXPECT_THAT(GetAndDropLine(print),
  469. StrEq(" {node_index: 0, kind: 'DeclaredName', text: 'F'},"));
  470. EXPECT_THAT(GetAndDropLine(print),
  471. StrEq(" {node_index: 2, kind: 'ParameterList', text: '(', "
  472. "subtree_size: 2, children: ["));
  473. EXPECT_THAT(GetAndDropLine(print),
  474. StrEq(" {node_index: 1, kind: 'ParameterListEnd', "
  475. "text: ')'}]},"));
  476. EXPECT_THAT(GetAndDropLine(print),
  477. StrEq(" {node_index: 3, kind: 'DeclarationEnd', text: ';'}]},"));
  478. EXPECT_THAT(GetAndDropLine(print),
  479. StrEq("{node_index: 5, kind: 'FileEnd', text: ''},"));
  480. EXPECT_THAT(GetAndDropLine(print), StrEq("]"));
  481. EXPECT_TRUE(print.empty()) << print;
  482. }
  483. TEST_F(ParseTreeTest, PrintingAsYAML) {
  484. TokenizedBuffer tokens = GetTokenizedBuffer("fn F();");
  485. ParseTree tree = ParseTree::Parse(tokens, consumer);
  486. EXPECT_FALSE(tree.HasErrors());
  487. std::string print_output;
  488. llvm::raw_string_ostream print_stream(print_output);
  489. tree.Print(print_stream);
  490. print_stream.flush();
  491. // Parse the output into a YAML stream. This will print errors to stderr.
  492. llvm::SourceMgr source_manager;
  493. llvm::yaml::Stream yaml_stream(print_output, source_manager);
  494. auto di = yaml_stream.begin();
  495. auto* root_node = llvm::dyn_cast<llvm::yaml::SequenceNode>(di->getRoot());
  496. ASSERT_THAT(root_node, NotNull());
  497. // The root node is just an array of top-level parse nodes.
  498. auto ni = root_node->begin();
  499. auto ne = root_node->end();
  500. auto* node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ni);
  501. ASSERT_THAT(node, NotNull());
  502. auto nkvi = node->begin();
  503. auto nkve = node->end();
  504. EXPECT_THAT(&*nkvi, IsKeyValueScalars("node_index", "4"));
  505. ++nkvi;
  506. EXPECT_THAT(&*nkvi, IsKeyValueScalars("kind", "FunctionDeclaration"));
  507. ++nkvi;
  508. EXPECT_THAT(&*nkvi, IsKeyValueScalars("text", "fn"));
  509. ++nkvi;
  510. EXPECT_THAT(&*nkvi, IsKeyValueScalars("subtree_size", "5"));
  511. ++nkvi;
  512. auto* children_node = llvm::dyn_cast<llvm::yaml::KeyValueNode>(&*nkvi);
  513. ASSERT_THAT(children_node, NotNull());
  514. auto* children_key_node =
  515. llvm::dyn_cast<llvm::yaml::ScalarNode>(children_node->getKey());
  516. ASSERT_THAT(children_key_node, NotNull());
  517. EXPECT_THAT(children_key_node->getRawValue(), StrEq("children"));
  518. auto* children_value_node =
  519. llvm::dyn_cast<llvm::yaml::SequenceNode>(children_node->getValue());
  520. ASSERT_THAT(children_value_node, NotNull());
  521. auto ci = children_value_node->begin();
  522. auto ce = children_value_node->end();
  523. ASSERT_THAT(ci, Ne(ce));
  524. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  525. ASSERT_THAT(node, NotNull());
  526. auto ckvi = node->begin();
  527. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "0"));
  528. ++ckvi;
  529. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "DeclaredName"));
  530. ++ckvi;
  531. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", "F"));
  532. ++ckvi;
  533. EXPECT_THAT(ckvi, Eq(node->end()));
  534. ++ci;
  535. ASSERT_THAT(ci, Ne(ce));
  536. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  537. ASSERT_THAT(node, NotNull());
  538. ckvi = node->begin();
  539. auto ckve = node->end();
  540. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "2"));
  541. ++ckvi;
  542. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "ParameterList"));
  543. ++ckvi;
  544. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", "("));
  545. ++ckvi;
  546. EXPECT_THAT(&*ckvi, IsKeyValueScalars("subtree_size", "2"));
  547. ++ckvi;
  548. children_node = llvm::dyn_cast<llvm::yaml::KeyValueNode>(&*ckvi);
  549. ASSERT_THAT(children_node, NotNull());
  550. children_key_node =
  551. llvm::dyn_cast<llvm::yaml::ScalarNode>(children_node->getKey());
  552. ASSERT_THAT(children_key_node, NotNull());
  553. EXPECT_THAT(children_key_node->getRawValue(), StrEq("children"));
  554. children_value_node =
  555. llvm::dyn_cast<llvm::yaml::SequenceNode>(children_node->getValue());
  556. ASSERT_THAT(children_value_node, NotNull());
  557. auto c2_i = children_value_node->begin();
  558. auto c2_e = children_value_node->end();
  559. ASSERT_THAT(c2_i, Ne(c2_e));
  560. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*c2_i);
  561. ASSERT_THAT(node, NotNull());
  562. auto c2_kvi = node->begin();
  563. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("node_index", "1"));
  564. ++c2_kvi;
  565. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("kind", "ParameterListEnd"));
  566. ++c2_kvi;
  567. EXPECT_THAT(&*c2_kvi, IsKeyValueScalars("text", ")"));
  568. ++c2_kvi;
  569. EXPECT_THAT(c2_kvi, Eq(node->end()));
  570. ++c2_i;
  571. EXPECT_THAT(c2_i, Eq(c2_e));
  572. ++ckvi;
  573. EXPECT_THAT(ckvi, Eq(ckve));
  574. ++ci;
  575. ASSERT_THAT(ci, Ne(ce));
  576. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ci);
  577. ASSERT_THAT(node, NotNull());
  578. ckvi = node->begin();
  579. EXPECT_THAT(&*ckvi, IsKeyValueScalars("node_index", "3"));
  580. ++ckvi;
  581. EXPECT_THAT(&*ckvi, IsKeyValueScalars("kind", "DeclarationEnd"));
  582. ++ckvi;
  583. EXPECT_THAT(&*ckvi, IsKeyValueScalars("text", ";"));
  584. ++ckvi;
  585. EXPECT_THAT(ckvi, Eq(node->end()));
  586. ++ci;
  587. EXPECT_THAT(ci, Eq(ce));
  588. ++nkvi;
  589. EXPECT_THAT(nkvi, Eq(nkve));
  590. ++ni;
  591. ASSERT_THAT(ni, Ne(ne));
  592. node = llvm::dyn_cast<llvm::yaml::MappingNode>(&*ni);
  593. ASSERT_THAT(node, NotNull());
  594. nkvi = node->begin();
  595. EXPECT_THAT(&*nkvi, IsKeyValueScalars("node_index", "5"));
  596. ++nkvi;
  597. EXPECT_THAT(&*nkvi, IsKeyValueScalars("kind", "FileEnd"));
  598. ++nkvi;
  599. EXPECT_THAT(&*nkvi, IsKeyValueScalars("text", ""));
  600. ++nkvi;
  601. EXPECT_THAT(nkvi, Eq(node->end()));
  602. ++ni;
  603. EXPECT_THAT(ni, Eq(ne));
  604. ++di;
  605. EXPECT_THAT(di, Eq(yaml_stream.end()));
  606. }
  607. } // namespace
  608. } // namespace Carbon