+
+static inline bool try_include(struct psi_cpp *cpp, const char *path, bool *parsed)
+{
+ struct psi_parser_input *include;
+
+ PSI_DEBUG_PRINT(cpp->parser, "PSI: CPP include trying %s\n", path);
+
+ include = psi_parser_open_file(cpp->parser, path, false);
+ if (include) {
+ struct psi_plist *tokens;
+
+ PSI_DEBUG_PRINT(cpp->parser, "PSI: CPP include scanning %s\n", path);
+
+ tokens = psi_parser_scan(cpp->parser, include);
+ if (tokens) {
+ *parsed = psi_cpp_process(cpp, &tokens);
+
+ if (*parsed) {
+ size_t num_tokens = psi_plist_count(tokens);
+
+ ++cpp->expanded;
+ psi_cpp_tokiter_ins_range(cpp, cpp->index,
+ num_tokens, psi_plist_eles(tokens));
+ /* skip already processed tokens */
+ cpp->index += num_tokens;
+ free(tokens);
+ } else {
+ psi_plist_free(tokens);
+ }
+ }
+ free(include);
+
+ zend_hash_str_add_empty_element(&cpp->once, path, strlen(path));
+ return true;
+ }
+ return false;
+}
+
+static inline void include_path(const struct psi_token *file, char **path)
+{
+ if (*file->text == '/') {
+ *path = file->text;
+ } else {
+ char *dir;
+ size_t len;
+
+ strncpy(*path, file->file, PATH_MAX);
+
+ dir = dirname(*path);
+ len = strlen(dir);
+
+ assert(len + file->size + 1 < PATH_MAX);
+
+ memmove(*path, dir, len);
+ (*path)[len] = '/';
+ memcpy(&(*path)[len + 1], file->text, file->size + 1);
+ }
+}
+
+bool psi_cpp_include(struct psi_cpp *cpp, const struct psi_token *file, unsigned flags)
+{
+ bool parsed = false;
+ int f_len = strlen(file->text);
+
+ if (!(flags & PSI_CPP_INCLUDE_NEXT) || *file->text == '/') {
+ /* first try as is, full or relative path */
+ char temp[PATH_MAX], *path = temp;
+
+ include_path(file, &path);
+
+ if ((flags & PSI_CPP_INCLUDE_ONCE) && zend_hash_str_exists(&cpp->once, path, f_len)) {
+ return true;
+ }
+ if (try_include(cpp, path, &parsed)) {
+ /* found */
+ return parsed;
+ }
+ }
+
+ /* look through search paths */
+ if (*file->text != '/') {
+ char path[PATH_MAX];
+ const char *sep;
+ int p_len;
+
+ if ((flags & PSI_CPP_INCLUDE_NEXT) && cpp->search) {
+ if ((sep = strchr(cpp->search, ':'))) {
+ cpp->search = sep + 1;
+ } else {
+ /* point to end of string */
+ cpp->search += strlen(cpp->search);
+ }
+ }
+
+ if (!(flags & PSI_CPP_INCLUDE_NEXT) || !cpp->search) {
+ cpp->search = PSI_G(search_path);
+ }
+
+ do {
+ int d_len;
+
+ sep = strchr(cpp->search, ':');
+ d_len = sep ? sep - cpp->search : strlen(cpp->search);
+
+ if (PATH_MAX > (p_len = snprintf(path, PATH_MAX, "%.*s/%.*s", d_len, cpp->search, f_len, file->text))) {
+ if ((flags & PSI_CPP_INCLUDE_ONCE) && zend_hash_str_exists(&cpp->once, path, p_len)) {
+ return true;
+ }
+ if (try_include(cpp, path, &parsed)) {
+ break;
+ }
+ }
+
+ if (sep) {
+ cpp->search = sep + 1;
+ }
+ } while (sep);
+ }
+
+ return parsed;
+}