meta.c 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Guile-GCC
  2. Copyright (C) 2012 Ludovic Courtès <ludo@gnu.org>
  3. This file is part of Guile-GCC.
  4. Guile-GCC is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile-GCC is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with Guile-GCC. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <stdlib.h>
  15. /* Define `describe', which generates code that describes the given
  16. structure. Note use of the `tree' EDSL, which allows code generation to
  17. be expressed concisely. */
  18. #pragma guile define describe " \
  19. (lambda (x) \
  20. (define var (identifier-string (decl-name x))) \
  21. (define (fmt t) \
  22. (cond ((integral-type? t) \"%d\") \
  23. ((and (pointer-type? t) \
  24. (integral-type? (tree-type t)) \
  25. (= 1 (int-size-in-bytes (tree-type t)))) \
  26. \"`%s'\") \
  27. ((pointer-type? t) \"%p\") \
  28. (else \"<unknown-type>\"))) \
  29. (for-each (lambda (f) \
  30. (let* ((print (built-in-decl BUILT_IN_PRINTF)) \
  31. (fname (decl-name f)) \
  32. (str (string-append \"field `\" \
  33. (identifier-string fname) \
  34. \"' of `\" var \"' is \" \
  35. (fmt (tree-type f)) \
  36. \"\\n\"))) \
  37. (add-statement \
  38. (tree %unknown-location \
  39. (print str (x dot f)))))) \
  40. (type-fields (tree-type x)))) \
  41. "
  42. struct foo { int x; const char *y; };
  43. struct bar { struct bar *next; int x; };
  44. int
  45. main ()
  46. {
  47. struct foo f = { 42, "hello" };
  48. struct bar b = { (void *) 0xdeadbeef, 77 };
  49. #pragma guile invoke describe f
  50. #pragma guile invoke describe b
  51. return EXIT_SUCCESS;
  52. }