gvpr.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. /*************************************************************************
  2. * Copyright (c) 2011 AT&T Intellectual Property
  3. * All rights reserved. This program and the accompanying materials
  4. * are made available under the terms of the Eclipse Public License v1.0
  5. * which accompanies this distribution, and is available at
  6. * https://www.eclipse.org/legal/epl-v10.html
  7. *
  8. * Contributors: Details at https://graphviz.org
  9. *************************************************************************/
  10. /*
  11. * gpr: graph pattern recognizer
  12. *
  13. * Written by Emden Gansner
  14. */
  15. #include "builddate.h"
  16. #include <assert.h>
  17. #include <ast/error.h>
  18. #include <cgraph/cgraph.h>
  19. #include <cgraph/gv_ctype.h>
  20. #include <cgraph/ingraphs.h>
  21. #include <cgraph/list.h>
  22. #include <common/globals.h>
  23. #include <getopt.h>
  24. #include <gvpr/actions.h>
  25. #include <gvpr/compile.h>
  26. #include <gvpr/gprstate.h>
  27. #include <gvpr/gvpr.h>
  28. #include <setjmp.h>
  29. #include <stdbool.h>
  30. #include <stddef.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <unistd.h>
  34. #include <util/agxbuf.h>
  35. #include <util/alloc.h>
  36. #include <util/exit.h>
  37. #include <util/unreachable.h>
  38. #ifndef DFLT_GVPRPATH
  39. #define DFLT_GVPRPATH "."
  40. #endif
  41. static char *Info[] = {
  42. "gvpr", /* Program */
  43. PACKAGE_VERSION, /* Version */
  44. BUILDDATE /* Build Date */
  45. };
  46. static const char *usage =
  47. " [-o <ofile>] [-a <args>] ([-f <prog>] | 'prog') [files]\n\
  48. -c - use source graph for output\n\
  49. -f <pfile> - find program in file <pfile>\n\
  50. -i - create node induced subgraph\n\
  51. -a <args> - string arguments available as ARGV[0..]\n\
  52. -o <ofile> - write output to <ofile>; stdout by default\n\
  53. -n - no read-ahead of input graphs\n\
  54. -q - turn off warning messages\n\
  55. -V - print version info\n\
  56. -? - print usage info\n\
  57. If no files are specified, stdin is used\n";
  58. typedef struct {
  59. char *cmdName; /* command name */
  60. FILE *outFile; /* output stream; stdout default */
  61. char *program; /* program source */
  62. int useFile; /* true if program comes from a file */
  63. compflags_t compflags;
  64. int readAhead;
  65. char **inFiles;
  66. int argc;
  67. char **argv;
  68. int state; /* > 0 : continue; <= 0 finish */
  69. int verbose;
  70. } options;
  71. static FILE *openOut(char *name) {
  72. FILE *outs = fopen(name, "w");
  73. if (outs == 0) {
  74. error(ERROR_ERROR, "could not open %s for writing", name);
  75. }
  76. return outs;
  77. }
  78. /* gettok:
  79. * Tokenize a string. Tokens consist of either a non-empty string
  80. * of non-space characters, or all characters between a pair of
  81. * single or double quotes. As usual, we map
  82. * \c -> c
  83. * for all c
  84. * Return next argument token, returning NULL if none.
  85. * sp is updated to point to next character to be processed.
  86. * NB. There must be white space between tokens. Otherwise, they
  87. * are concatenated.
  88. */
  89. static char *gettok(char **sp) {
  90. char *s = *sp;
  91. char *ws = s;
  92. char *rs = s;
  93. char c;
  94. char q = '\0'; /* if non-0, in quote mode with quote char q */
  95. while (gv_isspace(*rs))
  96. rs++;
  97. if ((c = *rs) == '\0')
  98. return NULL;
  99. while ((c = *rs)) {
  100. if (q && (q == c)) { /* end quote */
  101. q = '\0';
  102. } else if (!q && ((c == '"') || (c == '\''))) {
  103. q = c;
  104. } else if (c == '\\') {
  105. rs++;
  106. c = *rs;
  107. if (c)
  108. *ws++ = c;
  109. else {
  110. error(ERROR_WARNING,
  111. "backslash in argument followed by no character - ignored");
  112. rs--;
  113. }
  114. } else if (q || !gv_isspace(c))
  115. *ws++ = c;
  116. else
  117. break;
  118. rs++;
  119. }
  120. if (*rs)
  121. rs++;
  122. else if (q)
  123. error(ERROR_WARNING, "no closing quote for argument %s", s);
  124. *sp = rs;
  125. *ws = '\0';
  126. return s;
  127. }
  128. #define NUM_ARGS 100
  129. /* parseArgs:
  130. * Split s into whitespace separated tokens, allowing quotes.
  131. * Append tokens to argument list and return new number of arguments.
  132. * argc is the current number of arguments, with the arguments
  133. * stored in *argv.
  134. */
  135. static int parseArgs(char *s, int argc, char ***argv) {
  136. int i, cnt = 0;
  137. char *args[NUM_ARGS];
  138. char *t;
  139. char **av;
  140. assert(argc >= 0);
  141. while ((t = gettok(&s))) {
  142. if (cnt == NUM_ARGS) {
  143. error(ERROR_WARNING,
  144. "at most %d arguments allowed per -a flag - ignoring rest",
  145. NUM_ARGS);
  146. break;
  147. }
  148. args[cnt++] = t;
  149. }
  150. if (cnt) {
  151. int oldcnt = argc;
  152. argc = oldcnt + cnt;
  153. av = gv_recalloc(*argv, (size_t)oldcnt, (size_t)argc, sizeof(char *));
  154. for (i = 0; i < cnt; i++)
  155. av[oldcnt + i] = gv_strdup(args[i]);
  156. *argv = av;
  157. }
  158. return argc;
  159. }
  160. #if defined(_WIN32) && !defined(__MINGW32__)
  161. #define PATHSEP '\\'
  162. #define LISTSEP ';'
  163. #else
  164. #define PATHSEP '/'
  165. #define LISTSEP ':'
  166. #endif
  167. static char *concat(char *pfx, char *sfx) {
  168. agxbuf sp = {0};
  169. agxbprint(&sp, "%s%s", pfx, sfx);
  170. return agxbdisown(&sp);
  171. }
  172. /* resolve:
  173. * Translate -f arg parameter into a pathname.
  174. * If arg contains '/', return arg.
  175. * Else search directories in GVPRPATH for arg.
  176. * Return NULL on error.
  177. */
  178. static char *resolve(char *arg, int verbose) {
  179. char *path;
  180. char *s;
  181. char *cp;
  182. char c;
  183. char *fname = 0;
  184. char *pathp = NULL;
  185. size_t sz;
  186. if (strchr(arg, PATHSEP))
  187. return gv_strdup(arg);
  188. path = getenv("GVPRPATH");
  189. if (!path)
  190. path = getenv("GPRPATH"); // deprecated
  191. if (path && (c = *path)) {
  192. if (c == LISTSEP) {
  193. pathp = path = concat(DFLT_GVPRPATH, path);
  194. } else if ((c = path[strlen(path) - 1]) == LISTSEP) {
  195. pathp = path = concat(path, DFLT_GVPRPATH);
  196. }
  197. } else
  198. path = DFLT_GVPRPATH;
  199. if (verbose)
  200. fprintf(stderr, "PATH: %s\n", path);
  201. agxbuf fp = {0};
  202. while (*path && !fname) {
  203. if (*path == LISTSEP) { /* skip colons */
  204. path++;
  205. continue;
  206. }
  207. cp = strchr(path, LISTSEP);
  208. if (cp) {
  209. sz = (size_t)(cp - path);
  210. agxbput_n(&fp, path, sz);
  211. path = cp + 1; /* skip past current colon */
  212. } else {
  213. sz = agxbput(&fp, path);
  214. path += sz;
  215. }
  216. agxbprint(&fp, "%c%s", PATHSEP, arg);
  217. s = agxbuse(&fp);
  218. if (access(s, R_OK) == 0) {
  219. fname = gv_strdup(s);
  220. }
  221. }
  222. if (!fname)
  223. error(ERROR_ERROR, "Could not find file \"%s\" in GVPRPATH", arg);
  224. agxbfree(&fp);
  225. free(pathp);
  226. if (verbose)
  227. fprintf(stderr, "file %s resolved to %s\n", arg, fname);
  228. return fname;
  229. }
  230. static char *getOptarg(int c, char **argp, int *argip, int argc, char **argv) {
  231. char *rv;
  232. char *arg = *argp;
  233. int argi = *argip;
  234. if (*arg) {
  235. rv = arg;
  236. while (*arg)
  237. arg++;
  238. *argp = arg;
  239. } else if (argi < argc) {
  240. rv = argv[argi++];
  241. *argip = argi;
  242. } else {
  243. rv = NULL;
  244. error(ERROR_WARNING, "missing argument for option -%c", c);
  245. }
  246. return rv;
  247. }
  248. /* doFlags:
  249. * Process a command-line argument starting with a '-'.
  250. * argi is the index of the next available item in argv[].
  251. * argc has its usual meaning.
  252. *
  253. * return > 0 given next argi value
  254. * = 0 for exit with 0
  255. * < 0 for error
  256. */
  257. static int doFlags(char *arg, int argi, int argc, char **argv, options *opts) {
  258. int c;
  259. while ((c = *arg++)) {
  260. switch (c) {
  261. case 'c':
  262. opts->compflags.srcout = true;
  263. break;
  264. case 'C':
  265. opts->compflags.srcout = true;
  266. opts->compflags.clone = true;
  267. break;
  268. case 'f':
  269. if ((optarg = getOptarg(c, &arg, &argi, argc, argv)) &&
  270. (opts->program = resolve(optarg, opts->verbose))) {
  271. opts->useFile = 1;
  272. } else
  273. return -1;
  274. break;
  275. case 'i':
  276. opts->compflags.induce = true;
  277. break;
  278. case 'n':
  279. opts->readAhead = 0;
  280. break;
  281. case 'a':
  282. if ((optarg = getOptarg(c, &arg, &argi, argc, argv))) {
  283. opts->argc = parseArgs(optarg, opts->argc, &(opts->argv));
  284. } else
  285. return -1;
  286. break;
  287. case 'o':
  288. if (!(optarg = getOptarg(c, &arg, &argi, argc, argv)) ||
  289. !(opts->outFile = openOut(optarg)))
  290. return -1;
  291. break;
  292. case 'q':
  293. setTraceLevel(ERROR_ERROR); /* Don't emit warning messages */
  294. break;
  295. case 'v':
  296. opts->verbose = 1;
  297. break;
  298. case 'V':
  299. fprintf(stderr, "%s version %s (%s)\n", Info[0], Info[1], Info[2]);
  300. return 0;
  301. break;
  302. case '?':
  303. if (optopt == '\0' || optopt == '?')
  304. fprintf(stderr, "Usage: gvpr%s", usage);
  305. else {
  306. error(ERROR_USAGE | ERROR_WARNING, "%s", usage);
  307. }
  308. return 0;
  309. break;
  310. default:
  311. error(ERROR_WARNING, "option -%c unrecognized", c);
  312. break;
  313. }
  314. }
  315. return argi;
  316. }
  317. static void freeOpts(options opts) {
  318. if (opts.outFile != NULL && opts.outFile != stdout)
  319. fclose(opts.outFile);
  320. free(opts.inFiles);
  321. if (opts.useFile)
  322. free(opts.program);
  323. for (int i = 0; i < opts.argc; i++)
  324. free(opts.argv[i]);
  325. free(opts.argv);
  326. }
  327. DEFINE_LIST(strs, char *)
  328. /* scanArgs:
  329. * Parse command line options.
  330. */
  331. static options scanArgs(int argc, char **argv) {
  332. char *arg;
  333. options opts = {0};
  334. opts.cmdName = argv[0];
  335. opts.state = 1;
  336. opts.readAhead = 1;
  337. setErrorId(opts.cmdName);
  338. opts.verbose = 0;
  339. strs_t input_filenames = {0};
  340. /* loop over arguments */
  341. for (int i = 1; i < argc;) {
  342. arg = argv[i++];
  343. if (*arg == '-') {
  344. i = doFlags(arg + 1, i, argc, argv, &opts);
  345. if (i <= 0) {
  346. opts.state = i;
  347. goto opts_done;
  348. }
  349. } else if (arg)
  350. strs_append(&input_filenames, arg);
  351. }
  352. /* Handle additional semantics */
  353. if (opts.useFile == 0) {
  354. if (strs_is_empty(&input_filenames)) {
  355. error(ERROR_ERROR, "No program supplied via argument or -f option");
  356. opts.state = -1;
  357. } else {
  358. opts.program = strs_pop_front(&input_filenames);
  359. }
  360. }
  361. if (strs_is_empty(&input_filenames)) {
  362. opts.inFiles = 0;
  363. strs_free(&input_filenames);
  364. } else {
  365. strs_append(&input_filenames, NULL);
  366. opts.inFiles = strs_detach(&input_filenames);
  367. }
  368. if (!opts.outFile)
  369. opts.outFile = stdout;
  370. opts_done:
  371. if (opts.state <= 0) {
  372. if (opts.state < 0)
  373. error(ERROR_USAGE | ERROR_ERROR, "%s", usage);
  374. strs_free(&input_filenames);
  375. }
  376. return opts;
  377. }
  378. static Agobj_t *evalEdge(Gpr_t *state, Expr_t *prog, comp_block *xprog,
  379. Agedge_t *e) {
  380. case_stmt *cs;
  381. bool okay;
  382. state->curobj = (Agobj_t *)e;
  383. for (size_t i = 0; i < xprog->n_estmts; i++) {
  384. cs = xprog->edge_stmts + i;
  385. if (cs->guard)
  386. okay = exeval(prog, cs->guard, state).integer != 0;
  387. else
  388. okay = true;
  389. if (okay) {
  390. if (cs->action)
  391. exeval(prog, cs->action, state);
  392. else
  393. agsubedge(state->target, e, 1);
  394. }
  395. }
  396. return state->curobj;
  397. }
  398. static Agobj_t *evalNode(Gpr_t *state, Expr_t *prog, comp_block *xprog,
  399. Agnode_t *n) {
  400. case_stmt *cs;
  401. bool okay;
  402. state->curobj = (Agobj_t *)n;
  403. for (size_t i = 0; i < xprog->n_nstmts; i++) {
  404. cs = xprog->node_stmts + i;
  405. if (cs->guard)
  406. okay = exeval(prog, cs->guard, state).integer != 0;
  407. else
  408. okay = true;
  409. if (okay) {
  410. if (cs->action)
  411. exeval(prog, cs->action, state);
  412. else
  413. agsubnode(state->target, n, 1);
  414. }
  415. }
  416. return (state->curobj);
  417. }
  418. typedef struct {
  419. Agnode_t *oldroot;
  420. Agnode_t *prev;
  421. } nodestream;
  422. static Agnode_t *nextNode(Gpr_t *state, nodestream *nodes) {
  423. Agnode_t *np;
  424. if (state->tvroot != nodes->oldroot) {
  425. np = nodes->oldroot = state->tvroot;
  426. } else if (state->flags & GV_NEXT_SET) {
  427. np = nodes->oldroot = state->tvroot = state->tvnext;
  428. state->flags &= ~GV_NEXT_SET;
  429. } else if (nodes->prev) {
  430. np = nodes->prev = agnxtnode(state->curgraph, nodes->prev);
  431. } else {
  432. np = nodes->prev = agfstnode(state->curgraph);
  433. }
  434. return np;
  435. }
  436. #define MARKED(x) (((x)->iu.integer) & 1)
  437. #define MARK(x) (((x)->iu.integer) = 1)
  438. #define ONSTACK(x) (((x)->iu.integer) & 2)
  439. #define PUSH(x, e) (((x)->iu.integer) |= 2, (x)->ine = (e))
  440. #define POP(x) (((x)->iu.integer) &= (~2))
  441. typedef Agedge_t *(*fstedgefn_t)(Agraph_t *, Agnode_t *);
  442. typedef Agedge_t *(*nxttedgefn_t)(Agraph_t *, Agedge_t *, Agnode_t *);
  443. #define PRE_VISIT 1
  444. #define POST_VISIT 2
  445. typedef struct {
  446. fstedgefn_t fstedge;
  447. nxttedgefn_t nxtedge;
  448. unsigned char undirected;
  449. unsigned char visit;
  450. } trav_fns;
  451. /// `agnxtout` wrapper to tweak calling convention
  452. static Agedge_t *agnxtout_(Agraph_t *g, Agedge_t *e, Agnode_t *ignored) {
  453. (void)ignored;
  454. return agnxtout(g, e);
  455. }
  456. /// `agnxtin` wrapper to tweak calling convention
  457. static Agedge_t *agnxtin_(Agraph_t *g, Agedge_t *e, Agnode_t *ignored) {
  458. (void)ignored;
  459. return agnxtin(g, e);
  460. }
  461. static trav_fns DFSfns = {agfstedge, agnxtedge, 1, 0};
  462. static trav_fns FWDfns = {agfstout, agnxtout_, 0, 0};
  463. static trav_fns REVfns = {agfstin, agnxtin_, 0, 0};
  464. DEFINE_LIST(node_queue, Agnode_t *)
  465. static void travBFS(Gpr_t *state, Expr_t *prog, comp_block *xprog) {
  466. nodestream nodes;
  467. node_queue_t q = {0};
  468. ndata *nd;
  469. Agnode_t *n;
  470. Agedge_t *cure;
  471. Agedge_t *nxte;
  472. Agraph_t *g = state->curgraph;
  473. nodes.oldroot = 0;
  474. nodes.prev = 0;
  475. while ((n = nextNode(state, &nodes))) {
  476. nd = nData(n);
  477. if (MARKED(nd))
  478. continue;
  479. PUSH(nd, 0);
  480. node_queue_push_back(&q, n);
  481. while (!node_queue_is_empty(&q)) {
  482. n = node_queue_pop_front(&q);
  483. nd = nData(n);
  484. MARK(nd);
  485. POP(nd);
  486. state->tvedge = nd->ine;
  487. if (!evalNode(state, prog, xprog, n))
  488. continue;
  489. for (cure = agfstedge(g, n); cure; cure = nxte) {
  490. nxte = agnxtedge(g, cure, n);
  491. nd = nData(cure->node);
  492. if (MARKED(nd))
  493. continue;
  494. if (!evalEdge(state, prog, xprog, cure))
  495. continue;
  496. if (!ONSTACK(nd)) {
  497. node_queue_push_back(&q, cure->node);
  498. PUSH(nd, cure);
  499. }
  500. }
  501. }
  502. }
  503. state->tvedge = 0;
  504. node_queue_free(&q);
  505. }
  506. DEFINE_LIST(edge_stack, Agedge_t *)
  507. static void travDFS(Gpr_t *state, Expr_t *prog, comp_block *xprog,
  508. trav_fns *fns) {
  509. Agnode_t *n;
  510. edge_stack_t stk = {0};
  511. Agnode_t *curn;
  512. Agedge_t *cure;
  513. Agedge_t *entry;
  514. int more;
  515. ndata *nd;
  516. nodestream nodes;
  517. Agedgepair_t seed;
  518. nodes.oldroot = 0;
  519. nodes.prev = 0;
  520. while ((n = nextNode(state, &nodes))) {
  521. nd = nData(n);
  522. if (MARKED(nd))
  523. continue;
  524. seed.out.node = n;
  525. seed.in.node = 0;
  526. curn = n;
  527. entry = &(seed.out);
  528. state->tvedge = cure = 0;
  529. MARK(nd);
  530. PUSH(nd, 0);
  531. if (fns->visit & PRE_VISIT)
  532. evalNode(state, prog, xprog, n);
  533. more = 1;
  534. while (more) {
  535. if (cure)
  536. cure = fns->nxtedge(state->curgraph, cure, curn);
  537. else
  538. cure = fns->fstedge(state->curgraph, curn);
  539. if (cure) {
  540. if (entry == agopp(cure)) /* skip edge used to get here */
  541. continue;
  542. nd = nData(cure->node);
  543. if (MARKED(nd)) {
  544. /* For undirected DFS, visit an edge only if its head
  545. * is on the stack, to avoid visiting it twice.
  546. * This is no problem in directed DFS.
  547. */
  548. if (fns->undirected) {
  549. if (ONSTACK(nd))
  550. evalEdge(state, prog, xprog, cure);
  551. } else
  552. evalEdge(state, prog, xprog, cure);
  553. } else {
  554. evalEdge(state, prog, xprog, cure);
  555. edge_stack_push_back(&stk, entry);
  556. state->tvedge = entry = cure;
  557. curn = cure->node;
  558. cure = 0;
  559. if (fns->visit & PRE_VISIT)
  560. evalNode(state, prog, xprog, curn);
  561. MARK(nd);
  562. PUSH(nd, entry);
  563. }
  564. } else {
  565. if (fns->visit & POST_VISIT)
  566. evalNode(state, prog, xprog, curn);
  567. nd = nData(curn);
  568. POP(nd);
  569. cure = entry;
  570. entry = edge_stack_is_empty(&stk) ? NULL : edge_stack_pop_back(&stk);
  571. if (entry == &(seed.out))
  572. state->tvedge = 0;
  573. else
  574. state->tvedge = entry;
  575. if (entry)
  576. curn = entry->node;
  577. else
  578. more = 0;
  579. }
  580. }
  581. }
  582. state->tvedge = 0;
  583. edge_stack_free(&stk);
  584. }
  585. static void travNodes(Gpr_t *state, Expr_t *prog, comp_block *xprog) {
  586. Agnode_t *n;
  587. Agnode_t *next;
  588. Agraph_t *g = state->curgraph;
  589. for (n = agfstnode(g); n; n = next) {
  590. next = agnxtnode(g, n);
  591. evalNode(state, prog, xprog, n);
  592. }
  593. }
  594. static void travEdges(Gpr_t *state, Expr_t *prog, comp_block *xprog) {
  595. Agnode_t *n;
  596. Agnode_t *next;
  597. Agedge_t *e;
  598. Agedge_t *nexte;
  599. Agraph_t *g = state->curgraph;
  600. for (n = agfstnode(g); n; n = next) {
  601. next = agnxtnode(g, n);
  602. for (e = agfstout(g, n); e; e = nexte) {
  603. nexte = agnxtout(g, e);
  604. evalEdge(state, prog, xprog, e);
  605. }
  606. }
  607. }
  608. static void travFlat(Gpr_t *state, Expr_t *prog, comp_block *xprog) {
  609. Agnode_t *n;
  610. Agnode_t *next;
  611. Agedge_t *e;
  612. Agedge_t *nexte;
  613. Agraph_t *g = state->curgraph;
  614. for (n = agfstnode(g); n; n = next) {
  615. next = agnxtnode(g, n);
  616. if (!evalNode(state, prog, xprog, n))
  617. continue;
  618. if (xprog->n_estmts > 0) {
  619. for (e = agfstout(g, n); e; e = nexte) {
  620. nexte = agnxtout(g, e);
  621. evalEdge(state, prog, xprog, e);
  622. }
  623. }
  624. }
  625. }
  626. /* doCleanup:
  627. * Reset node traversal data
  628. */
  629. static void doCleanup(Agraph_t *g) {
  630. Agnode_t *n;
  631. ndata *nd;
  632. for (n = agfstnode(g); n; n = agnxtnode(g, n)) {
  633. nd = nData(n);
  634. nd->ine = NULL;
  635. nd->iu.integer = 0;
  636. }
  637. }
  638. /* traverse:
  639. * return true if traversal requires cleanup
  640. */
  641. static bool traverse(Gpr_t *state, Expr_t *prog, comp_block *bp, bool cleanup) {
  642. if (!state->target) {
  643. char *target;
  644. agxbuf tmp = {0};
  645. if (state->name_used) {
  646. agxbprint(&tmp, "%s%d", state->tgtname, state->name_used);
  647. target = agxbuse(&tmp);
  648. } else
  649. target = state->tgtname;
  650. state->name_used++;
  651. /* make sure target subgraph does not exist */
  652. while (agsubg(state->curgraph, target, 0)) {
  653. state->name_used++;
  654. agxbprint(&tmp, "%s%d", state->tgtname, state->name_used);
  655. target = agxbuse(&tmp);
  656. }
  657. state->target = openSubg(state->curgraph, target);
  658. agxbfree(&tmp);
  659. }
  660. if (!state->outgraph)
  661. state->outgraph = state->target;
  662. switch (state->tvt) {
  663. case TV_flat:
  664. travFlat(state, prog, bp);
  665. break;
  666. case TV_bfs:
  667. if (cleanup)
  668. doCleanup(state->curgraph);
  669. travBFS(state, prog, bp);
  670. cleanup = true;
  671. break;
  672. case TV_dfs:
  673. if (cleanup)
  674. doCleanup(state->curgraph);
  675. DFSfns.visit = PRE_VISIT;
  676. travDFS(state, prog, bp, &DFSfns);
  677. cleanup = true;
  678. break;
  679. case TV_fwd:
  680. if (cleanup)
  681. doCleanup(state->curgraph);
  682. FWDfns.visit = PRE_VISIT;
  683. travDFS(state, prog, bp, &FWDfns);
  684. cleanup = true;
  685. break;
  686. case TV_rev:
  687. if (cleanup)
  688. doCleanup(state->curgraph);
  689. REVfns.visit = PRE_VISIT;
  690. travDFS(state, prog, bp, &REVfns);
  691. cleanup = true;
  692. break;
  693. case TV_postdfs:
  694. if (cleanup)
  695. doCleanup(state->curgraph);
  696. DFSfns.visit = POST_VISIT;
  697. travDFS(state, prog, bp, &DFSfns);
  698. cleanup = true;
  699. break;
  700. case TV_postfwd:
  701. if (cleanup)
  702. doCleanup(state->curgraph);
  703. FWDfns.visit = POST_VISIT;
  704. travDFS(state, prog, bp, &FWDfns);
  705. cleanup = true;
  706. break;
  707. case TV_postrev:
  708. if (cleanup)
  709. doCleanup(state->curgraph);
  710. REVfns.visit = POST_VISIT;
  711. travDFS(state, prog, bp, &REVfns);
  712. cleanup = true;
  713. break;
  714. case TV_prepostdfs:
  715. if (cleanup)
  716. doCleanup(state->curgraph);
  717. DFSfns.visit = POST_VISIT | PRE_VISIT;
  718. travDFS(state, prog, bp, &DFSfns);
  719. cleanup = true;
  720. break;
  721. case TV_prepostfwd:
  722. if (cleanup)
  723. doCleanup(state->curgraph);
  724. FWDfns.visit = POST_VISIT | PRE_VISIT;
  725. travDFS(state, prog, bp, &FWDfns);
  726. cleanup = true;
  727. break;
  728. case TV_prepostrev:
  729. if (cleanup)
  730. doCleanup(state->curgraph);
  731. REVfns.visit = POST_VISIT | PRE_VISIT;
  732. travDFS(state, prog, bp, &REVfns);
  733. cleanup = true;
  734. break;
  735. case TV_ne:
  736. travNodes(state, prog, bp);
  737. travEdges(state, prog, bp);
  738. break;
  739. case TV_en:
  740. travEdges(state, prog, bp);
  741. travNodes(state, prog, bp);
  742. break;
  743. default:
  744. UNREACHABLE();
  745. }
  746. return cleanup;
  747. }
  748. /* addOutputGraph:
  749. * Append output graph to option struct.
  750. * We know uopts and state->outgraph are non-NULL.
  751. */
  752. static void addOutputGraph(Gpr_t *state, gvpropts *uopts) {
  753. Agraph_t *g = state->outgraph;
  754. if ((agroot(g) == state->curgraph) && !uopts->ingraphs)
  755. g = (Agraph_t *)cloneO(0, (Agobj_t *)g);
  756. uopts->outgraphs = gv_recalloc(uopts->outgraphs, uopts->n_outgraphs,
  757. uopts->n_outgraphs + 1, sizeof(Agraph_t *));
  758. uopts->n_outgraphs++;
  759. uopts->outgraphs[uopts->n_outgraphs - 1] = g;
  760. }
  761. static void chkClose(Agraph_t *g) {
  762. gdata *data;
  763. data = gData(g);
  764. if (data->lock.locked)
  765. data->lock.zombie = true;
  766. else
  767. agclose(g);
  768. }
  769. static Agraph_t *ing_read(void *fp) { return readG(fp); }
  770. /// collective managed state used in `gvpr_core`
  771. typedef struct {
  772. parse_prog *prog;
  773. ingraph_state *ing;
  774. comp_prog *xprog;
  775. Gpr_t *state;
  776. options opts;
  777. } gvpr_state_t;
  778. /* gvexitf:
  779. * Only used if GV_USE_EXIT not set during exeval.
  780. * This implies setjmp/longjmp set up.
  781. */
  782. static void gvexitf(void *env, int v) {
  783. gvpr_state_t *st = env;
  784. longjmp(st->state->jbuf, v);
  785. }
  786. static void gverrorf(Expr_t *handle, Exdisc_t *discipline, int level,
  787. const char *fmt, ...) {
  788. va_list ap;
  789. va_start(ap, fmt);
  790. errorv((discipline && handle) ? *((char **)handle) : (char *)handle, level,
  791. fmt, ap);
  792. va_end(ap);
  793. if (level >= ERROR_ERROR) {
  794. Gpr_t *state = discipline->user;
  795. if (state->flags & GV_USE_EXIT)
  796. graphviz_exit(1);
  797. else if (state->flags & GV_USE_JUMP)
  798. longjmp(state->jbuf, 1);
  799. }
  800. }
  801. /* gvpr_core:
  802. * Return 0 on success; non-zero on error.
  803. *
  804. * FIX/TODO:
  805. * - close non-source/non-output graphs
  806. * - flag to clone target graph?
  807. * - remove assignment in boolean warning if wrapped in ()
  808. * - do automatic cast for array indices if type is known
  809. * - array initialization
  810. */
  811. static int gvpr_core(int argc, char *argv[], gvpropts *uopts,
  812. gvpr_state_t *gs) {
  813. gpr_info info;
  814. int rv = 0;
  815. setErrorErrors(0);
  816. gs->opts = scanArgs(argc, argv);
  817. if (gs->opts.state <= 0) {
  818. return gs->opts.state;
  819. }
  820. if (gs->opts.verbose)
  821. gvstart_timer();
  822. gs->prog = parseProg(gs->opts.program, gs->opts.useFile);
  823. if (gs->prog == NULL) {
  824. return 1;
  825. }
  826. info.outFile = gs->opts.outFile;
  827. info.argc = gs->opts.argc;
  828. info.argv = gs->opts.argv;
  829. info.errf = gverrorf;
  830. if (uopts)
  831. info.flags = uopts->flags;
  832. else
  833. info.flags = 0;
  834. if ((uopts->flags & GV_USE_EXIT))
  835. info.exitf = 0;
  836. else
  837. info.exitf = gvexitf;
  838. gs->state = openGPRState(&info);
  839. if (gs->state == NULL) {
  840. return 1;
  841. }
  842. if (uopts->bindings)
  843. addBindings(gs->state, uopts->bindings);
  844. gs->xprog = compileProg(gs->prog, gs->state, gs->opts.compflags);
  845. if (gs->xprog == NULL) {
  846. return 1;
  847. }
  848. initGPRState(gs->state);
  849. if ((uopts->flags & GV_USE_OUTGRAPH)) {
  850. uopts->outgraphs = 0;
  851. uopts->n_outgraphs = 0;
  852. }
  853. if (!(uopts->flags & GV_USE_EXIT)) {
  854. gs->state->flags |= GV_USE_JUMP;
  855. if ((rv = setjmp(gs->state->jbuf))) {
  856. return rv;
  857. }
  858. }
  859. bool incoreGraphs = uopts && uopts->ingraphs;
  860. if (gs->opts.verbose)
  861. fprintf(stderr, "Parse/compile/init: %.2f secs.\n", gvelapsed_sec());
  862. /* do begin */
  863. if (gs->xprog->begin_stmt != NULL)
  864. exeval(gs->xprog->prog, gs->xprog->begin_stmt, gs->state);
  865. /* if program is not null */
  866. if (gs->xprog->uses_graph) {
  867. if (uopts && uopts->ingraphs)
  868. gs->ing = newIngGraphs(0, uopts->ingraphs, ing_read);
  869. else
  870. gs->ing = newIng(0, gs->opts.inFiles, ing_read);
  871. if (gs->opts.verbose)
  872. gvstart_timer();
  873. Agraph_t *nextg = NULL;
  874. for (gs->state->curgraph = nextGraph(gs->ing); gs->state->curgraph;
  875. gs->state->curgraph = nextg) {
  876. if (gs->opts.verbose)
  877. fprintf(stderr, "Read graph: %.2f secs.\n", gvelapsed_sec());
  878. gs->state->infname = fileName(gs->ing);
  879. if (gs->opts.readAhead)
  880. nextg = gs->state->nextgraph = nextGraph(gs->ing);
  881. bool cleanup = false;
  882. for (size_t i = 0; i < gs->xprog->n_blocks; i++) {
  883. comp_block *bp = gs->xprog->blocks + i;
  884. /* begin graph */
  885. if (incoreGraphs && gs->opts.compflags.clone)
  886. gs->state->curgraph =
  887. (Agraph_t *)cloneO(0, &gs->state->curgraph->base);
  888. gs->state->curobj = &gs->state->curgraph->base;
  889. gs->state->tvroot = 0;
  890. if (bp->begg_stmt)
  891. exeval(gs->xprog->prog, bp->begg_stmt, gs->state);
  892. /* walk graph */
  893. if (bp->does_walk_graph) {
  894. cleanup = traverse(gs->state, gs->xprog->prog, bp, cleanup);
  895. }
  896. }
  897. /* end graph */
  898. gs->state->curobj = &gs->state->curgraph->base;
  899. if (gs->xprog->endg_stmt != NULL)
  900. exeval(gs->xprog->prog, gs->xprog->endg_stmt, gs->state);
  901. if (gs->opts.verbose)
  902. fprintf(stderr, "Finish graph: %.2f secs.\n", gvelapsed_sec());
  903. /* if $O == $G and $T is empty, delete $T */
  904. if (gs->state->outgraph == gs->state->curgraph &&
  905. gs->state->target != NULL && !agnnodes(gs->state->target))
  906. agdelete(gs->state->curgraph, gs->state->target);
  907. /* output graph, if necessary
  908. * For this, the outgraph must be defined, and either
  909. * be non-empty or the -c option was used.
  910. */
  911. if (gs->state->outgraph != NULL &&
  912. (agnnodes(gs->state->outgraph) || gs->opts.compflags.srcout)) {
  913. if (uopts && (uopts->flags & GV_USE_OUTGRAPH))
  914. addOutputGraph(gs->state, uopts);
  915. else
  916. sfioWrite(gs->state->outgraph, gs->opts.outFile);
  917. }
  918. if (!incoreGraphs)
  919. chkClose(gs->state->curgraph);
  920. gs->state->target = 0;
  921. gs->state->outgraph = 0;
  922. if (gs->opts.verbose)
  923. gvstart_timer();
  924. if (!gs->opts.readAhead)
  925. nextg = nextGraph(gs->ing);
  926. if (gs->opts.verbose && nextg != NULL) {
  927. fprintf(stderr, "Read graph: %.2f secs.\n", gvelapsed_sec());
  928. }
  929. }
  930. }
  931. /* do end */
  932. gs->state->curgraph = 0;
  933. gs->state->curobj = 0;
  934. if (gs->xprog->end_stmt != NULL)
  935. exeval(gs->xprog->prog, gs->xprog->end_stmt, gs->state);
  936. return 0;
  937. }
  938. /** main loop for gvpr
  939. *
  940. * \return 0 on success
  941. */
  942. int gvpr(int argc, char *argv[], gvpropts *uopts) {
  943. gvpr_state_t gvpr_state = {0};
  944. // initialize opts to something that makes freeOpts() a no-op if we fail early
  945. gvpr_state.opts.outFile = stdout;
  946. int rv = gvpr_core(argc, argv, uopts, &gvpr_state);
  947. // free all allocated resources
  948. freeParseProg(gvpr_state.prog);
  949. freeCompileProg(gvpr_state.xprog);
  950. closeGPRState(gvpr_state.state);
  951. if (gvpr_state.ing != NULL) {
  952. closeIngraph(gvpr_state.ing);
  953. }
  954. freeOpts(gvpr_state.opts);
  955. return rv;
  956. }
  957. /**
  958. * @dir lib/gvpr
  959. * @brief graph pattern scanning and processing language, API gvpr.h
  960. */