parse_and_lex_context.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #ifndef CARBON_EXPLORER_SYNTAX_PARSE_AND_LEX_CONTEXT_H_
  5. #define CARBON_EXPLORER_SYNTAX_PARSE_AND_LEX_CONTEXT_H_
  6. #include <variant>
  7. #include "explorer/ast/ast.h"
  8. #include "explorer/base/source_location.h"
  9. #include "explorer/syntax/parser.h" // from parser.ypp
  10. namespace Carbon {
  11. // The state and functionality that is threaded "globally" through the
  12. // lexing/parsing process.
  13. class ParseAndLexContext {
  14. public:
  15. // Creates an instance analyzing the given input file.
  16. ParseAndLexContext(Nonnull<const std::string*> input_file_name,
  17. FileKind file_kind, bool parser_debug)
  18. : input_file_name_(input_file_name),
  19. file_kind_(file_kind),
  20. parser_debug_(parser_debug) {}
  21. // Formats ands records a lexing oor parsing error. Returns an error token as
  22. // a convenience.
  23. auto RecordSyntaxError(Error error) -> Parser::symbol_type;
  24. auto RecordSyntaxError(const std::string& message) -> Parser::symbol_type;
  25. auto source_loc() const -> SourceLocation {
  26. return SourceLocation(input_file_name_,
  27. static_cast<int>(current_token_position.begin.line),
  28. file_kind_);
  29. }
  30. auto parser_debug() const -> bool { return parser_debug_; }
  31. // The source range of the token being (or just) lex'd.
  32. location current_token_position;
  33. auto take_errors() -> std::vector<Error> {
  34. std::vector<Error> errors = std::move(errors_);
  35. errors_.clear();
  36. return errors;
  37. }
  38. private:
  39. // A path to the file processed, relative to the current working directory
  40. // when *this is called.
  41. Nonnull<const std::string*> input_file_name_;
  42. // The kind of file being processed.
  43. FileKind file_kind_;
  44. bool parser_debug_;
  45. std::vector<Error> errors_;
  46. };
  47. } // namespace Carbon
  48. // Gives flex the yylex prototype we want.
  49. #define YY_DECL \
  50. auto yylex(Carbon::Nonnull<Carbon::Arena*> /*arena*/, yyscan_t yyscanner, \
  51. Carbon::ParseAndLexContext& context) \
  52. -> Carbon::Parser::symbol_type
  53. // Declares yylex for the parser's sake.
  54. YY_DECL;
  55. #endif // CARBON_EXPLORER_SYNTAX_PARSE_AND_LEX_CONTEXT_H_