2 \brief APC Directory Scanner
3 \details This hand-written parser/scanner traverses a directory tree and
4 tokenizes elements of the structure which correspond to APC grammar.
5 The parser is implemented as a 2D stack which populates a list of
6 child directories at each depth, handling only the leaf nodes
7 (regular files) of the directory open at the current depth to
8 conserve memory and speed up traversal.
9 The scanner works with the lexer to lexically analyze text, and
10 assumes the existence of an external 'lex' function
11 \author Jordan Lavatai
13 ----------------------------------------------------------------------------*/
15 #include <stdio.h> //print
16 #include <errno.h> //errno
18 #include <err.h> //warnx
19 #include <stdlib.h> //exit
20 #include <unistd.h> //chdir
21 #include <dirent.h> //opendir
22 #include <unistr.h> //unicode strings
23 #include <string.h> //strlen
25 #include "parser.tab.h"
27 int scanner_init(void);
28 void scanner_quit(void);
29 int scanner_scanpath(char const*);
30 int scanner_scandir(DIR*);
35 int lexer_lexfile(uint8_t const*);
36 #define PUSHTOK(T,L) yypush_parse(apc_pstate, T, L, apc_cstate)
43 { if (apc_pstate
!= NULL
|| apc_cstate
!= NULL
)
45 apc_pstate
= yypstate_new();
46 apc_cstate
= yycstate_new();
47 return (apc_pstate
== NULL
|| apc_cstate
== NULL
);
51 Free initialized memory
55 { yypstate_delete(apc_pstate
);
56 yycstate_delete(apc_cstate
);
61 /* Scan the provided path
62 Changes working directory to the provided pathname and, if successful, sends
63 a directory stream of the provided path to scanner_scandir
66 ( char const* pathname
)
69 if ((dirp
= opendir(pathname
)) == NULL
|| errno
)
70 { fprintf(stderr
, "Path %s could not be accessed\n", pathname
);
75 return scanner_scandir(dirp
);
78 /* Scan directory stream
79 Recursively scans the provided directory, sending CLOPEN and CLCLOSE tokens
80 to the parser when entering new directories (classes)
85 struct dirent
* direntp
;
88 direntp
= readdir(dirp
);
92 { if (*(direntp
->d_name
) == '.') //skip hidden or relative files
93 goto scan_next_dirent
;
94 switch (direntp
->d_type
)
96 printf("lexfile %s\n",direntp
->d_name
);
97 lexer_lexfile((uint8_t*)direntp
->d_name
);
98 goto scan_next_dirent
;
100 lexer_lexfile((uint8_t*)direntp
->d_name
); //lex the dirname
101 printf("lexdir %s\n",direntp
->d_name
);
102 if (chdir(direntp
->d_name
)) //change to the specified dir
105 if ((cdirp
= opendir(".")) == NULL
|| errno
) //open it
107 PUSHTOK(CLOPEN
, NULL
); //push "Open Directory" token
108 printf("Scanner entered [%s]\n",direntp
->d_name
);
109 if(scanner_scandir(cdirp
)) //scan the directory
111 if (chdir("..")) //return to the parent dir
113 PUSHTOK(CLCLOSE
, NULL
); //push "Close Directory" token
114 printf("Scanner returned\n");
115 goto scan_next_dirent
; //continue scan
117 warnx("unknown file %s: ignoring", direntp
->d_name
);
119 goto scan_next_dirent
;
122 return closedir(dirp
);
124 perror("scanner_scandir");