declaration.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 "executable_semantics/ast/declaration.h"
  5. #include <iostream>
  6. namespace Carbon {
  7. auto MakeFunDecl(FunctionDefinition* f) -> Declaration* {
  8. auto* d = new Declaration();
  9. d->tag = DeclarationKind::FunctionDeclaration;
  10. d->u.fun_def = f;
  11. return d;
  12. }
  13. auto MakeStructDecl(int line_num, std::string name, std::list<Member*>* members)
  14. -> Declaration* {
  15. auto* d = new Declaration();
  16. d->tag = DeclarationKind::StructDeclaration;
  17. d->u.struct_def = new StructDefinition();
  18. d->u.struct_def->line_num = line_num;
  19. d->u.struct_def->name = new std::string(std::move(name));
  20. d->u.struct_def->members = members;
  21. return d;
  22. }
  23. auto MakeChoiceDecl(int line_num, std::string name,
  24. std::list<std::pair<std::string, Expression*>>* alts)
  25. -> Declaration* {
  26. auto* d = new Declaration();
  27. d->tag = DeclarationKind::ChoiceDeclaration;
  28. d->u.choice_def.line_num = line_num;
  29. d->u.choice_def.name = new std::string(std::move(name));
  30. d->u.choice_def.alternatives = alts;
  31. return d;
  32. }
  33. void PrintDecl(Declaration* d) {
  34. switch (d->tag) {
  35. case DeclarationKind::FunctionDeclaration:
  36. PrintFunDef(d->u.fun_def);
  37. break;
  38. case DeclarationKind::StructDeclaration:
  39. std::cout << "struct " << *d->u.struct_def->name << " {" << std::endl;
  40. for (auto& member : *d->u.struct_def->members) {
  41. PrintMember(member);
  42. }
  43. std::cout << "}" << std::endl;
  44. break;
  45. case DeclarationKind::ChoiceDeclaration:
  46. std::cout << "choice " << *d->u.choice_def.name << " {" << std::endl;
  47. for (auto& alternative : *d->u.choice_def.alternatives) {
  48. std::cout << "alt " << alternative.first << " ";
  49. PrintExp(alternative.second);
  50. std::cout << ";" << std::endl;
  51. }
  52. std::cout << "}" << std::endl;
  53. break;
  54. }
  55. }
  56. } // namespace Carbon