lexer.lpp 13 KB

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