string_literal.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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_TOOLCHAIN_LEX_STRING_LITERAL_H_
  5. #define CARBON_TOOLCHAIN_LEX_STRING_LITERAL_H_
  6. #include <optional>
  7. #include <string>
  8. #include "llvm/ADT/StringRef.h"
  9. #include "toolchain/diagnostics/diagnostic_emitter.h"
  10. namespace Carbon::Lex {
  11. class StringLiteral {
  12. public:
  13. // Extract a string literal token from the given text, if it has a suitable
  14. // form. Returning std::nullopt indicates no string literal was found;
  15. // returning an invalid literal indicates a string prefix was found, but it's
  16. // malformed and is returning a partial string literal to assist error
  17. // construction.
  18. static auto Lex(llvm::StringRef source_text) -> std::optional<StringLiteral>;
  19. // Expand any escape sequences in the given string literal and compute the
  20. // resulting value. This handles error recovery internally and cannot fail.
  21. auto ComputeValue(DiagnosticEmitter<const char*>& emitter) const
  22. -> std::string;
  23. // Get the text corresponding to this literal.
  24. [[nodiscard]] auto text() const -> llvm::StringRef { return text_; }
  25. // Determine whether this is a multi-line string literal.
  26. [[nodiscard]] auto is_multi_line() const -> bool { return multi_line_; }
  27. // Returns true if the string has a valid terminator.
  28. [[nodiscard]] auto is_terminated() const -> bool { return is_terminated_; }
  29. private:
  30. enum MultiLineKind : int8_t {
  31. NotMultiLine,
  32. MultiLine,
  33. MultiLineWithDoubleQuotes
  34. };
  35. struct Introducer;
  36. explicit StringLiteral(llvm::StringRef text, llvm::StringRef content,
  37. int hash_level, MultiLineKind multi_line,
  38. bool is_terminated)
  39. : text_(text),
  40. content_(content),
  41. hash_level_(hash_level),
  42. multi_line_(multi_line),
  43. is_terminated_(is_terminated) {}
  44. // The complete text of the string literal.
  45. llvm::StringRef text_;
  46. // The content of the literal. For a multi-line literal, this begins
  47. // immediately after the newline following the file type indicator, and ends
  48. // at the start of the closing `"""`. Leading whitespace is not removed from
  49. // either end.
  50. llvm::StringRef content_;
  51. // The number of `#`s preceding the opening `"` or `"""`.
  52. int hash_level_;
  53. // Whether this was a multi-line string literal.
  54. MultiLineKind multi_line_;
  55. // Whether the literal is valid, or should only be used for errors.
  56. bool is_terminated_;
  57. };
  58. } // namespace Carbon::Lex
  59. #endif // CARBON_TOOLCHAIN_LEX_STRING_LITERAL_H_