lexer.lpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  3. Exceptions. See /LICENSE for license information.
  4. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. */
  6. %{
  7. #include <cstdlib>
  8. #include "common/check.h"
  9. #include "common/error.h"
  10. #include "common/string_helpers.h"
  11. #include "explorer/syntax/parse_and_lex_context.h"
  12. #include "explorer/syntax/parser.h"
  13. #include "llvm/ADT/StringExtras.h"
  14. #include "llvm/Support/FormatVariadic.h"
  15. // Reads and returns a single character. Reports an error on EOF.
  16. auto ReadChar(yyscan_t yyscanner, Carbon::ParseAndLexContext& context) -> int;
  17. %}
  18. /* Turn off legacy bits we don't need. */
  19. %option noyywrap nounput nodefault
  20. %option reentrant
  21. /* Lexing a token immediately after consuming some whitespace. */
  22. %s AFTER_WHITESPACE
  23. /*
  24. * Lexing a token immediately after consuming an operand-ending token:
  25. * a closing bracket, identifier, or literal.
  26. */
  27. %s AFTER_OPERAND
  28. /* table-begin */
  29. ADDR "addr"
  30. ALIAS "alias"
  31. AMPERSAND "&"
  32. AND "and"
  33. API "api"
  34. ARROW "->"
  35. AS "as"
  36. AUTO "auto"
  37. AWAIT "__await"
  38. BOOL "Bool"
  39. BREAK "break"
  40. CASE "case"
  41. CHOICE "choice"
  42. CLASS "class"
  43. COLON ":"
  44. COLON_BANG ":!"
  45. COMMA ","
  46. CONTINUATION "__continuation"
  47. CONTINUATION_TYPE "__Continuation"
  48. CONTINUE "continue"
  49. DEFAULT "default"
  50. DOUBLE_ARROW "=>"
  51. ELSE "else"
  52. EQUAL "="
  53. EQUAL_EQUAL "=="
  54. EXTERNAL "external"
  55. FALSE "false"
  56. FN "fn"
  57. FN_TYPE "__Fn"
  58. FORALL "forall"
  59. IF "if"
  60. IMPL "impl"
  61. IMPORT "import"
  62. INTERFACE "interface"
  63. IS "is"
  64. LEFT_CURLY_BRACE "{"
  65. LEFT_PARENTHESIS "("
  66. LEFT_SQUARE_BRACKET "["
  67. LET "let"
  68. LIBRARY "library"
  69. MATCH "match"
  70. MINUS "-"
  71. NOT "not"
  72. OR "or"
  73. PACKAGE "package"
  74. PERIOD "."
  75. PLUS "+"
  76. RETURN "return"
  77. RIGHT_CURLY_BRACE "}"
  78. RIGHT_PARENTHESIS ")"
  79. RIGHT_SQUARE_BRACKET "]"
  80. RUN "__run"
  81. SELF "Self"
  82. SEMICOLON ";"
  83. SLASH "/"
  84. STRING "String"
  85. THEN "then"
  86. TRUE "true"
  87. TYPE "Type"
  88. UNDERSCORE "_"
  89. UNIMPL_EXAMPLE "__unimplemented_example_infix"
  90. VAR "var"
  91. WHERE "where"
  92. WHILE "while"
  93. /* table-end */
  94. /* This should be kept table-like, but isn't automatic due to spaces. */
  95. identifier [A-Za-z_][A-Za-z0-9_]*
  96. intrinsic_identifier __intrinsic_[A-Za-z0-9_]*
  97. sized_type_literal [iuf][1-9][0-9]*
  98. integer_literal [0-9]+
  99. horizontal_whitespace [ \t\r]
  100. whitespace [ \t\r\n]
  101. one_line_comment \/\/[^\n]*\n
  102. operand_start [(A-Za-z0-9_\"]
  103. /* Single-line string literals should reject vertical whitespace. */
  104. string_literal \"([^\\\"\n\v\f\r]|\\.)*\"
  105. %{
  106. // This macro is expanded immediately before each action specified below.
  107. //
  108. // Advances the current token position by yyleng columns without changing
  109. // the line number, and takes us out of the after-whitespace / after-operand
  110. // state.
  111. #define YY_USER_ACTION \
  112. context.current_token_position.columns(yyleng); \
  113. if (YY_START == AFTER_WHITESPACE || YY_START == AFTER_OPERAND) { \
  114. BEGIN(INITIAL); \
  115. }
  116. #define SIMPLE_TOKEN(name) \
  117. Carbon::Parser::make_##name(context.current_token_position);
  118. #define ARG_TOKEN(name, arg) \
  119. Carbon::Parser::make_##name(arg, context.current_token_position);
  120. %}
  121. %%
  122. %{
  123. // Code run each time yylex is called.
  124. // Begin with an empty token span starting where its previous end was.
  125. context.current_token_position.step();
  126. %}
  127. /* table-begin */
  128. {ADDR} { return SIMPLE_TOKEN(ADDR); }
  129. {ALIAS} { return SIMPLE_TOKEN(ALIAS); }
  130. {AMPERSAND} { return SIMPLE_TOKEN(AMPERSAND); }
  131. {AND} { return SIMPLE_TOKEN(AND); }
  132. {API} { return SIMPLE_TOKEN(API); }
  133. {ARROW} { return SIMPLE_TOKEN(ARROW); }
  134. {AS} { return SIMPLE_TOKEN(AS); }
  135. {AUTO} { return SIMPLE_TOKEN(AUTO); }
  136. {AWAIT} { return SIMPLE_TOKEN(AWAIT); }
  137. {BOOL} { return SIMPLE_TOKEN(BOOL); }
  138. {BREAK} { return SIMPLE_TOKEN(BREAK); }
  139. {CASE} { return SIMPLE_TOKEN(CASE); }
  140. {CHOICE} { return SIMPLE_TOKEN(CHOICE); }
  141. {CLASS} { return SIMPLE_TOKEN(CLASS); }
  142. {COLON_BANG} { return SIMPLE_TOKEN(COLON_BANG); }
  143. {COLON} { return SIMPLE_TOKEN(COLON); }
  144. {COMMA} { return SIMPLE_TOKEN(COMMA); }
  145. {CONTINUATION_TYPE} { return SIMPLE_TOKEN(CONTINUATION_TYPE); }
  146. {CONTINUATION} { return SIMPLE_TOKEN(CONTINUATION); }
  147. {CONTINUE} { return SIMPLE_TOKEN(CONTINUE); }
  148. {DEFAULT} { return SIMPLE_TOKEN(DEFAULT); }
  149. {DOUBLE_ARROW} { return SIMPLE_TOKEN(DOUBLE_ARROW); }
  150. {ELSE} { return SIMPLE_TOKEN(ELSE); }
  151. {EQUAL_EQUAL} { return SIMPLE_TOKEN(EQUAL_EQUAL); }
  152. {EQUAL} { return SIMPLE_TOKEN(EQUAL); }
  153. {EXTERNAL} { return SIMPLE_TOKEN(EXTERNAL); }
  154. {FALSE} { return SIMPLE_TOKEN(FALSE); }
  155. {FN_TYPE} { return SIMPLE_TOKEN(FN_TYPE); }
  156. {FN} { return SIMPLE_TOKEN(FN); }
  157. {FORALL} { return SIMPLE_TOKEN(FORALL); }
  158. {IF} { return SIMPLE_TOKEN(IF); }
  159. {IMPL} { return SIMPLE_TOKEN(IMPL); }
  160. {IMPORT} { return SIMPLE_TOKEN(IMPORT); }
  161. {INTERFACE} { return SIMPLE_TOKEN(INTERFACE); }
  162. {IS} { return SIMPLE_TOKEN(IS); }
  163. {LEFT_CURLY_BRACE} { return SIMPLE_TOKEN(LEFT_CURLY_BRACE); }
  164. {LEFT_PARENTHESIS} { return SIMPLE_TOKEN(LEFT_PARENTHESIS); }
  165. {LEFT_SQUARE_BRACKET} { return SIMPLE_TOKEN(LEFT_SQUARE_BRACKET); }
  166. {LET} { return SIMPLE_TOKEN(LET); }
  167. {LIBRARY} { return SIMPLE_TOKEN(LIBRARY); }
  168. {MATCH} { return SIMPLE_TOKEN(MATCH); }
  169. {MINUS} { return SIMPLE_TOKEN(MINUS); }
  170. {NOT} { return SIMPLE_TOKEN(NOT); }
  171. {OR} { return SIMPLE_TOKEN(OR); }
  172. {PACKAGE} { return SIMPLE_TOKEN(PACKAGE); }
  173. {PERIOD} { return SIMPLE_TOKEN(PERIOD); }
  174. {PLUS} { return SIMPLE_TOKEN(PLUS); }
  175. {RETURN} { return SIMPLE_TOKEN(RETURN); }
  176. {RUN} { return SIMPLE_TOKEN(RUN); }
  177. {SELF} { return SIMPLE_TOKEN(SELF); }
  178. {SEMICOLON} { return SIMPLE_TOKEN(SEMICOLON); }
  179. {SLASH} { return SIMPLE_TOKEN(SLASH); }
  180. {STRING} { return SIMPLE_TOKEN(STRING); }
  181. {THEN} { return SIMPLE_TOKEN(THEN); }
  182. {TRUE} { return SIMPLE_TOKEN(TRUE); }
  183. {TYPE} { return SIMPLE_TOKEN(TYPE); }
  184. {UNDERSCORE} { return SIMPLE_TOKEN(UNDERSCORE); }
  185. {UNIMPL_EXAMPLE} { return SIMPLE_TOKEN(UNIMPL_EXAMPLE); }
  186. {VAR} { return SIMPLE_TOKEN(VAR); }
  187. {WHERE} { return SIMPLE_TOKEN(WHERE); }
  188. {WHILE} { return SIMPLE_TOKEN(WHILE); }
  189. /* table-end */
  190. /* More modern Bisons provide make_EOF. */
  191. <<EOF>> { return SIMPLE_TOKEN(END_OF_FILE); }
  192. {RIGHT_PARENTHESIS} {
  193. BEGIN(AFTER_OPERAND);
  194. return SIMPLE_TOKEN(RIGHT_PARENTHESIS);
  195. }
  196. {RIGHT_CURLY_BRACE} {
  197. BEGIN(AFTER_OPERAND);
  198. return SIMPLE_TOKEN(RIGHT_CURLY_BRACE);
  199. }
  200. {RIGHT_SQUARE_BRACKET} {
  201. BEGIN(AFTER_OPERAND);
  202. return SIMPLE_TOKEN(RIGHT_SQUARE_BRACKET);
  203. }
  204. /*
  205. * For a `*` operator, we look at whitespace and local context to determine the
  206. * arity and fixity. There are two ways to write a binary operator:
  207. *
  208. * 1) Whitespace on both sides.
  209. * 2) Whitespace on neither side, and the previous token is considered to be
  210. * the end of an operand, and the next token is considered to be the start
  211. * of an operand.
  212. *
  213. * Otherwise, the operator is unary, but we also check for whitespace to help
  214. * the parser enforce the rule that whitespace is not permitted between the
  215. * operator and its operand, leading to three more cases:
  216. *
  217. * 3) Whitespace before (but implicitly not after, because that would give a
  218. * longer match and hit case 1): this can only be a prefix operator.
  219. * 4) Whitespace after and not before: this can only be a postfix operator.
  220. * 5) No whitespace on either side (otherwise the longest match would take us
  221. * to case 4): this is a unary operator and could be either prefix or
  222. * postfix.
  223. */
  224. /* `*` operator case 1: */
  225. <AFTER_WHITESPACE>"*"{whitespace}+ {
  226. BEGIN(AFTER_WHITESPACE);
  227. return SIMPLE_TOKEN(BINARY_STAR);
  228. }
  229. /* `*` operator case 2: */
  230. <AFTER_OPERAND>"*"/{operand_start} { return SIMPLE_TOKEN(BINARY_STAR); }
  231. /* `*` operator case 3: */
  232. <AFTER_WHITESPACE>"*" { return SIMPLE_TOKEN(PREFIX_STAR); }
  233. /* `*` operator case 4: */
  234. <INITIAL,AFTER_OPERAND>"*"{whitespace}+ {
  235. BEGIN(AFTER_WHITESPACE);
  236. return SIMPLE_TOKEN(POSTFIX_STAR);
  237. }
  238. /* `*` operator case 5: */
  239. <INITIAL,AFTER_OPERAND>"*" { return SIMPLE_TOKEN(UNARY_STAR); }
  240. {sized_type_literal} {
  241. BEGIN(AFTER_OPERAND);
  242. return ARG_TOKEN(sized_type_literal, yytext);
  243. }
  244. {intrinsic_identifier} {
  245. BEGIN(AFTER_OPERAND);
  246. Carbon::ErrorOr<Carbon::IntrinsicExpression::Intrinsic> intrinsic =
  247. Carbon::IntrinsicExpression::FindIntrinsic(yytext, context.source_loc());
  248. if (intrinsic.ok()) {
  249. return ARG_TOKEN(intrinsic_identifier, *intrinsic);
  250. } else {
  251. return context.RecordSyntaxError(intrinsic.error().message());
  252. }
  253. }
  254. {identifier} {
  255. BEGIN(AFTER_OPERAND);
  256. return ARG_TOKEN(identifier, yytext);
  257. }
  258. {integer_literal} {
  259. BEGIN(AFTER_OPERAND);
  260. int val = 0;
  261. if (!llvm::to_integer(yytext, val)) {
  262. return context.RecordSyntaxError(
  263. llvm::formatv("Invalid integer literal: {0}", yytext));
  264. }
  265. return ARG_TOKEN(integer_literal, val);
  266. }
  267. {string_literal} {
  268. llvm::StringRef str(yytext);
  269. CARBON_CHECK(str.consume_front("\"") && str.consume_back("\""));
  270. std::optional<std::string> unescaped = Carbon::UnescapeStringLiteral(str);
  271. if (unescaped == std::nullopt) {
  272. return context.RecordSyntaxError(
  273. llvm::formatv("Invalid escaping in string: {0}", yytext));
  274. }
  275. return ARG_TOKEN(string_literal, *unescaped);
  276. }
  277. \"\"\" {
  278. // Block string literal.
  279. std::string s(yytext);
  280. // Scans for the closing """, checking for possible escape sequences
  281. // like \""".
  282. for (;;) {
  283. int c = ReadChar(yyscanner, context);
  284. if (c <= 0) {
  285. return SIMPLE_TOKEN(END_OF_FILE);
  286. }
  287. s.push_back(c);
  288. if (c != '"' && c != '\\') {
  289. continue;
  290. }
  291. if (c == '\\') {
  292. // \" in \""" is not a terminator.
  293. c = ReadChar(yyscanner, context);
  294. if (c <= 0) {
  295. return SIMPLE_TOKEN(END_OF_FILE);
  296. }
  297. s.push_back(c);
  298. continue;
  299. }
  300. c = ReadChar(yyscanner, context);
  301. if (c <= 0) {
  302. return SIMPLE_TOKEN(END_OF_FILE);
  303. }
  304. s.push_back(c);
  305. if (c != '"') {
  306. continue;
  307. }
  308. c = ReadChar(yyscanner, context);
  309. if (c <= 0) {
  310. return SIMPLE_TOKEN(END_OF_FILE);
  311. }
  312. s.push_back(c);
  313. if (c == '"') {
  314. break;
  315. }
  316. }
  317. Carbon::ErrorOr<std::string> block_string =
  318. Carbon::ParseBlockStringLiteral(s);
  319. if (!block_string.ok()) {
  320. return context.RecordSyntaxError(llvm::formatv(
  321. "Invalid block string: {0}", block_string.error().message()));
  322. }
  323. return ARG_TOKEN(string_literal, *block_string);
  324. }
  325. {one_line_comment} {
  326. // Advance end by 1 line, resetting the column to zero.
  327. context.current_token_position.lines(1);
  328. // Make the span empty by setting start to end.
  329. context.current_token_position.step();
  330. }
  331. {horizontal_whitespace}+ {
  332. // Make the span empty by setting start to end.
  333. context.current_token_position.step();
  334. BEGIN(AFTER_WHITESPACE);
  335. }
  336. \n+ {
  337. // Advance end by yyleng lines, resetting the column to zero.
  338. context.current_token_position.lines(yyleng);
  339. // Make the span empty by setting start to end.
  340. context.current_token_position.step();
  341. BEGIN(AFTER_WHITESPACE);
  342. }
  343. . {
  344. return context.RecordSyntaxError(
  345. llvm::formatv("invalid character '\\x{0}' in source file.",
  346. llvm::toHex(llvm::StringRef(yytext, 1))));
  347. }
  348. %%
  349. auto ReadChar(yyscan_t yyscanner, Carbon::ParseAndLexContext& context) -> int {
  350. const int c = yyinput(yyscanner);
  351. if (c <= 0) {
  352. context.RecordSyntaxError("Unexpected end of file");
  353. }
  354. return c;
  355. }