lexer.lpp 13 KB

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