re2_playground.carbon 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. import Cpp library "llvm/LineEditor/LineEditor.h";
  5. import Cpp library "llvm/Support/raw_ostream.h";
  6. import Cpp library "re2/re2.h";
  7. import Cpp inline "using OptionalString = std::optional<std::string>;";
  8. import Cpp inline "std::string_view AsStringView(const std::string &s) { return s; }";
  9. import Core library "io";
  10. class RE2 {
  11. extend adapt Cpp.re2.RE2;
  12. fn Make(re: str) -> Self {
  13. return RE2(re) as Self;
  14. }
  15. fn Match[self: Self](text: str) -> bool {
  16. return FullMatch(text, self as Cpp.re2.RE2);
  17. }
  18. }
  19. impl str as Core.ImplicitAs(Cpp.llvm.StringRef) {
  20. fn Convert[self: Self]() -> Cpp.llvm.StringRef {
  21. return Cpp.llvm.StringRef.StringRef(self);
  22. }
  23. }
  24. fn Print(var s: str) {
  25. *Cpp.llvm.outs() << s;
  26. }
  27. fn Run() -> i32 {
  28. var editor: Cpp.llvm.LineEditor = Cpp.llvm.LineEditor.LineEditor("re2_playground");
  29. editor.setPrompt(Cpp.std.string.basic_string("re2> "));
  30. Print('''
  31. Usage:
  32. /regex/ -- sets the current regular expression to regex
  33. anything else -- matches the entered text against the specified regex
  34. ''');
  35. var re: RE2 = RE2.Make("^a*$");
  36. while (true) {
  37. var line: Cpp.OptionalString = editor.readLine();
  38. if (not line.has_value()) {
  39. break;
  40. }
  41. if (line.value()->starts_with("/") and line.value()->ends_with("/")) {
  42. re = RE2.Make(Cpp.AsStringView(line.value()->substr(1, line.value()->size() - 2)));
  43. continue;
  44. }
  45. if (re.Match(Cpp.AsStringView(*line.value()))) {
  46. Print("Match\n");
  47. } else {
  48. Print("No match\n");
  49. }
  50. }
  51. return 0;
  52. }