string_literal.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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_LEXER_STRING_LITERAL_H_
  5. #define CARBON_TOOLCHAIN_LEXER_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 {
  11. class LexedStringLiteral {
  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)
  19. -> std::optional<LexedStringLiteral>;
  20. // Expand any escape sequences in the given string literal and compute the
  21. // resulting value. This handles error recovery internally and cannot fail.
  22. auto ComputeValue(DiagnosticEmitter<const char*>& emitter) const
  23. -> std::string;
  24. // Get the text corresponding to this literal.
  25. [[nodiscard]] auto text() const -> llvm::StringRef { return text_; }
  26. // Determine whether this is a multi-line string literal.
  27. [[nodiscard]] auto is_multi_line() const -> bool { return multi_line_; }
  28. // Returns true if the string has a valid terminator.
  29. [[nodiscard]] auto is_terminated() const -> bool { return is_terminated_; }
  30. private:
  31. enum MultiLineKind { NotMultiLine, MultiLine, MultiLineWithDoubleQuotes };
  32. struct Introducer;
  33. explicit LexedStringLiteral(llvm::StringRef text, llvm::StringRef content,
  34. int hash_level, MultiLineKind multi_line,
  35. bool is_terminated)
  36. : text_(text),
  37. content_(content),
  38. hash_level_(hash_level),
  39. multi_line_(multi_line),
  40. is_terminated_(is_terminated) {}
  41. // The complete text of the string literal.
  42. llvm::StringRef text_;
  43. // The content of the literal. For a multi-line literal, this begins
  44. // immediately after the newline following the file type indicator, and ends
  45. // at the start of the closing `"""`. Leading whitespace is not removed from
  46. // either end.
  47. llvm::StringRef content_;
  48. // The number of `#`s preceding the opening `"` or `"""`.
  49. int hash_level_;
  50. // Whether this was a multi-line string literal.
  51. MultiLineKind multi_line_;
  52. // Whether the literal is valid, or should only be used for errors.
  53. bool is_terminated_;
  54. };
  55. } // namespace Carbon
  56. #endif // CARBON_TOOLCHAIN_LEXER_STRING_LITERAL_H_