xref: /petsc/src/sys/objects/optionsyaml.c (revision 951eb098380074caae4bf47fd8add38d208cc89e)
1 #define PETSC_DESIRE_FEATURE_TEST_MACROS /* for strdup() */
2 #include <petsc/private/petscimpl.h>     /*I  "petscsys.h"  I*/
3 
4 #if defined(PETSC_HAVE_YAML)
5 #include <yaml.h>  /* use external LibYAML */
6 #else
7 #include <../src/sys/yaml/include/yaml.h>
8 #endif
9 
10 static MPI_Comm petsc_yaml_comm = MPI_COMM_NULL; /* only used for parallel error handling */
11 
12 PETSC_STATIC_INLINE MPI_Comm PetscYAMLGetComm(void)
13 {
14   return PetscLikely(petsc_yaml_comm != MPI_COMM_NULL) ? petsc_yaml_comm : (petsc_yaml_comm = PETSC_COMM_SELF);
15 }
16 
17 PETSC_STATIC_INLINE MPI_Comm PetscYAMLSetComm(MPI_Comm comm)
18 {
19   MPI_Comm prev = PetscYAMLGetComm(); petsc_yaml_comm = comm; return prev;
20 }
21 
22 #define TAG(node) ((const char *)((node)->tag))
23 #define STR(node) ((const char *)((node)->data.scalar.value))
24 #define SEQ(node) ((node)->data.sequence.items)
25 #define MAP(node) ((node)->data.mapping.pairs)
26 
27 static PetscErrorCode PetscParseLayerYAML(PetscOptions options, yaml_document_t *doc, yaml_node_t *node)
28 {
29   MPI_Comm         comm = PetscYAMLGetComm();
30   char             name[PETSC_MAX_OPTION_NAME] = "", prefix[PETSC_MAX_OPTION_NAME] = "";
31   PetscErrorCode   ierr;
32 
33   PetscFunctionBegin;
34   if (node->type != YAML_MAPPING_NODE) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected mapping");
35   for (yaml_node_pair_t *pair = MAP(node).start; pair < MAP(node).top; pair++) {
36     yaml_node_t *keynode = yaml_document_get_node(doc, pair->key);
37     yaml_node_t *valnode = yaml_document_get_node(doc, pair->value);
38     PetscBool   isMergeKey,isDummyKey,isIncludeTag;
39 
40     if (!keynode) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
41     if (!valnode) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
42     if (keynode->type != YAML_SCALAR_NODE) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected scalar");
43 
44     /* "<<" is the merge key: don't increment the prefix */
45     ierr = PetscStrcmp(STR(keynode), "<<", &isMergeKey);CHKERRQ(ierr);
46     if (isMergeKey) {
47       if (valnode->type == YAML_SEQUENCE_NODE) {
48         for (yaml_node_item_t *item = SEQ(valnode).start; item < SEQ(valnode).top; item++) {
49           yaml_node_t *itemnode = yaml_document_get_node(doc, *item);
50           if (!itemnode) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
51           if (itemnode->type != YAML_MAPPING_NODE) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected mapping");
52           ierr = PetscParseLayerYAML(options, doc, itemnode);CHKERRQ(ierr);
53         }
54       } else if (valnode->type == YAML_MAPPING_NODE) {
55         ierr = PetscParseLayerYAML(options, doc, valnode);CHKERRQ(ierr);
56       } else SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected sequence or mapping");
57       continue; /* to next pair */
58     }
59 
60     /* "$$*" are treated as dummy keys, we use them for !include tags and to define anchors */
61     ierr = PetscStrbeginswith(STR(keynode), "$$", &isDummyKey);CHKERRQ(ierr);
62     if (isDummyKey) {
63       ierr = PetscStrendswith(TAG(valnode), "!include", &isIncludeTag);CHKERRQ(ierr);CHKERRQ(ierr);
64       if (isIncludeTag) { /* TODO: add proper support relative paths */
65         ierr = PetscOptionsInsertFileYAML(comm, options, STR(valnode), PETSC_TRUE);CHKERRQ(ierr);
66       }
67       continue; /* to next pair */
68     }
69 
70     if (valnode->type == YAML_SCALAR_NODE) {
71       ierr = PetscSNPrintf(name, sizeof(name), "-%s", STR(keynode));CHKERRQ(ierr);
72       ierr = PetscOptionsSetValue(options, name, STR(valnode));CHKERRQ(ierr);
73 
74     } else if (valnode->type == YAML_SEQUENCE_NODE) {
75       PetscSegBuffer seg;
76       char           *buf, *strlist;
77       PetscBool      addSep = PETSC_FALSE;
78 
79       ierr = PetscSegBufferCreate(sizeof(char), PETSC_MAX_PATH_LEN, &seg);CHKERRQ(ierr);
80       for (yaml_node_item_t *item = SEQ(valnode).start; item < SEQ(valnode).top; item++) {
81         yaml_node_t *itemnode = yaml_document_get_node(doc, *item);
82         const char  *itemstr = NULL;
83         size_t       itemlen;
84 
85         if (!itemnode) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
86 
87         if (itemnode->type == YAML_SCALAR_NODE) {
88           itemstr = STR(itemnode);
89 
90         } else if (itemnode->type == YAML_MAPPING_NODE) {
91           yaml_node_pair_t *kvn = itemnode->data.mapping.pairs.start;
92           yaml_node_pair_t *top = itemnode->data.mapping.pairs.top;
93 
94           if (top - kvn > 1) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node value: expected a single key:value pair");
95           if (top - kvn > 0) {
96             yaml_node_t *kn = yaml_document_get_node(doc, kvn->key);
97             yaml_node_t *vn = yaml_document_get_node(doc, kvn->value);
98 
99             if (!kn) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
100             if (!vn) SETERRQ(comm, PETSC_ERR_LIB, "Corrupt YAML document");
101             if (kn->type != YAML_SCALAR_NODE) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected scalar");
102 
103             ierr = PetscStrcmp(STR(kn), "<<", &isMergeKey);CHKERRQ(ierr);
104             if (isMergeKey) SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node value: merge key '<<' not supported here");
105 
106             ierr = PetscStrbeginswith(STR(kn), "$$", &isDummyKey);CHKERRQ(ierr);
107             if (isDummyKey) continue;
108             itemstr = STR(kn);
109           }
110 
111           ierr = PetscSNPrintf(prefix,sizeof(prefix), "%s_", STR(keynode));CHKERRQ(ierr);
112           ierr = PetscOptionsPrefixPush(options, prefix);CHKERRQ(ierr);
113           ierr = PetscParseLayerYAML(options, doc, itemnode);CHKERRQ(ierr);
114           ierr = PetscOptionsPrefixPop(options);CHKERRQ(ierr);
115 
116         } else SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected scalar or mapping");
117 
118         ierr = PetscStrlen(itemstr, &itemlen);CHKERRQ(ierr);
119         if (itemlen) {
120           if (addSep) {
121             ierr = PetscSegBufferGet(seg, 1, &buf);CHKERRQ(ierr);
122             ierr = PetscArraycpy(buf, ",", 1);CHKERRQ(ierr);
123           }
124           ierr = PetscSegBufferGet(seg, itemlen, &buf);CHKERRQ(ierr);
125           ierr = PetscArraycpy(buf, itemstr, itemlen);CHKERRQ(ierr);
126           addSep = PETSC_TRUE;
127         }
128       }
129       ierr = PetscSegBufferGet(seg, 1, &buf);CHKERRQ(ierr);
130       ierr = PetscArrayzero(buf, 1);CHKERRQ(ierr);
131       ierr = PetscSegBufferExtractAlloc(seg, &strlist);CHKERRQ(ierr);
132       ierr = PetscSegBufferDestroy(&seg);CHKERRQ(ierr);
133 
134       ierr = PetscSNPrintf(name, sizeof(name), "-%s", STR(keynode));CHKERRQ(ierr);
135       ierr = PetscOptionsSetValue(options, name, strlist);CHKERRQ(ierr);
136       ierr = PetscFree(strlist);CHKERRQ(ierr);
137 
138     } else if (valnode->type == YAML_MAPPING_NODE) {
139       ierr = PetscSNPrintf(prefix,sizeof(prefix), "%s_", STR(keynode));CHKERRQ(ierr);
140       ierr = PetscOptionsPrefixPush(options, prefix);CHKERRQ(ierr);
141       ierr = PetscParseLayerYAML(options, doc, valnode);CHKERRQ(ierr);
142       ierr = PetscOptionsPrefixPop(options);CHKERRQ(ierr);
143 
144     } else SETERRQ(comm, PETSC_ERR_SUP, "Unsupported YAML node type: expected scalar, sequence or mapping");
145   }
146   PetscFunctionReturn(0);
147 }
148 
149 /*@C
150    PetscOptionsInsertStringYAML - Inserts YAML-formatted options into the database from a string
151 
152    Logically Collective
153 
154    Input Parameter:
155 +  options - options database, use NULL for default global database
156 -  in_str - YAML-formatted string options
157 
158    Level: intermediate
159 
160 .seealso: PetscOptionsSetValue(), PetscOptionsView(), PetscOptionsHasName(), PetscOptionsGetInt(),
161           PetscOptionsGetReal(), PetscOptionsGetString(), PetscOptionsGetIntArray(), PetscOptionsBool(),
162           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
163           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
164           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
165           PetscOptionsFList(), PetscOptionsEList(), PetscOptionsInsertFile(), PetscOptionsInsertFileYAML()
166 @*/
167 PetscErrorCode PetscOptionsInsertStringYAML(PetscOptions options,const char in_str[])
168 {
169   MPI_Comm        comm = PetscYAMLGetComm();
170   yaml_parser_t   parser;
171   yaml_document_t doc;
172   yaml_node_t     *root;
173   PetscErrorCode  ierr;
174 
175   PetscFunctionBegin;
176   if (!in_str) in_str = "";
177   ierr = !yaml_parser_initialize(&parser); if (ierr) SETERRQ(comm, PETSC_ERR_LIB, "YAML parser initialization error");
178   yaml_parser_set_input_string(&parser, (const unsigned char *)in_str, strlen(in_str));
179   do {
180     ierr = !yaml_parser_load(&parser, &doc); if (ierr) SETERRQ(comm, PETSC_ERR_LIB, "YAML parser loading error");
181     root = yaml_document_get_root_node(&doc);
182     if (root) {
183       ierr = PetscParseLayerYAML(options, &doc, root);CHKERRQ(ierr);
184     }
185     yaml_document_delete(&doc);
186   } while (root);
187   yaml_parser_delete(&parser);
188   PetscFunctionReturn(0);
189 }
190 
191 /*@C
192   PetscOptionsInsertFileYAML - Insert a YAML-formatted file in the option database
193 
194   Collective
195 
196   Input Parameter:
197 +   comm - the processes that will share the options (usually PETSC_COMM_WORLD)
198 .   options - options database, use NULL for default global database
199 .   file - name of file
200 -   require - if PETSC_TRUE will generate an error if the file does not exist
201 
202   Only a small subset of the YAML standard is implemented. Non-scalar keys are NOT supported;
203   aliases and the merge key "<<" are.
204   The algorithm recursively parses the yaml file, pushing and popping prefixes
205   and inserting key + values pairs using PetscOptionsSetValue().
206 
207   PETSc will generate an error condition that stops the program if a YAML error
208   is detected, hence the user should check that the YAML file is valid before
209   supplying it, for instance at http://www.yamllint.com/ .
210 
211   Inspired by https://stackoverflow.com/a/621451
212 
213   Level: intermediate
214 
215 .seealso: PetscOptionsSetValue(), PetscOptionsView(), PetscOptionsHasName(), PetscOptionsGetInt(),
216           PetscOptionsGetReal(), PetscOptionsGetString(), PetscOptionsGetIntArray(), PetscOptionsBool(),
217           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
218           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
219           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
220           PetscOptionsFList(), PetscOptionsEList(), PetscOptionsInsertFile(), PetscOptionsInsertStringYAML()
221 @*/
222 PetscErrorCode PetscOptionsInsertFileYAML(MPI_Comm comm,PetscOptions options,const char file[],PetscBool require)
223 {
224   int            yamlLength = -1;
225   char          *yamlString = NULL;
226   MPI_Comm       prev;
227   PetscMPIInt    rank;
228   PetscErrorCode ierr;
229 
230   PetscFunctionBegin;
231   ierr = MPI_Comm_rank(comm, &rank);CHKERRMPI(ierr);
232   if (!rank) {
233     char   fpath[PETSC_MAX_PATH_LEN];
234     char   fname[PETSC_MAX_PATH_LEN];
235     FILE  *fd;
236     size_t rd;
237 
238     ierr = PetscStrreplace(PETSC_COMM_SELF, file, fpath, sizeof(fpath));CHKERRQ(ierr);
239     ierr = PetscFixFilename(fpath, fname);CHKERRQ(ierr);
240 
241     fd = fopen(fname, "r");
242     if (fd) {
243       fseek(fd, 0, SEEK_END);
244       yamlLength = (int)ftell(fd);
245       fseek(fd, 0, SEEK_SET);
246       if (yamlLength < 0) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to query size of YAML file: %s", fname);
247       ierr = PetscMalloc1(yamlLength+1, &yamlString);CHKERRQ(ierr);
248       rd = fread(yamlString, 1, (size_t)yamlLength, fd);
249       if (rd != (size_t)yamlLength) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Unable to read entire YAML file: %s", fname);
250       yamlString[yamlLength] = 0;
251       fclose(fd);
252     }
253   }
254 
255   ierr = MPI_Bcast(&yamlLength, 1, MPI_INT, 0, comm);CHKERRMPI(ierr);
256   if (require && yamlLength < 0) SETERRQ1(comm, PETSC_ERR_FILE_OPEN, "Unable to open YAML option file: %s\n", file);
257   if (yamlLength < 0) PetscFunctionReturn(0);
258 
259   if (rank) {ierr = PetscMalloc1(yamlLength+1, &yamlString);CHKERRQ(ierr);}
260   ierr = MPI_Bcast(yamlString, yamlLength+1, MPI_CHAR, 0, comm);CHKERRMPI(ierr);
261 
262   prev = PetscYAMLSetComm(comm);
263   ierr = PetscOptionsInsertStringYAML(options, yamlString);CHKERRQ(ierr);
264   (void) PetscYAMLSetComm(prev);
265 
266   ierr = PetscFree(yamlString);CHKERRQ(ierr);
267   PetscFunctionReturn(0);
268 }
269 
270 
271 #if !defined(PETSC_HAVE_YAML)
272 
273 /*
274 #if !defined(PETSC_HAVE_STRDUP)
275 #define strdup(s) (char*)memcpy(malloc(strlen(s)+1),s,strlen(s)+1)
276 #endif
277 */
278 
279 /* Embed LibYAML in this compilation unit */
280 #include <../src/sys/yaml/src/api.c>
281 #include <../src/sys/yaml/src/loader.c>
282 #include <../src/sys/yaml/src/parser.c>
283 #include <../src/sys/yaml/src/reader.c>
284 #include <../src/sys/yaml/src/scanner.c>
285 
286 /* Silence a few unused-function warnings */
287 static PETSC_UNUSED void petsc_yaml_unused(void)
288 {
289   (void)yaml_parser_scan;
290   (void)yaml_document_get_node;
291   (void)yaml_parser_set_encoding;
292   (void)yaml_parser_set_input;
293   (void)yaml_parser_set_input_file;
294 }
295 
296 #endif
297