lexer.lpp 13 KB

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