resolve_unformed.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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_INTERPRETER_RESOLVE_UNFORMED_H_
  5. #define CARBON_EXPLORER_INTERPRETER_RESOLVE_UNFORMED_H_
  6. #include <string>
  7. #include <unordered_map>
  8. #include "explorer/ast/ast.h"
  9. #include "explorer/base/nonnull.h"
  10. #include "explorer/base/trace_stream.h"
  11. namespace Carbon {
  12. // Maps AST nodes to flow facts within a function.
  13. class FlowFacts {
  14. public:
  15. explicit FlowFacts(Nonnull<TraceStream*> trace_stream)
  16. : trace_stream_(trace_stream) {}
  17. enum class ActionType {
  18. // Adds a must-be-formed flow fact.
  19. // Used at `VariableDefinition` with initialization.
  20. AddInit,
  21. // Adds an unformed flow fact.
  22. // Used at `VariableDefinition` without initialization.
  23. AddUninit,
  24. // Marks an unformed flow fact as may-be-formed.
  25. // Used at AST nodes that potentially initializes a variable.
  26. Form,
  27. // Returns compilation error if the AST node is impossible to be formed.
  28. // Used at AST nodes that uses a variable.
  29. Check,
  30. // Used in traversing children nodes without an acion to take.
  31. None,
  32. };
  33. auto action_type_string(ActionType action) const -> std::string_view;
  34. // Take action on flow facts based on `ActionType`.
  35. auto TakeAction(Nonnull<const AstNode*> node, ActionType action,
  36. SourceLocation source_loc, const std::string& name)
  37. -> ErrorOr<Success>;
  38. private:
  39. enum class FormedState {
  40. MustBeFormed,
  41. MayBeFormed,
  42. Unformed,
  43. };
  44. // Aggregate information about a AstNode being analyzed.
  45. struct Fact {
  46. FormedState formed_state;
  47. };
  48. void AddFact(Nonnull<const AstNode*> node, const FormedState state) {
  49. CARBON_CHECK(facts_.find(node) == facts_.end());
  50. facts_.insert({node, {state}});
  51. }
  52. std::unordered_map<Nonnull<const AstNode*>, Fact> facts_;
  53. Nonnull<TraceStream*> trace_stream_;
  54. };
  55. // An intraprocedural forward analysis that checks the may-be-formed states on
  56. // local variables. Returns compilation error on usage of must-be-unformed
  57. // variables.
  58. auto ResolveUnformed(Nonnull<TraceStream*> trace_stream, const AST& ast)
  59. -> ErrorOr<Success>;
  60. } // namespace Carbon
  61. #endif // CARBON_EXPLORER_INTERPRETER_RESOLVE_UNFORMED_H_