Geen cache-versie.

Caching uitgeschakeld. Standaardinstelling voor deze pagina:ingeschakeld (code LNG204)
Als het scherm te langzaam is, kunt u de gebruikersmodus uitschakelen om de cacheversie te bekijken.

Générer une image d'un arbre et de ses nœuds

En programmation, nous manipulons souvent des arbres et des graphes, et il vient toujours un moment où nous souhaitons obtenir un affichage de la structure de l'arbre ou du graphe, que ce soit pour assurer la traçabilité (debugging), ou pour présenter la structure à d'autres personnes.

Nous pouvons utiliser l'outil Graphvizref 1  pour afficher la structure d'un arbre sous forme d'image.

Exemple d'image de structure de l'arbre

AST d'une fonction main LSD010

Voici le code qui à été analysé par le compilateur LSD010 pour afficher cette image de l'arbre.

  1. void main()
  2. {
  3. {
  4. integer k;
  5. boolean b;
  6. }
  7. k=2;
  8. b=3<k;
  9. }

Code utilisé pour afficher l'arbre

L'exemple suivant nous montre le code en langage C qui permet d'afficher une image des nœuds de l'arbre syntaxique abstrait généré pour le compilateur LSD010 développé dans le cadre du cours de syntaxe et sémantiqueref 2

  1. /*
  2.  * graphVizHelper.h : Helper for the graphViz tool (generation of images from a tree)
  3.  * @see http://www.graphviz.org/doc/info/command.html
  4.  * Part of the compiler project for LSD10 language
  5.  * Gaudry Stéphane
  6.  * More information on http://www.gaudry.be/programmer-arbre-image-noeuds.html
  7.  */
  8. #ifndef GRAPHVIZ_HELPER_H
  9. #define GRAPHVIZ_HELPER_H
  10.  
  11. #define GRAPHVIZ_CONFIG_FILE "astLSD10.dot"
  12.  
  13. /**
  14. * Generates an image of the AST into the current directory
  15. */
  16. void printGraph();
  17.  
  18. //void printGraph(char *xmlFileName, char *graphFileName);
  19. #endif
  1. /*
  2.  * graphVizHelper.c : Helper for the graphViz tool (generation of images from a tree)
  3.  * @see http://www.graphviz.org/doc/info/command.html
  4.  * Part of the compiler project for LSD10 language
  5.  * Gaudry Stéphane
  6.  * More information on http://www.gaudry.be/programmer-arbre-image-noeuds.html
  7.  */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include "common.h"
  13. #include "graphVizHelper.h"
  14. #include "y.tab.h"
  15. #if(VERBOSE_LEVEL<=DEB_E)
  16. #include <errno.h>
  17. #endif
  18. extern AstNode *rootNode;
  19.  
  20. /*
  21.  * **********************************************************
  22.  * Internal business
  23.  * **********************************************************
  24.  */
  25.  
  26. #define GRAPH_RIGHT 0
  27. #define GRAPH_LEFT 1
  28. #define GRAPH_ROOT -1
  29.  
  30. int isGraphVisInstalled()
  31. {
  32. return 1;//todo : get it dynamically
  33. }
  34.  
  35. /**
  36.  * http://www.graphviz.org/doc/info/command.html
  37.  */
  38. void generateImage(char *dotFileName)
  39. {
  40. time_t now;
  41. struct tm *timeinfo;
  42.  
  43. now = time(NULL);//time ( &now );
  44. timeinfo = localtime ( &now );
  45.  
  46. char commandString[100];
  47. //todo : set the timeinfo int values on a 2 digits format
  48. commandString,
  49. "%slsd10_Img%d%d%d%d%d%d.jpg %s",
  50. "dot -Tjpg -o",
  51. timeinfo->tm_year+1900,
  52. timeinfo->tm_mon+1,
  53. timeinfo->tm_mday,
  54. timeinfo->tm_hour,
  55. timeinfo->tm_min,
  56. timeinfo->tm_sec,
  57. dotFileName);
  58. printf("\n;\tGenerating image from dot file : %s\n",commandString);
  59.  
  60. int ret = 0;
  61. ret = system (commandString);
  62. //printf ("ret = %d\n", ret);
  63.  
  64. }
  65.  
  66. void printGraphDotHeader(FILE * graphFile)
  67. {
  68.  
  69. if(graphFile!=NULL)
  70. {
  71. fprintf(graphFile, "digraph LSD10{\n");
  72. fprintf(graphFile, "\tbgcolor=white \n");
  73. fprintf(graphFile, "\tnode [");
  74. fprintf(graphFile, "color=\"#9DACBF\", ");
  75. fprintf(graphFile, "fontcolor=\"#000000\", ");
  76. fprintf(graphFile, "style=filled");
  77. fprintf(graphFile, "];\n");
  78. fprintf(graphFile, "\tedge [arrowsize=2, color=\"#000000\"];\n");
  79. }
  80. }
  81.  
  82. void printGraphDotFooter(FILE * graphFile)
  83. {
  84.  
  85. if(graphFile!=NULL)
  86. {
  87.  
  88. time_t now;
  89. struct tm *timeinfo;
  90.  
  91. now = time(NULL);//time ( &now );
  92. timeinfo = localtime ( &now );
  93. // fprintf(graphFile, "}\n");
  94. // fprintf(graphFile, "digraph INFO{\n");
  95. graphFile,
  96. "\t\"Generated by the SSHD09 LSD010 compiler\\n%d/%d/%d %dHr %d\\nWith GraphViz engine\" [",
  97. timeinfo->tm_mday,
  98. timeinfo->tm_mon+1,
  99. timeinfo->tm_year+1900,
  100. timeinfo->tm_hour,
  101. timeinfo->tm_min,
  102. timeinfo->tm_sec
  103. );
  104. fprintf(graphFile, "shape=box, ");
  105. fprintf(graphFile, "color=\"#FF9933\", ");
  106. fprintf(graphFile, "fontcolor=\"#000000\"");
  107. fprintf(graphFile, "];\n");
  108. fprintf(graphFile, "}\n");
  109. }
  110. }
  111. /**
  112.  * Prints an AST node into the graph file
  113.  * Pre-condition : dotFile not null
  114.  */
  115. void printGraphNode(FILE *dotFile, AstNode *node, int depth, int psn)
  116. {
  117. if(node!=NULL)
  118. {
  119. if(node->parent!=NULL)
  120. {
  121. fprintf(dotFile, "\t\"%p\" -> ", node->parent);
  122. }
  123. else
  124. {
  125. fprintf(dotFile, "\t");
  126. }
  127. dotFile,
  128. "\"%p\";\n\t\"%p\" [shape=%s, color=\"%s\", fontcolor=\"%s\", label=\"%s%s%s%s : \\n%s %s\\nLine %d char %d\"];\n",//print position?
  129. node,
  130. node,
  131. //node->type>LEX_FIRST_TOKEN&&node->type<LEX_LAST_TOKEN?"polygon":"box",
  132. psn==GRAPH_LEFT?"hexagon":(psn==GRAPH_RIGHT?"box":"doublecircle"),
  133. (node->type==NODE_TYPE_DECLARATION
  134. || node->type==NODE_TYPE_FUNCTION
  135. || node->type==NODE_TYPE_PARAM_DECL
  136. )?"#677E96":psn==GRAPH_LEFT?"#e6e8f2":(psn==GRAPH_RIGHT?"#AAB5C6":"#C0C0C0"),
  137. (node->type==NODE_TYPE_DECLARATION
  138. || node->type==NODE_TYPE_FUNCTION
  139. || node->type==NODE_TYPE_PARAM_DECL
  140. )?"#FFFFFF":"#000000",
  141. typeToString(node->type),
  142. node->subtype!=NODE_TYPE_NOTHING?" (":"",
  143. node->subtype!=NODE_TYPE_NOTHING?typeToString(node->subtype):"",
  144. node->subtype!=NODE_TYPE_NOTHING?")":"",
  145. typeToString(node->info->type),
  146. node->info->name,
  147. node->debug->line,
  148. node->debug->linePsn
  149. );
  150. printGraphNode(dotFile, node->left, depth+1, GRAPH_LEFT);
  151. printGraphNode(dotFile, node->right, depth+1, GRAPH_RIGHT);
  152. }
  153. //else fprintf(dotFile, "null");
  154. }
  155. void printGraphDotFromXML(char *xmlFileName, char *dotFileName)
  156. {
  157.  
  158. FILE * graphFile;
  159. time_t genTime = time(NULL);
  160. if(xmlFileName==NULL)xmlFileName=AST_XML_FILE;
  161. if(dotFileName==NULL)dotFileName=GRAPHVIZ_CONFIG_FILE;
  162. graphFile = fopen(dotFileName, "w");
  163. if(graphFile!=NULL)
  164. {
  165. printf("\n;\tGenerating AST Graph from %s into %s file ... (%s, col %d)", xmlFileName, dotFileName, __FILE__, __LINE__);
  166. printGraphDotHeader(graphFile);
  167. //todo : read info from XML file to generate the dot file
  168. fprintf(graphFile, "Warning : reading from XML is not yet implemented\n");
  169. printGraphDotFooter(graphFile);
  170. fclose(graphFile);
  171.  
  172. #if(VERBOSE_LEVEL<=DEB_EXEC)
  173. printMsg(DEB_EXEC,"...OK Graph printed", __FILE__, __LINE__);
  174. #endif
  175.  
  176. if(isGraphVisInstalled()==1)
  177. {
  178. generateImage(dotFileName);
  179. }
  180. }
  181. else
  182. {
  183. #if(VERBOSE_LEVEL<=DEB_EXEC)
  184. printMsg(DEB_EXEC,"Printing AST into Graph file ... Can't open file", __FILE__, __LINE__);
  185. printMsg(DEB_E, (char *)strerror(errno), __FILE__, __LINE__);
  186. #endif
  187. }
  188. }
  189.  
  190. void printGraphDotFromAST(char *dotFileName)
  191. {
  192.  
  193. FILE * graphFile;
  194. time_t genTime = time(NULL);
  195. if(dotFileName==NULL)dotFileName=GRAPHVIZ_CONFIG_FILE;
  196. graphFile = fopen(dotFileName, "w");
  197. if(graphFile!=NULL)
  198. {
  199. printf("\n;\tGenerating AST Graph from last compilation into %s file ... (%s, col %d)", dotFileName, __FILE__, __LINE__);
  200. printGraphDotHeader(graphFile);
  201. printGraphNode(graphFile, rootNode, 0, GRAPH_ROOT);
  202. printGraphDotFooter(graphFile);
  203. fclose(graphFile);
  204.  
  205. #if(VERBOSE_LEVEL<=DEB_EXEC)
  206. printMsg(DEB_EXEC,"...OK Graph printed", __FILE__, __LINE__);
  207. #endif
  208. }
  209. else
  210. {
  211. #if(VERBOSE_LEVEL<=DEB_EXEC)
  212. printMsg(DEB_EXEC,"Printing AST into Graph file ... Can't open file", __FILE__, __LINE__);
  213. printMsg(DEB_E, (char *)strerror(errno), __FILE__, __LINE__);
  214. #endif
  215. }
  216. }
  217.  
  218. /*
  219.  * **********************************************************
  220.  * Implementation of the header exposed items
  221.  * See graphVizHelper.h for these functions comments
  222.  * **********************************************************
  223.  */
  224.  
  225. void printGraph()
  226. {
  227. printGraphDotFromAST(GRAPHVIZ_CONFIG_FILE);
  228. if(isGraphVisInstalled()==1)
  229. {
  230. generateImage(GRAPHVIZ_CONFIG_FILE);
  231. }
  232. }

Je reviendrais plus en détails sur le code quand j'aurais plus de temps, mais voici déjà quelques explications...

Comme nous pouvons le constater dans le fichier d'en-tête, une seule fonction est proposée ici : void printGraph();. Cette fonction génère un fichier DOT défini dans l'en-tête par la constante GRAPHVIZ_CONFIG_FILE, car dans notre cas un seul fichier est utilisé et est écrasé à chaque analyse de code avec le compilateur LSD010.
Ce fichier est seulement destiné à être appelé par l'outil GraphViz pour créer une image des nœuds de l'arbre. Comme nous utiliserons le style "dot" de GraphViz pour notre image, nous pouvons retenir "dot" comme extension de notre fichier temporaire, afin de nous en souvenir.

Nous pouvons aussi générer un fichier de configuration pour GraphViz au départ d'un fichier XML généré par void printXMLTree(FILE *file, pAST_NODE node, int depth) lors de la dernière analyse par le compilateur LSD010. Ce fichier contient les différentes données de notre AST [“Abstract Syntaxic Tree”2].

Exemple fichier de configuration pour GraphViz

Reprennons un instant notre exemple de code qui à été analysé par le compilateur LSD010. Voici le fichier de configuration de GraphViz généré par un appel à void printGraph() pour produire l'image de l'exemple.

  1. digraph LSD10{
  2. bgcolor=white
  3. node [color="#9DACBF", fontcolor="#000000", style=filled];
  4. edge [arrowsize=2, color="#000000"];
  5. "0x91789c0";
  6. "0x91789c0" [shape=doublecircle, color="#677E96", fontcolor="#FFFFFF", label="Functions : \nNo Type Functions\nLine 1 char 4"];
  7. "0x91789c0" -> "0x9178960";
  8. "0x9178960" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="Function : \nvoid main\nLine 1 char 8"];
  9. "0x9178960" -> "0x9178900";
  10. "0x9178900" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="Structural node : \nNo Type {{decl}statement}\nLine 9 char 1"];
  11. "0x9178900" -> "0x9178898";
  12. "0x9178898" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="function body : \nNODE_TYPE_TODO Statements node\nLine 9 char 1"];
  13. "0x9178898" -> "0x9178830";
  14. "0x9178830" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="function body : \nNODE_TYPE_TODO Statements node\nLine 9 char 1"];
  15. "0x9178830" -> "0x91787c8";
  16. "0x91787c8" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Statement : \nNODE_TYPE_CHECK Statement : 'LExpr = RExpr;'\nLine 8 char 6"];
  17. "0x91787c8" -> "0x9178750";
  18. "0x9178750" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="Right expression : \nboolean _2\nLine 8 char 6"];
  19. "0x9178750" -> "0x91786f0";
  20. "0x91786f0" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="Right expression : \nNODE_TYPE_TODO _1\nLine 8 char 6"];
  21. "0x91786f0" -> "0x9178690";
  22. "0x9178690" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Id : \nNo Type k\nLine 8 char 6"];
  23. "0x9178750" -> "0x9178620";
  24. "0x9178620" [shape=box, color="#AAB5C6", fontcolor="#000000", label="number : \ninteger CONSTANT, NUMBER\nLine 8 char 3"];
  25. "0x91787c8" -> "0x91785b8";
  26. "0x91785b8" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Id : \nNo Type b\nLine 8 char 2"];
  27. "0x9178898" -> "0x9178548";
  28. "0x9178548" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Statement : \nNODE_TYPE_CHECK Statement : 'LExpr = RExpr;'\nLine 7 char 4"];
  29. "0x9178548" -> "0x91784d0";
  30. "0x91784d0" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="number : \ninteger CONSTANT, NUMBER\nLine 7 char 3"];
  31. "0x9178548" -> "0x9178468";
  32. "0x9178468" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Id : \nNo Type k\nLine 7 char 2"];
  33. "0x9178900" -> "0x91783f8";
  34. "0x91783f8" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Type declarations : \nNo Type Declarations node\nLine 6 char 1"];
  35. "0x91783f8" -> "0x9178390";
  36. "0x9178390" [shape=hexagon, color="#e6e8f2", fontcolor="#000000", label="Type declarations : \nNo Type Declarations node\nLine 6 char 1"];
  37. "0x9178390" -> "0x9178348";
  38. "0x9178348" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Type declaration : \nboolean b\nLine 5 char 9"];
  39. "0x91783f8" -> "0x9178298";
  40. "0x9178298" [shape=box, color="#AAB5C6", fontcolor="#000000", label="Type declaration : \ninteger k\nLine 4 char 9"];
  41. "Generated by the SSHD09 LSD010 compiler\n22/4/2010 4Hr 1\nWith GraphViz engine" [shape=box, color="#FF9933", fontcolor="#000000"];
  42. }

Code source du compilateur LSD010

Vous pouvez explorer et consulter la totalité du code source de l'exemple du compilateur LSD010 à cette adresse : https://www.gaudry.be/nl/langages-lsd10-source.html

Nederlandse vertaling

U hebt gevraagd om deze site in het Nederlands te bezoeken. Voor nu wordt alleen de interface vertaald, maar nog niet alle inhoud.

Als je me wilt helpen met vertalingen, is je bijdrage welkom. Het enige dat u hoeft te doen, is u op de site registreren en mij een bericht sturen waarin u wordt gevraagd om u toe te voegen aan de groep vertalers, zodat u de gewenste pagina's kunt vertalen. Een link onderaan elke vertaalde pagina geeft aan dat u de vertaler bent en heeft een link naar uw profiel.

Bij voorbaat dank.

Document heeft de 25/04/2010 gemaakt, de laatste keer de 09/03/2020 gewijzigd
Bron van het afgedrukte document:https://www.gaudry.be/nl/programmer-arbre-image-noeuds.html

De infobrol is een persoonlijke site waarvan de inhoud uitsluitend mijn verantwoordelijkheid is. De tekst is beschikbaar onder CreativeCommons-licentie (BY-NC-SA). Meer info op de gebruiksvoorwaarden en de auteur.

Notes

  1. a,b,c,d,e LSD010 : Langage Simple et Didactique Il existe une un certain nombre d'interprétations de l'acronyme LSD (Langage Symbolique Didactique, Langage Sans Difficulté, Langage Simple et Didactique). LSD010 est la version 2010 de la suite LSD80, LSD_02, LSD03, LSD04, LSD05, LSD06, LSD07, LSD08, et LSD09.

  2. a,b Abstract Syntaxic Tree : komt overeen met « arbre syntaxique abstrait » en français

  3.  AST : “Abstract Syntaxic Tree” (en français, « arbre syntaxique abstrait »)

Inhoudsopgave Haut

Referenties

  1. Bekijk - html-document Taal van het document:uk Graph Visualization Software : http://www.graphviz.org/Credits.php, Graphviz (version 24/04/10)
  2. boek Taal van het document:fr IHDCB332 - Théorie des langages : Syntaxe et sémantique : PY Schobbens, Syntaxe et sémantique (January 2010)

Deze verwijzingen en links verwijzen naar documenten die geraadpleegd zijn tijdens het schrijven van deze pagina, of die aanvullende informatie kunnen geven, maar de auteurs van deze bronnen kunnen niet verantwoordelijk worden gehouden voor de inhoud van deze pagina.
De auteur Deze site is als enige verantwoordelijk voor de manier waarop de verschillende concepten, en de vrijheden die met de referentiewerken worden genomen, hier worden gepresenteerd. Vergeet niet dat u meerdere broninformatie moet doorgeven om het risico op fouten te verkleinen.

Inhoudsopgave Haut