parse_tree_test.cpp 35 KB

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