format.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. #include "toolchain/format/format.h"
  5. #include "toolchain/lex/token_index.h"
  6. #include "toolchain/lex/tokenized_buffer.h"
  7. namespace Carbon::Format {
  8. // TODO: Add support for formatting line ranges (will need flags too).
  9. auto Format(const Lex::TokenizedBuffer& tokens, llvm::raw_ostream& out)
  10. -> bool {
  11. if (tokens.has_errors()) {
  12. // TODO: Error recovery.
  13. return false;
  14. }
  15. auto comments = tokens.comments();
  16. auto comment_it = comments.begin();
  17. llvm::ListSeparator sep(" ");
  18. for (auto token : tokens.tokens()) {
  19. while (comment_it != comments.end() &&
  20. tokens.IsAfterComment(token, *comment_it)) {
  21. // TODO: Fix newlines and indent.
  22. out << "\n" << tokens.GetCommentText(*comment_it) << "\n";
  23. ++comment_it;
  24. }
  25. switch (tokens.GetKind(token)) {
  26. case Lex::TokenKind::FileStart:
  27. break;
  28. case Lex::TokenKind::FileEnd:
  29. out << "\n";
  30. break;
  31. default:
  32. // TODO: More dependent formatting.
  33. out << sep << tokens.GetTokenText(token);
  34. break;
  35. }
  36. }
  37. return true;
  38. }
  39. } // namespace Carbon::Format