예제 #1
0
파일: yaml.c 프로젝트: Perkville/uwsgi
void uwsgi_yaml_config(char *file, char *magic_table[]) {

	size_t len = 0;
	char *yaml;

	int in_uwsgi_section = 0;

	char *key = NULL;
	char *val = NULL;

	char *section_asked = "uwsgi";
	char *colon;

	if (uwsgi_check_scheme(file)) {
		colon = uwsgi_get_last_char(file, '/');
		colon = uwsgi_get_last_char(colon, ':');
	}
	else {
		colon = uwsgi_get_last_char(file, ':');
	}

	if (colon) {
		colon[0] = 0;
		if (colon[1] != 0) {
			section_asked = colon + 1;
		}
	}

	uwsgi_log_initial("[uWSGI] getting YAML configuration from %s\n", file);

	yaml = uwsgi_open_and_read(file, &len, 1, magic_table);

#ifdef UWSGI_LIBYAML
	yaml_parser_t parser;
	yaml_token_t token;
	int status = 0;
	int parsing = 1;

	if (!yaml_parser_initialize(&parser)) {
		uwsgi_log("unable to initialize YAML parser (libyaml)\n");
		exit(1);
	}

	yaml_parser_set_input_string(&parser, (unsigned char *) yaml, (size_t) len - 1);

	while (parsing) {
		if (!yaml_parser_scan(&parser, &token)) {
			uwsgi_log("error parsing YAML file: %s (%c)\n", parser.problem, yaml[parser.problem_offset]);
			exit(1);
		}
		switch (token.type) {
		case YAML_STREAM_END_TOKEN:
			parsing = 0;
			break;
		case YAML_KEY_TOKEN:
			status = 1;
			break;
		case YAML_VALUE_TOKEN:
			status = 2;
			break;
		case YAML_FLOW_SEQUENCE_START_TOKEN:
		case YAML_BLOCK_SEQUENCE_START_TOKEN:
			status = 3;
			break;
		case YAML_BLOCK_MAPPING_START_TOKEN:
			if (!in_uwsgi_section) {
				if (key) {
					if (!strcmp(section_asked, key)) {
						in_uwsgi_section = 1;
					}
				}
			}
			break;
		case YAML_BLOCK_END_TOKEN:
			if (in_uwsgi_section) {
				parsing = 0;
				break;
			}
			break;
		case YAML_SCALAR_TOKEN:
		case YAML_FLOW_ENTRY_TOKEN:
		case YAML_BLOCK_ENTRY_TOKEN:
			if (status == 1) {
				key = (char *) token.data.scalar.value;
			}
			else if (status == 2) {
				val = (char *) token.data.scalar.value;
				if (key && val && in_uwsgi_section) {
					add_exported_option(key, val, 0);
				}
				status = 0;
			}
			else if (status == 3) {
				val = (char *) token.data.scalar.value;
				if (key && val && in_uwsgi_section) {
					add_exported_option(key, val, 0);
				}
			}
			else {
				uwsgi_log("unsupported YAML token in %s block\n", section_asked);
				parsing = 0;
				break;
			}
			break;
		default:
			status = 0;
		}
	}

#else
	int depth;
	int current_depth = 0;
	int lines = 1;
	char *yaml_line;
	char *section = "";


	while (len) {
		yaml_line = yaml_get_line(yaml, len);
		if (yaml_line == NULL) {
			break;
		}
		lines++;

		// skip empty line
		if (yaml[0] == 0)
			goto next;
		depth = yaml_get_depth(yaml);
		if (depth <= current_depth) {
			current_depth = depth;
			// end the parsing cycle
			if (in_uwsgi_section)
				return;
		}
		else if (depth > current_depth && !in_uwsgi_section) {
			goto next;
		}

		key = yaml_lstrip(yaml);
		// skip empty line
		if (key[0] == 0)
			goto next;

		// skip list and {} defined dict
		if (key[0] == '-' || key[0] == '[' || key[0] == '{') {
			if (in_uwsgi_section)
				return;
			goto next;
		}

		if (!in_uwsgi_section) {
			section = strchr(key, ':');
			if (!section)
				goto next;
			section[0] = 0;
			if (!strcmp(key, section_asked)) {
				in_uwsgi_section = 1;
			}
		}
		else {
			// get dict value       
			val = strstr(key, ": ");
			if (!val) {
				val = strstr(key, ":\t");
			}
			if (!val)
				return;
			// get the right key
			val[0] = 0;
			// yeah overengineering....
			yaml_rstrip(key);

			val = yaml_lstrip(val + 2);
			yaml_rstrip(val);

			//uwsgi_log("YAML: %s = %s\n", key, val);

			add_exported_option((char *) key, val, 0);
		}
next:
		len -= (yaml_line - yaml);
		yaml += (yaml_line - yaml);

	}
#endif

	if (colon) colon[0] = ':';

}
예제 #2
0
int main(int argc, char* argv[])
{
    yaml_parser_t parser;
    yaml_event_t event;
    if(!yaml_parser_initialize(&parser)) {
        fputs("Failed to initialize yaml parser", stderr);
        return 1;
    }
    FILE *input = fopen(argv[1], "r");
    if(input == NULL) {
        fputs("Can't open config file", stderr);
        return 1;
    }
    yaml_parser_set_input_file(&parser, input);
    do {
        yaml_parser_parse(&parser, &event);
        switch(event.type) {
        case YAML_NO_EVENT:
		puts("No event!\n");
            break;
            /* Stream start/end */
        case YAML_STREAM_START_EVENT:
            puts("STREAM START");
            break;
        case YAML_STREAM_END_EVENT:
            puts("STREAM END");
            break;
            /* Block delimeters */
        case YAML_DOCUMENT_START_EVENT:
            puts("<b>Start Document</b>");
            break;
        case YAML_DOCUMENT_END_EVENT:
            puts("<b>End Document</b>");
            break;
        case YAML_SEQUENCE_START_EVENT:
            puts("<b>Start Sequence</b>");
            break;
        case YAML_SEQUENCE_END_EVENT:
            puts("<b>End Sequence</b>");
            break;
        case YAML_MAPPING_START_EVENT:
            puts("<b>Start Mapping</b>");
            break;
        case YAML_MAPPING_END_EVENT:
            puts("<b>End Mapping</b>");
            break;
            /* Data */
        case YAML_ALIAS_EVENT:
            printf("Got alias (anchor %s)\n", event.data.alias.anchor);
            break;
        case YAML_SCALAR_EVENT:
            printf("Got scalar (value %s)\n", event.data.scalar.value);
            break;
        default:
            printf("Unhandled event %d\n", event.type);
        }
	if(parser.error != YAML_NO_ERROR) {
            printf("ERROR: yaml_error_type_e %d: %s %s at (line: %d, col: %d)\n", parser.error, parser.context, parser.problem, parser.problem_mark.line, parser.problem_mark.column);
	    return parser.error;
	}
        if(event.type != YAML_STREAM_END_EVENT)
            yaml_event_delete(&event);
    } while(event.type != YAML_STREAM_END_EVENT);
    yaml_event_delete(&event);
    yaml_parser_delete(&parser);
    fclose(input);
    return 0;
}
예제 #3
0
파일: urlfile.c 프로젝트: fijal/wideload
/**
 * Parse a URL file into a requests
 */
requests parse_urls(const char* url_filename)
{
    unsigned long i;

    requests reqs;
    request* req;

    list* req_list;
    node* n;
    FILE* urls;
    char done = 0;

    yaml_parser_t parser;
    yaml_event_t event;

    reqs.count = 0;
    reqs.reqs = NULL;
    req_list = list_new();

    urls = fopen(url_filename, "r");
    yaml_parser_initialize(&parser);
    yaml_parser_set_input_file(&parser, urls);

    while (!done) {
        if (!yaml_parser_parse(&parser, &event)) {
            break;
        } else {
            switch (event.type) {
                case YAML_MAPPING_START_EVENT:
                    // printf("event.type: MAPPING_START\n");
                    // printf("  calling parse_request()\n");
                    if ((req = parse_request(&parser)) == NULL) {
                        done = 2;
                    } else {
                        // printf("  got a good request!\n");
                        n = list_node_new(req);
                        list_push(req_list, n);
                    }
                    break;

                case YAML_STREAM_START_EVENT:
                case YAML_DOCUMENT_START_EVENT:
                case YAML_SEQUENCE_START_EVENT:
                case YAML_SEQUENCE_END_EVENT:
                    break;

                case YAML_STREAM_END_EVENT:
                case YAML_DOCUMENT_END_EVENT:
                    done = 1;
                    break;

                default:
                    // printf("got event type %d\n", event.type);
                    fprintf(stderr, "Malformed URLS_FILE at pos: %lu\n", (unsigned long)parser.offset);
                    done = 2;
            }
        }
        yaml_event_delete(&event);
    }
    yaml_parser_delete(&parser);

    if (done == 2) {
        fprintf(stderr, "Error parsing URLs file\n");
        exit(1);
    }

    if (!(reqs.reqs = malloc(sizeof(request) * req_list->length))) {
        list_free(req_list, 1);
        exit(2);
    }

    n = req_list->head;
    for (i=0; i<req_list->length; i++) {
        req = (request *)(n->data);
        reqs.reqs[i].method = req->method;
        reqs.reqs[i].url = req->url;
        reqs.reqs[i].payload_length = req->payload_length;
        reqs.reqs[i].payload = req->payload;
        reqs.reqs[i].headers = req->headers;
        reqs.reqs[i].num_headers = req->num_headers;
        reqs.reqs[i].curl_headers = req->curl_headers;
        // printf("set request %lu with url %s\n", i, reqs.reqs[i].url);
        n = n->next;
    }
    reqs.count = req_list->length;
    list_free(req_list, 0);

    return reqs;
}
예제 #4
0
int ParseSpecFile(rsf_settings *set, char *path, dname_struct *dname)
{
	ctr_yaml_context *ctx = malloc(sizeof(ctr_yaml_context));
	InitYamlContext(ctx);

	/* Set Specfile Type */
	
	/* Create the Parser object. */
	yaml_parser_initialize(&ctx->parser);

	/* Set a file input. */
	FILE *input = fopen(path,"rb");
	yaml_parser_set_input_file(&ctx->parser, input);
	
	
	ctx->dname = dname;
	ctx->IsSequence = false;
	ctx->IsKey = true;
	ctx->prev_event = 0;
	ctx->Level = 0;
	
	
	/* Read the event sequence. */
	while (!ctx->done) {
		/* Get the next event. */
		GetEvent(ctx);
		if(ctx->error) goto error;
		
		/* Proccess Event */
		
		
		if(EventIsScalar(ctx)){
			EvaluateRSF(set,ctx);
			if(ctx->error) goto error;
			break;
		}
		/*
		if((ctx->event.type == YAML_SEQUENCE_START_EVENT|| ctx->event.type == YAML_MAPPING_START_EVENT) && ctx->prev_event == YAML_SCALAR_EVENT) printf(":\n");
		if(ctx->event.type == YAML_SCALAR_EVENT){
			if(ctx->IsSequence){
				printf(" - %s\n",ctx->event.data.scalar.value);
			}
			else{
				if(!ctx->IsKey) printf(": %s\n",ctx->event.data.scalar.value);
				else printf("%s",ctx->event.data.scalar.value);
			}			
		}
		*/
		
		/* Finish Event */
		FinishEvent(ctx);
		if(ctx->error) goto error;
	}

	/* Destroy the Parser object. */
	yaml_parser_delete(&ctx->parser);
	fclose(input);
	return 0;

	/* On error. */
	error:
	fprintf(stderr,"[RSF ERROR] Error Proccessing RSF file\n");
	
	/* Destroy the Parser object. */
	yaml_parser_delete(&ctx->parser);
	fclose(input);
	return ctx->error;
}
예제 #5
0
/**
 * @brief [brief description]
 * @details [long description]
 *
 * @param fh [description]
 * @param configuration [description]
 *
 * @return [description]
 */
int ocs_configuration_parse(FILE* fh, ocs_configuration_t* configuration)
{
  assert(fh != NULL);
  assert(configuration != NULL);

  yaml_parser_t parser;
  yaml_token_t token;

  if (!yaml_parser_initialize(&parser))
  {
    /* Failed to initialize parser */
    return(OCS_ERROR);
  }

  /* */
  yaml_parser_set_input_file(&parser, fh);

  /* */
  enum ocs_yaml_reader_state_t state = OCS_YAML_READER_STATE_UNDEFINED;

  /* */
  char** data_ptr = NULL;

  /* */
  char* token_scalar_value = NULL;

  do
  {
    yaml_parser_scan(&parser, &token);
    switch(token.type)
    {
    case YAML_KEY_TOKEN:
      state = OCS_YAML_READER_STATE_KEY_TOKEN;
      break;
    case YAML_VALUE_TOKEN:
      state = OCS_YAML_READER_STATE_VALUE_TOKEN;
      break;
    case YAML_SCALAR_TOKEN:
      token_scalar_value = (char*) token.data.scalar.value;
      if (state == OCS_YAML_READER_STATE_KEY_TOKEN) {
        if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_USERNAME))
        {
          data_ptr = &(configuration->username);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_AUTH))
        {
          data_ptr = &(configuration->auth);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_EMAIL))
        {
          data_ptr = &(configuration->email);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_SERVER))
        {
          data_ptr = &(configuration->server);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_PORT))
        {
          data_ptr = &(configuration->port);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_PATH))
        {
          data_ptr = &(configuration->path);
        }
        else if (!strcmp(token_scalar_value, OCS_CONFIGURATION_TOKEN_TAGS))
        {
          data_ptr = &(configuration->tags);
        }
        else
        {
          /* Unrecognised key */
          return(OCS_ERROR);
        }
      }
      else if (state == OCS_YAML_READER_STATE_VALUE_TOKEN)
      {
	     *data_ptr = strdup(token_scalar_value);
	  }
      break;
    default:
      break;
    }
    if (token.type != YAML_STREAM_END_TOKEN)
    {
      yaml_token_delete(&token);
    }
  } while (token.type != YAML_STREAM_END_TOKEN);

  /* Cleanup. */
  yaml_token_delete(&token);
  yaml_parser_delete(&parser);

  return(OCS_SUCCESS);
}
예제 #6
0
int getServiceFromYAML(maps* conf, char* file,service** service,char *name){
  FILE *fh = fopen("test.yml", "r");
  if(current_content!=NULL){
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
#ifdef DEBUG_SERVICE_CONF
  fprintf(stderr,"(STARTING)FREE current_element\n");
#endif
  if(current_element!=NULL){
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  my_service=NULL;
  
  my_service=*service;
  my_service->name=strdup(name);
  my_service->content=NULL;
  my_service->metadata=NULL;
  my_service->inputs=NULL;
  my_service->outputs=NULL;
  fh = fopen(file,"r");
  if (fh==NULL){
    fprintf(stderr,"error : file not found\n") ;
    return -1;
  }
  yaml_parser_t parser;
  yaml_token_t  token;   /* new variable */

  /* Initialize parser */
  if(!yaml_parser_initialize(&parser))
    fputs("Failed to initialize parser!\n", stderr);
  if(fh == NULL)
    fputs("Failed to open file!\n", stderr);
  /* Set input file */
  yaml_parser_set_input_file(&parser, fh);
  /* BEGIN new code */
  int level=0;
  int plevel=level;
  int ilevel=-1;
  int blevel=-1;
  int ttype=0;
  int wait_metadata=-1;
  char *cur_key;
  do {
    yaml_parser_scan(&parser, &token);
    switch(token.type)
    {
    /* Stream start/end */
    case YAML_STREAM_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("STREAM START"); 
#endif
      break;
    case YAML_STREAM_END_TOKEN:   
#ifdef DEBUG_YAML
      puts("STREAM END");   
#endif
      break;
    /* Token types (read before actual token) */
    case YAML_KEY_TOKEN:   
#ifdef DEBUG_YAML
      printf("(Key token)   "); 
#endif
      ttype=0;
      break;
    case YAML_VALUE_TOKEN: 
#ifdef DEBUG_YAML
      printf("(Value token) "); 
#endif
      ttype=1;
      break;
    /* Block delimeters */
    case YAML_BLOCK_SEQUENCE_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("<b>Start Block (Sequence)</b>"); 
#endif
      break;
    case YAML_BLOCK_ENTRY_TOKEN:          
#ifdef DEBUG_YAML
      puts("<b>Start Block (Entry)</b>");    
#endif
      break;
    case YAML_BLOCK_END_TOKEN:      
      blevel--;
      if(ilevel>=0)
	ilevel--;
#ifdef DEBUG_YAML
      printf("<b>End block</b> (%d,%d,%d,%d)\n", blevel,level,ilevel,ttype); 
#endif
      break;
    /* Data */
    case YAML_BLOCK_MAPPING_START_TOKEN:  
#ifdef DEBUG_YAML
      puts("[Block mapping]");            
#endif
      blevel++;
      break;
    case YAML_SCALAR_TOKEN:  
      if(ttype==0){
	cur_key=zStrdup((char *)token.data.scalar.value);
      }
      if(ttype==1){
	if(current_content==NULL){
	  current_content=createMap(cur_key,(char *)token.data.scalar.value);
	}else{
	  addToMap(current_content,cur_key,(char *)token.data.scalar.value);
	}
	free(cur_key);
	cur_key=NULL;
      }

      if(ttype==0 && blevel==0 && level==0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0 && blevel==0){
	addMapToMap(&my_service->content,current_content);
#ifdef DEBUG_YAML
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && blevel>0 && level>0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0){
	if(current_element->content==NULL && current_content!=NULL)
	  addMapToMap(&current_element->content,current_content);
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"inputs")==0 && blevel==0){
	if(wait_metadata>0){
	  addMapToMap(&my_service->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL && my_service->content==NULL)
	    addMapToMap(&my_service->content,current_content);
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=false;
	level++;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"outputs")==0 && blevel==1){
	level++;
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    addMapToIoType(&current_element->supported,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    dumpMap(current_content);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"default")==0){
	ilevel=0;
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"supported")==0){
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	    }
	    addMapToMap(&current_element->supported->content,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
	ilevel=1;
      }


      if(strncasecmp((char *)token.data.scalar.value,"ComplexData",11)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralData",10)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"ComplexOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralOutput",12)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxData",12)==0){
	current_element->format=zStrdup((char *)token.data.scalar.value);
	free(cur_key);
	cur_key=NULL;
	if(wait_metadata>0 && current_content!=NULL){
	  addMapToMap(&current_element->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL){
	    addMapToMap(&current_element->content,current_content);
	  }
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
#ifdef DEBUG_YAML
	dumpElements(current_element);
#endif
      }

      if(blevel==1 && level==1){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(my_service->inputs==NULL)
	    my_service->inputs=dupElements(current_element);
	  else
	    addToElements(&my_service->inputs,current_element);
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }
      if(blevel==1 && level==2){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(plevel==level){
	    if(my_service->outputs==NULL)
	      my_service->outputs=dupElements(current_element);
	    else
	      addToElements(&my_service->outputs,current_element);
	  }else{
	    if(my_service->inputs==NULL)
	      my_service->inputs=dupElements(current_element);
	    else
	      addToElements(&my_service->inputs,current_element);
	  }
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }


#ifdef DEBUG_YAML
      printf("scalar %s (%d,%d,%d,%d,%d)\n", token.data.scalar.value,blevel,level,plevel,ilevel,ttype); 
#endif
      break;
    /* Others */
    default:
      if(token.type==0){
	char tmp[1024];
	sprintf(tmp,"Wrong charater found in %s: \\t",name);
	setMapInMaps(conf,"lenv","message",tmp);
	return -1;
      }
#ifdef DEBUG_YAML
      printf("Got token of type %d\n", token.type);
#endif
      break;
    }
    if(token.type != YAML_STREAM_END_TOKEN )
      yaml_token_delete(&token);
  } while(token.type != YAML_STREAM_END_TOKEN);
  yaml_token_delete(&token);


#ifdef DEBUG_YAML
  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
  if(current_element!=NULL && current_content!=NULL){
    if(current_element->defaults==NULL){
      current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
      current_element->defaults->content=NULL;
      current_element->defaults->next=NULL;
      addMapToMap(&current_element->defaults->content,current_content);
    }else{
      if(current_element->supported==NULL){
	current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	current_element->supported->content=NULL;
	current_element->supported->next=NULL;
	addMapToMap(&current_element->supported->content,current_content);
      }else
	addMapToIoType(&current_element->supported,current_content);
    }
#ifdef DEBUG_YAML
    dumpMap(current_content);
    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
  if(current_element!=NULL){
    if(my_service->outputs==NULL)
      my_service->outputs=dupElements(current_element);
    else
      addToElements(&my_service->outputs,current_element);
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  /* END new code */

  /* Cleanup */
  yaml_parser_delete(&parser);
  fclose(fh);

#ifdef DEBUG_YAML
  dumpService(my_service);
#endif
  *service=my_service;

  return 1;
}
예제 #7
0
파일: multi_core.c 프로젝트: kristrev/multi
static uint8_t multi_core_parse_config(uint8_t *cfg_filename){
    yaml_parser_t parser;
    yaml_event_t event;
    FILE *cfgfile = NULL;
    uint8_t error = 0;
    struct multi_link_info_static *mlis;
      
    //Only in use when a configuration file is present
    TAILQ_INIT(&multi_shared_static_links);

    if((cfgfile = fopen(cfg_filename, "rb")) == NULL){
        MULTI_DEBUG_PRINT_SYSLOG(stderr, "Could not open configuration file\n");
        error = 1;
        return error;
    }

    //Initialized the parser
    assert(yaml_parser_initialize(&parser));
    yaml_parser_set_input_file(&parser, cfgfile);

    while(1){
        if(!yaml_parser_parse(&parser, &event)){
            MULTI_DEBUG_PRINT_SYSLOG(stderr, "Parsing failed\n");
            error = 1;
            break;
        }

        if(event.type == YAML_STREAM_END_EVENT){
            //LibYAML might allocate memory for events and so forth. Must 
            //therefore free
            yaml_event_delete(&event);
            break;
        } else if(event.type == YAML_SCALAR_EVENT){
            if(strlen(event.data.scalar.value) > IFNAMSIZ){
                MULTI_DEBUG_PRINT_SYSLOG(stderr, "Interface name is too long\n");
                error = 1;
                break;
            }

            //The outer loop should only see scalars, which is the interface
            //names
            mlis = (struct multi_link_info_static *) 
                malloc(sizeof(struct multi_link_info_static));
            memset(mlis, 0, sizeof(*mlis));
            mlis->metric = 0;
            memcpy(mlis->dev_name, event.data.scalar.value, 
                    strlen(event.data.scalar.value) + 1);
            yaml_event_delete(&event);

            //Make sure next event is mapping!
            if(!yaml_parser_parse(&parser, &event)){
                MULTI_DEBUG_PRINT_SYSLOG(stderr, "Parsing failed\n");
                error = 1;
                break;
            } else if(event.type != YAML_MAPPING_START_EVENT){
                MULTI_DEBUG_PRINT_SYSLOG(stderr, "Configuration file is incorrect." 
                        "No information for interface\n");
                error = 1;
                break;
            }
            
            if(multi_core_parse_iface_info(mlis, &parser)){
                MULTI_DEBUG_PRINT_SYSLOG(stderr, 
                        "Parsing of configuration file failed\n");
                error = 1;
                break;
            } else {
                TAILQ_INSERT_TAIL(&multi_shared_static_links, mlis, 
                        list_ptr);
                MULTI_DEBUG_PRINT_SYSLOG(stderr, "Interface %s added to static list\n", 
                        mlis->dev_name);
            }
        }
    }

    yaml_parser_delete(&parser);
    fclose(cfgfile);

    return error;
}
예제 #8
0
파일: test_ifmap.c 프로젝트: britram/qof
int main (int argc, char* argv[])
{
    qfIfMap_t       map;
    yaml_parser_t   parser;
    
    FILE            *mapfile, *testfile;
    
    static char     testbuf[1024];
    static char     addrbuf[40];
    
    yfFlowKey_t     testkey;
    
    uint32_t        addr4;
    uint8_t         ingress, egress;
    
    int rv;
    
    // check args
    if (argc != 3) {
        fprintf(stdout, "Usage: test_ifmap mapfile testfile\n");
        return 1;
    }
    
    // initialize map
    qfIfMapInit(&map);

    // initilize parser
    memset(&parser, 0, sizeof(parser));
    if (!yaml_parser_initialize(&parser)) {
        print_parser_error(stderr, &parser, NULL, NULL);
        return 1;
    }
    
    // open and bind mapfile
    if (!(mapfile = fopen(argv[1], "r"))) {
        fprintf(stderr, "error opening mapfile: %s\n", strerror(errno));
        return 1;
    }
    yaml_parser_set_input_file(&parser, mapfile);

    // parse the mapfile
    fprintf(stdout, "Parsing mapfile %s...\n", argv[1]); 
    if ((rv = parse_ifmap(&map, &parser, argv[1])) != 0) {
        return rv;
    }
    
    fprintf(stdout, "Mapfile parse successful:\n");
    
    qfIfMapDump(stdout, &map);
    
    // open and parse the testfile
    if (!(testfile = fopen(argv[2], "r"))) {
        fprintf(stderr, "error opening testfile: %s\n", strerror(errno));
        return 1;
    }
    
    while (fgets(testbuf, sizeof(testbuf), testfile)) {

        // initialize the testkey
        memset(&testkey, 0, sizeof(testkey));

        if (strchr(testbuf, ':')) {
            if ((sscanf(testbuf, " %39[0-9a-fA-F:.]", addrbuf) == 1) &&
                (inet_pton(AF_INET6, addrbuf, testkey.addr.v6.sip) == 1))
            {
                testkey.version = 6;
                memcpy(testkey.addr.v6.dip, testkey.addr.v6.sip, sizeof(testkey.addr.v6.dip));
                inet_ntop(AF_INET6, testkey.addr.v6.sip, addrbuf, sizeof(addrbuf));
            } else {
                fprintf(stdout, "can't parse IPv6 address %40s\n", testbuf);
                continue;
            }
        } else {
            if ((sscanf(testbuf, " %15[0-9.]", addrbuf) == 1) &&
                (inet_pton(AF_INET, addrbuf, &addr4) == 1))
            {
                testkey.version = 4;
                testkey.addr.v4.sip = ntohl(addr4);
                testkey.addr.v4.dip = ntohl(addr4);
                inet_ntop(AF_INET, &addr4, addrbuf, sizeof(addrbuf));
            } else {
                fprintf(stdout, "can't parse IPv4 address %40s\n", testbuf);
                continue;
            }
        }
        
        qfIfMapAddresses(&map, &testkey, &ingress, &egress);
        fprintf(stdout, "%40s in %3u out %3u\n", addrbuf, ingress, egress);
    }
}
예제 #9
0
/*
 * This is the main Load function.
 * It takes a yaml stream and turns it into 0 or more Perl objects.
 */
void
Load(SV *yaml_sv)
{
    dXSARGS;
    perl_yaml_loader_t loader;
    SV *node;
    const unsigned char *yaml_str;
    STRLEN yaml_len;

    yaml_str = (const unsigned char *)SvPV_const(yaml_sv, yaml_len);

    if (DO_UTF8(yaml_sv)) {
        yaml_sv = sv_mortalcopy(yaml_sv);
        if (!sv_utf8_downgrade(yaml_sv, TRUE))
            croak("%s", "Wide character in YAML::XS::Load()");
        yaml_str = (const unsigned char *)SvPV_const(yaml_sv, yaml_len);
    }

    sp = mark;
    if (0 && (items || ax)) {} /* XXX Quiet the -Wall warnings for now. */

    yaml_parser_initialize(&loader.parser);
    loader.document = 0;
    yaml_parser_set_input_string(
        &loader.parser,
        yaml_str,
        yaml_len
    );

    /* Get the first event. Must be a STREAM_START */
    if (!yaml_parser_parse(&loader.parser, &loader.event))
        goto load_error;
    if (loader.event.type != YAML_STREAM_START_EVENT)
        croak("%sExpected STREAM_START_EVENT; Got: %d != %d",
            ERRMSG,
            loader.event.type,
            YAML_STREAM_START_EVENT
         );

    loader.anchors = newHV();
    sv_2mortal((SV *)loader.anchors);

    /* Keep calling load_node until end of stream */
    while (1) {
        loader.document++;
        /* We are through with the previous event - delete it! */
        yaml_event_delete(&loader.event);
        if (!yaml_parser_parse(&loader.parser, &loader.event))
            goto load_error;
        if (loader.event.type == YAML_STREAM_END_EVENT)
            break;
        node = load_node(&loader);
        /* We are through with the previous event - delete it! */
        yaml_event_delete(&loader.event);
        hv_clear(loader.anchors);
        if (! node) break;
        XPUSHs(sv_2mortal(node));
        if (!yaml_parser_parse(&loader.parser, &loader.event))
            goto load_error;
        if (loader.event.type != YAML_DOCUMENT_END_EVENT)
            croak("%sExpected DOCUMENT_END_EVENT", ERRMSG);
    }

    /* Make sure the last event is a STREAM_END */
    if (loader.event.type != YAML_STREAM_END_EVENT)
        croak("%sExpected STREAM_END_EVENT; Got: %d != %d",
            ERRMSG,
            loader.event.type,
            YAML_STREAM_END_EVENT
         );
    yaml_parser_delete(&loader.parser);
    PUTBACK;
    return;

load_error:
    croak("%s", loader_error_msg(&loader, NULL));
}
예제 #10
0
int check_utf8_sequences (void) {
  yaml_parser_t parser;
  int failed = 0;
  int k;
  printf ("checking utf-8 sequences...\n");

  for (k = 0; utf8_sequences[k].test; k++) {
    char* title = utf8_sequences[k].title;
    int check = utf8_sequences[k].result;
    int result;
    char* start = utf8_sequences[k].test;
    char* end = start;
    printf ("\t%s:\n", title);

    while (1) {
      while (*end != '|' && *end != '!') {
        end++;
        }

      yaml_parser_initialize (&parser);
      yaml_parser_set_input_string (&parser, (unsigned char*) start, end - start);
      result = yaml_parser_update_buffer (&parser, end - start);

      if (result != check) {
        printf ("\t\t- ");
        failed ++;
        }

      else {
        printf ("\t\t+ ");
        }

      if (!parser.error) {
        printf ("(no error)\n");
        }

      else if (parser.error == YAML_READER_ERROR) {
        if (parser.problem_value != -1) {
          printf ("(reader error: %s: #%X at %d)\n",
                  parser.problem, parser.problem_value, parser.problem_offset);
          }

        else {
          printf ("(reader error: %s at %d)\n",
                  parser.problem, parser.problem_offset);
          }
        }

      if (*end == '!') {
        break;
        }

      start = ++end;
      yaml_parser_delete (&parser);
      };

    printf ("\n");
    }

  printf ("checking utf-8 sequences: %d fail(s)\n", failed);
  return failed;
  }
예제 #11
0
int main (int argc, char *argv[])
{
    int help = 0;
    int canonical = 0;
    int unicode = 0;
    int k;
    int done = 0;

    yaml_parser_t parser;
    yaml_emitter_t emitter;
    yaml_document_t document;

    /* Clear the objects. */

    memset (&parser, 0, sizeof (parser));
    memset (&emitter, 0, sizeof (emitter));
    memset (&document, 0, sizeof (document));

    /* Analyze command line options. */

    for (k = 1; k < argc; k++)
	{
	    if (strcmp (argv[k], "-h") == 0 || strcmp (argv[k], "--help") == 0)
		{
		    help = 1;
		}

	    else if (strcmp (argv[k], "-c") == 0 || strcmp (argv[k], "--canonical") == 0)
		{
		    canonical = 1;
		}

	    else if (strcmp (argv[k], "-u") == 0 || strcmp (argv[k], "--unicode") == 0)
		{
		    unicode = 1;
		}

	    else
		{
		    fprintf (stderr, "Unrecognized option: %s\n" "Try `%s --help` for more information.\n", argv[k], argv[0]);
		    return 1;
		}
	}

    /* Display the help string. */

    if (help)
	{
	    printf ("%s [--canonical] [--unicode] <input >output\n"
		    "or\n%s -h | --help\nReformat a YAML stream\n\nOptions:\n"
		    "-h, --help\t\tdisplay this help and exit\n"
		    "-c, --canonical\t\toutput in the canonical YAML format\n" "-u, --unicode\t\toutput unescaped non-ASCII characters\n", argv[0], argv[0]);
	    return 0;
	}

    /* Initialize the parser and emitter objects. */

    if (!yaml_parser_initialize (&parser))
	goto parser_error;

    if (!yaml_emitter_initialize (&emitter))
	goto emitter_error;

    /* Set the parser parameters. */

    yaml_parser_set_input_file (&parser, stdin);

    /* Set the emitter parameters. */

    yaml_emitter_set_output_file (&emitter, stdout);

    yaml_emitter_set_canonical (&emitter, canonical);
    yaml_emitter_set_unicode (&emitter, unicode);

    /* The main loop. */

    while (!done)
	{
	    /* Get the next event. */

	    if (!yaml_parser_load (&parser, &document))
		goto parser_error;

	    /* Check if this is the stream end. */

	    if (!yaml_document_get_root_node (&document))
		{
		    done = 1;
		}

	    /* Emit the event. */

	    if (!yaml_emitter_dump (&emitter, &document))
		goto emitter_error;
	}

    yaml_parser_delete (&parser);
    yaml_emitter_delete (&emitter);

    return 0;

  parser_error:

    /* Display a parser error message. */

    switch (parser.error)
	{
	    case YAML_MEMORY_ERROR:
		fprintf (stderr, "Memory error: Not enough memory for parsing\n");
		break;

	    case YAML_READER_ERROR:
		if (parser.problem_value != -1)
		    {
			fprintf (stderr, "Reader error: %s: #%X at %d\n", parser.problem, parser.problem_value, parser.problem_offset);
		    }
		else
		    {
			fprintf (stderr, "Reader error: %s at %d\n", parser.problem, parser.problem_offset);
		    }
		break;

	    case YAML_SCANNER_ERROR:
		if (parser.context)
		    {
			fprintf (stderr, "Scanner error: %s at line %d, column %d\n"
				 "%s at line %d, column %d\n", parser.context,
				 parser.context_mark.line + 1, parser.context_mark.column + 1, parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		else
		    {
			fprintf (stderr, "Scanner error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		break;

	    case YAML_PARSER_ERROR:
		if (parser.context)
		    {
			fprintf (stderr, "Parser error: %s at line %d, column %d\n"
				 "%s at line %d, column %d\n", parser.context,
				 parser.context_mark.line + 1, parser.context_mark.column + 1, parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		else
		    {
			fprintf (stderr, "Parser error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		break;

	    case YAML_COMPOSER_ERROR:
		if (parser.context)
		    {
			fprintf (stderr, "Composer error: %s at line %d, column %d\n"
				 "%s at line %d, column %d\n", parser.context,
				 parser.context_mark.line + 1, parser.context_mark.column + 1, parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		else
		    {
			fprintf (stderr, "Composer error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line + 1, parser.problem_mark.column + 1);
		    }
		break;

	    default:
		/* Couldn't happen. */
		fprintf (stderr, "Internal error\n");
		break;
	}

    yaml_parser_delete (&parser);
    yaml_emitter_delete (&emitter);

    return 1;

  emitter_error:

    /* Display an emitter error message. */

    switch (emitter.error)
	{
	    case YAML_MEMORY_ERROR:
		fprintf (stderr, "Memory error: Not enough memory for emitting\n");
		break;

	    case YAML_WRITER_ERROR:
		fprintf (stderr, "Writer error: %s\n", emitter.problem);
		break;

	    case YAML_EMITTER_ERROR:
		fprintf (stderr, "Emitter error: %s\n", emitter.problem);
		break;

	    default:
		/* Couldn't happen. */
		fprintf (stderr, "Internal error\n");
		break;
	}

    yaml_parser_delete (&parser);
    yaml_emitter_delete (&emitter);

    return 1;
}
예제 #12
0
  void ProjectFrame::OnOpen(wxCommandEvent& event)
  {
    wxFileDialog
      openFileDialog(this, _("Open file"), "", "",
        "Dart files (*.dart)|*.dart|Flutter Projects (*.yaml)|*.yaml|All Files (*.*)|*.*", wxFD_OPEN | wxFD_FILE_MUST_EXIST);
    if (openFileDialog.ShowModal() == wxID_CANCEL)
      return;


    wxString        path = openFileDialog.GetPath();
    if (path.EndsWith(".yaml"))
    {
      // -- Load a new project
      yaml_parser_t parser;
      yaml_event_t evt;
      int done = 0;
      FILE *input;

      yaml_parser_initialize(&parser);

      if ((input = fopen(path, "rb")))
      {
        yaml_parser_set_input_file(&parser, input);

        while (!done) {
          // Get the next event.
          if (!yaml_parser_parse(&parser, &evt)) {
            wxLogError("Syntax error parsing YAML file '%s'.", path);
            break;
          }

          switch (evt.type)
          {
          case YAML_MAPPING_START_EVENT:
            wxLogMessage("<mapping>");
            break;
          case YAML_MAPPING_END_EVENT:
            wxLogMessage("</mapping>");
            break;
          case YAML_SEQUENCE_START_EVENT:
            wxLogMessage("<seq>");
            break;
          case YAML_SEQUENCE_END_EVENT:
            wxLogMessage("</seq>");
            break;
          case YAML_SCALAR_EVENT:
            wxLogMessage("%d %d %s %s %s", 
              evt.data.scalar.plain_implicit,
              evt.data.scalar.style,
              (const char*)evt.data.scalar.anchor,
              (const char*)evt.data.scalar.tag,
              (const char*)evt.data.scalar.value);
            break;
          default:
            break;
          }

          // Are we finished?
          done = (evt.type == YAML_STREAM_END_EVENT);

          // The application is responsible for destroying the event object.
          yaml_event_delete(&evt);

        }


        fclose(input);
      }

      yaml_parser_delete(&parser);

    }
    else 
    {
      // -- Load a file into the editor
      wxString        complete_file_contents;
      wxString        str;
      wxTextFile      tfile;
      if (!tfile.Open(path)) {
        wxLogError("Cannot open file '%s'.", path);
        return;
      }

      // read the first line
      str = tfile.GetFirstLine();
      complete_file_contents += str;
      while (!tfile.Eof())
      {
        str = tfile.GetNextLine();
        complete_file_contents += "\n";
        complete_file_contents += str;
      }

      _main_edit_box->SetValue(complete_file_contents);
    }
  }
예제 #13
0
int cli_config_read_cli_config(char* path, size_t size, struct cli_config* buf) {
   struct stat   path_stat;
   FILE*         fin;
   /* libyaml requirements */
   yaml_parser_t parser;
   yaml_event_t  event;
   /* parse depth / path tracking */
   int           depth[40] = { 0 };
   int           depth_index = 0;
   int           depth_of_interest[] = { YAML_STREAM_START_EVENT,
                                         YAML_DOCUMENT_START_EVENT,
                                         YAML_MAPPING_START_EVENT, 0 };
   /* key / value capture */
   char          key[1024] = { 0 };
   /* to compare the current stack (depth) with the (depth_of_interest) */
   int           compare_index;
   int           differ;

   if (buf == 0) {
       return -1;
   }
   memset(buf->ea_php_config, 0, CLI_CONFIG_EA_PHP_CONFIG_SIZE);
   memset(buf->testing_root_dir, 0, CLI_CONFIG_TESTING_ROOT_DIR_SIZE);
   memset(buf->php_bin_pattern, 0, CLI_CONFIG_PHP_BIN_PATTERN_SIZE);
   if (path == 0 || path[0] == 0) {
      return 0;
   }
   if (stat(path, &path_stat) != 0 || S_ISREG(path_stat.st_mode) == 0) {
     return -1;
   } 
   fin = fopen(path, "r");
   if (fin) {
     yaml_parser_initialize(&parser);
     yaml_parser_set_input_file(&parser, fin);

     while (yaml_parser_parse(&parser, &event) &&
            event.type != YAML_STREAM_END_EVENT) {
       switch (event.type) {
         case YAML_STREAM_START_EVENT: case YAML_DOCUMENT_START_EVENT:
         case YAML_MAPPING_START_EVENT: case YAML_SEQUENCE_START_EVENT:
           /* push position to stack, clear key and value buffers */
           depth[depth_index++] = event.type;
           key[0] = 0;
           break;
         case YAML_STREAM_END_EVENT: case YAML_DOCUMENT_END_EVENT:
         case YAML_MAPPING_END_EVENT: case YAML_SEQUENCE_END_EVENT:
           /* clear position from stack, clear key and value buffers */
           depth[--depth_index] = 0;
           key[0] = 0;
           break;
         case YAML_ALIAS_EVENT:
           /* In case someone tries to define a key to an alias, clear both */
           key[0] = 0;
           break;
         case YAML_SCALAR_EVENT:
           /* compare parse position.  Future improvement, put in funciton */
           compare_index = -1;
           differ = 0;
           do {
             compare_index++;
             differ = depth[compare_index] - depth_of_interest[compare_index];
           } while (differ == 0 && depth_of_interest[compare_index] != 0);
           /* If exact depth match and blank key, set the key */
           if (differ == 0 && key[0] == 0) {
             strncpy(key, (const char*)event.data.scalar.value, 1024);
             break;
           }
           /* If exact depth match and blank value, set the value */
           if (strncmp(key, "ea_php_yaml", 40) == 0) {
             strncpy(buf->ea_php_config, (const char*)event.data.scalar.value, CLI_CONFIG_EA_PHP_CONFIG_SIZE);
           } else if (strncmp(key, "testing_root_dir", 40) == 0) {
             strncpy(buf->testing_root_dir, (const char*)event.data.scalar.value, CLI_CONFIG_TESTING_ROOT_DIR_SIZE);
           } else if (strncmp(key, "php_bin_pattern", 40) == 0) {
             strncpy(buf->php_bin_pattern, (const char*)event.data.scalar.value, CLI_CONFIG_PHP_BIN_PATTERN_SIZE);
           } else if (strncmp(key, "lsphp_bin_pattern", 40) == 0) {
             strncpy(buf->lsphp_bin_pattern, (const char*)event.data.scalar.value, CLI_CONFIG_LSPHP_BIN_PATTERN_SIZE);
           };
           break;
         case YAML_NO_EVENT:
           /* to suppress compiler warning on unhandled enumeration value */
           break;
       }
       yaml_event_delete(&event);
     }
     yaml_parser_delete(&parser);
     fclose(fin);
   }
   return 0;
}
예제 #14
0
int
main(int argc, char *argv[])
{
    int help = 0;
    int canonical = 0;
    int unicode = 0;
    int k;
    int done = 0;

    yaml_parser_t parser;
    yaml_emitter_t emitter;
    yaml_event_t input_event;
    yaml_document_t output_document;

    int root;

    /* Clear the objects. */

    memset(&parser, 0, sizeof(parser));
    memset(&emitter, 0, sizeof(emitter));
    memset(&input_event, 0, sizeof(input_event));
    memset(&output_document, 0, sizeof(output_document));

    /* Analyze command line options. */

    for (k = 1; k < argc; k ++)
    {
        if (strcmp(argv[k], "-h") == 0
                || strcmp(argv[k], "--help") == 0) {
            help = 1;
        }

        else if (strcmp(argv[k], "-c") == 0
                || strcmp(argv[k], "--canonical") == 0) {
            canonical = 1;
        }

        else if (strcmp(argv[k], "-u") == 0
                || strcmp(argv[k], "--unicode") == 0) {
            unicode = 1;
        }

        else {
            fprintf(stderr, "Unrecognized option: %s\n"
                    "Try `%s --help` for more information.\n",
                    argv[k], argv[0]);
            return 1;
        }
    }

    /* Display the help string. */

    if (help)
    {
        printf("%s <input\n"
                "or\n%s -h | --help\nDeconstruct a YAML stream\n\nOptions:\n"
                "-h, --help\t\tdisplay this help and exit\n"
                "-c, --canonical\t\toutput in the canonical YAML format\n"
                "-u, --unicode\t\toutput unescaped non-ASCII characters\n",
                argv[0], argv[0]);
        return 0;
    }

    /* Initialize the parser and emitter objects. */

    if (!yaml_parser_initialize(&parser)) {
        fprintf(stderr, "Could not initialize the parser object\n");
        return 1;
    }

    if (!yaml_emitter_initialize(&emitter)) {
        yaml_parser_delete(&parser);
        fprintf(stderr, "Could not inialize the emitter object\n");
        return 1;
    }

    /* Set the parser parameters. */

    yaml_parser_set_input_file(&parser, stdin);

    /* Set the emitter parameters. */

    yaml_emitter_set_output_file(&emitter, stdout);

    yaml_emitter_set_canonical(&emitter, canonical);
    yaml_emitter_set_unicode(&emitter, unicode);

    /* Create and emit the STREAM-START event. */

    if (!yaml_emitter_open(&emitter))
        goto emitter_error;

    /* Create a output_document object. */

    if (!yaml_document_initialize(&output_document, NULL, NULL, NULL, 0, 0))
        goto document_error;

    /* Create the root sequence. */

    root = yaml_document_add_sequence(&output_document, NULL,
            YAML_BLOCK_SEQUENCE_STYLE);
    if (!root) goto document_error;

    /* Loop through the input events. */

    while (!done)
    {
        int properties, key, value, map, seq;

        /* Get the next event. */

        if (!yaml_parser_parse(&parser, &input_event))
            goto parser_error;

        /* Check if this is the stream end. */

        if (input_event.type == YAML_STREAM_END_EVENT) {
            done = 1;
        }

        /* Create a mapping node and attach it to the root sequence. */

        properties = yaml_document_add_mapping(&output_document, NULL,
                YAML_BLOCK_MAPPING_STYLE);
        if (!properties) goto document_error;
        if (!yaml_document_append_sequence_item(&output_document,
                    root, properties)) goto document_error;

        /* Analyze the event. */

        switch (input_event.type)
        {
            case YAML_STREAM_START_EVENT:

                /* Add 'type': 'STREAM-START'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "STREAM-START", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'encoding': <encoding>. */

                if (input_event.data.stream_start.encoding)
                {
                    yaml_encoding_t encoding
                        = input_event.data.stream_start.encoding;

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "encoding", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            (encoding == YAML_UTF8_ENCODING ? "utf-8" :
                             encoding == YAML_UTF16LE_ENCODING ? "utf-16-le" :
                             encoding == YAML_UTF16BE_ENCODING ? "utf-16-be" :
                             "unknown"), -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }
                    
                break;

            case YAML_STREAM_END_EVENT:

                /* Add 'type': 'STREAM-END'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "STREAM-END", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            case YAML_DOCUMENT_START_EVENT:

                /* Add 'type': 'DOCUMENT-START'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "DOCUMENT-START", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Display the output_document version numbers. */

                if (input_event.data.document_start.version_directive)
                {
                    yaml_version_directive_t *version
                        = input_event.data.document_start.version_directive;
                    char number[64];

                    /* Add 'version': {}. */
                    
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "version", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    map = yaml_document_add_mapping(&output_document, NULL,
                            YAML_FLOW_MAPPING_STYLE);
                    if (!map) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, map)) goto document_error;

                    /* Add 'major': <number>. */

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "major", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    sprintf(number, "%d", version->major);
                    value = yaml_document_add_scalar(&output_document, YAML_INT_TAG,
                        number, -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                map, key, value)) goto document_error;

                    /* Add 'minor': <number>. */

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "minor", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    sprintf(number, "%d", version->minor);
                    value = yaml_document_add_scalar(&output_document, YAML_INT_TAG,
                        number, -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                map, key, value)) goto document_error;
                }

                /* Display the output_document tag directives. */

                if (input_event.data.document_start.tag_directives.start
                        != input_event.data.document_start.tag_directives.end)
                {
                    yaml_tag_directive_t *tag;

                    /* Add 'tags': []. */
                    
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "tags", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    seq = yaml_document_add_sequence(&output_document, NULL,
                            YAML_BLOCK_SEQUENCE_STYLE);
                    if (!seq) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, seq)) goto document_error;

                    for (tag = input_event.data.document_start.tag_directives.start;
                            tag != input_event.data.document_start.tag_directives.end;
                            tag ++)
                    {
                        /* Add {}. */

                        map = yaml_document_add_mapping(&output_document, NULL,
                                YAML_FLOW_MAPPING_STYLE);
                        if (!map) goto document_error;
                        if (!yaml_document_append_sequence_item(&output_document,
                                    seq, map)) goto document_error;

                        /* Add 'handle': <handle>. */

                        key = yaml_document_add_scalar(&output_document, NULL,
                            "handle", -1, YAML_PLAIN_SCALAR_STYLE);
                        if (!key) goto document_error;
                        value = yaml_document_add_scalar(&output_document, NULL,
                            tag->handle, -1, YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                        if (!value) goto document_error;
                        if (!yaml_document_append_mapping_pair(&output_document,
                                    map, key, value)) goto document_error;

                        /* Add 'prefix': <prefix>. */

                        key = yaml_document_add_scalar(&output_document, NULL,
                            "prefix", -1, YAML_PLAIN_SCALAR_STYLE);
                        if (!key) goto document_error;
                        value = yaml_document_add_scalar(&output_document, NULL,
                            tag->prefix, -1, YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                        if (!value) goto document_error;
                        if (!yaml_document_append_mapping_pair(&output_document,
                                    map, key, value)) goto document_error;
                    }
                }

                /* Add 'implicit': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "implicit", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.document_start.implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            case YAML_DOCUMENT_END_EVENT:

                /* Add 'type': 'DOCUMENT-END'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "DOCUMENT-END", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'implicit': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "implicit", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.document_end.implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            case YAML_ALIAS_EVENT:

                /* Add 'type': 'ALIAS'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "ALIAS", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'anchor': <anchor>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "anchor", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                        input_event.data.alias.anchor, -1,
                        YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            case YAML_SCALAR_EVENT:

                /* Add 'type': 'SCALAR'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "SCALAR", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'anchor': <anchor>. */

                if (input_event.data.scalar.anchor)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "anchor", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.scalar.anchor, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'tag': <tag>. */

                if (input_event.data.scalar.tag)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "tag", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.scalar.tag, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'value': <value>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "value", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                        input_event.data.scalar.value,
                        input_event.data.scalar.length,
                        YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Display if the scalar tag is implicit. */

                /* Add 'implicit': {} */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "version", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                map = yaml_document_add_mapping(&output_document, NULL,
                        YAML_FLOW_MAPPING_STYLE);
                if (!map) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, map)) goto document_error;

                /* Add 'plain': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "plain", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.scalar.plain_implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            map, key, value)) goto document_error;

                /* Add 'quoted': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "quoted", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.scalar.quoted_implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            map, key, value)) goto document_error;

                /* Display the style information. */

                if (input_event.data.scalar.style)
                {
                    yaml_scalar_style_t style = input_event.data.scalar.style;

                    /* Add 'style': <style>. */

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "style", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            (style == YAML_PLAIN_SCALAR_STYLE ? "plain" :
                             style == YAML_SINGLE_QUOTED_SCALAR_STYLE ?
                                    "single-quoted" :
                             style == YAML_DOUBLE_QUOTED_SCALAR_STYLE ?
                                    "double-quoted" :
                             style == YAML_LITERAL_SCALAR_STYLE ? "literal" :
                             style == YAML_FOLDED_SCALAR_STYLE ? "folded" :
                             "unknown"), -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                break;

            case YAML_SEQUENCE_START_EVENT:

                /* Add 'type': 'SEQUENCE-START'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "SEQUENCE-START", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'anchor': <anchor>. */

                if (input_event.data.sequence_start.anchor)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "anchor", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.sequence_start.anchor, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'tag': <tag>. */

                if (input_event.data.sequence_start.tag)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "tag", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.sequence_start.tag, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'implicit': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "implicit", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.sequence_start.implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Display the style information. */

                if (input_event.data.sequence_start.style)
                {
                    yaml_sequence_style_t style
                        = input_event.data.sequence_start.style;

                    /* Add 'style': <style>. */

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "style", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            (style == YAML_BLOCK_SEQUENCE_STYLE ? "block" :
                             style == YAML_FLOW_SEQUENCE_STYLE ? "flow" :
                             "unknown"), -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                break;

            case YAML_SEQUENCE_END_EVENT:

                /* Add 'type': 'SEQUENCE-END'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "SEQUENCE-END", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            case YAML_MAPPING_START_EVENT:

                /* Add 'type': 'MAPPING-START'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "MAPPING-START", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Add 'anchor': <anchor>. */

                if (input_event.data.mapping_start.anchor)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "anchor", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.mapping_start.anchor, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'tag': <tag>. */

                if (input_event.data.mapping_start.tag)
                {
                    key = yaml_document_add_scalar(&output_document, NULL,
                        "tag", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            input_event.data.mapping_start.tag, -1,
                            YAML_DOUBLE_QUOTED_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                /* Add 'implicit': <flag>. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "implicit", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, YAML_BOOL_TAG,
                        (input_event.data.mapping_start.implicit ?
                         "true" : "false"), -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                /* Display the style information. */

                if (input_event.data.sequence_start.style)
                {
                    yaml_sequence_style_t style
                        = input_event.data.mapping_start.style;

                    /* Add 'style': <style>. */

                    key = yaml_document_add_scalar(&output_document, NULL,
                        "style", -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!key) goto document_error;
                    value = yaml_document_add_scalar(&output_document, NULL,
                            (style == YAML_BLOCK_MAPPING_STYLE ? "block" :
                             style == YAML_FLOW_MAPPING_STYLE ? "flow" :
                             "unknown"), -1, YAML_PLAIN_SCALAR_STYLE);
                    if (!value) goto document_error;
                    if (!yaml_document_append_mapping_pair(&output_document,
                                properties, key, value)) goto document_error;
                }

                break;

            case YAML_MAPPING_END_EVENT:

                /* Add 'type': 'MAPPING-END'. */

                key = yaml_document_add_scalar(&output_document, NULL,
                    "type", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!key) goto document_error;
                value = yaml_document_add_scalar(&output_document, NULL,
                    "MAPPING-END", -1, YAML_PLAIN_SCALAR_STYLE);
                if (!value) goto document_error;
                if (!yaml_document_append_mapping_pair(&output_document,
                            properties, key, value)) goto document_error;

                break;

            default:
                /* It couldn't really happen. */
                break;
        }

        /* Delete the event object. */

        yaml_event_delete(&input_event);
    }

    if (!yaml_emitter_dump(&emitter, &output_document))
        goto emitter_error;
    if (!yaml_emitter_close(&emitter))
        goto emitter_error;

    yaml_parser_delete(&parser);
    yaml_emitter_delete(&emitter);

    return 0;

parser_error:

    /* Display a parser error message. */

    switch (parser.error)
    {
        case YAML_MEMORY_ERROR:
            fprintf(stderr, "Memory error: Not enough memory for parsing\n");
            break;

        case YAML_READER_ERROR:
            if (parser.problem_value != -1) {
                fprintf(stderr, "Reader error: %s: #%X at %d\n", parser.problem,
                        parser.problem_value, parser.problem_offset);
            }
            else {
                fprintf(stderr, "Reader error: %s at %d\n", parser.problem,
                        parser.problem_offset);
            }
            break;

        case YAML_SCANNER_ERROR:
            if (parser.context) {
                fprintf(stderr, "Scanner error: %s at line %d, column %d\n"
                        "%s at line %d, column %d\n", parser.context,
                        parser.context_mark.line+1, parser.context_mark.column+1,
                        parser.problem, parser.problem_mark.line+1,
                        parser.problem_mark.column+1);
            }
            else {
                fprintf(stderr, "Scanner error: %s at line %d, column %d\n",
                        parser.problem, parser.problem_mark.line+1,
                        parser.problem_mark.column+1);
            }
            break;

        case YAML_PARSER_ERROR:
            if (parser.context) {
                fprintf(stderr, "Parser error: %s at line %d, column %d\n"
                        "%s at line %d, column %d\n", parser.context,
                        parser.context_mark.line+1, parser.context_mark.column+1,
                        parser.problem, parser.problem_mark.line+1,
                        parser.problem_mark.column+1);
            }
            else {
                fprintf(stderr, "Parser error: %s at line %d, column %d\n",
                        parser.problem, parser.problem_mark.line+1,
                        parser.problem_mark.column+1);
            }
            break;

        default:
            /* Couldn't happen. */
            fprintf(stderr, "Internal error\n");
            break;
    }

    yaml_event_delete(&input_event);
    yaml_document_delete(&output_document);
    yaml_parser_delete(&parser);
    yaml_emitter_delete(&emitter);

    return 1;

emitter_error:

    /* Display an emitter error message. */

    switch (emitter.error)
    {
        case YAML_MEMORY_ERROR:
            fprintf(stderr, "Memory error: Not enough memory for emitting\n");
            break;

        case YAML_WRITER_ERROR:
            fprintf(stderr, "Writer error: %s\n", emitter.problem);
            break;

        case YAML_EMITTER_ERROR:
            fprintf(stderr, "Emitter error: %s\n", emitter.problem);
            break;

        default:
            /* Couldn't happen. */
            fprintf(stderr, "Internal error\n");
            break;
    }

    yaml_event_delete(&input_event);
    yaml_document_delete(&output_document);
    yaml_parser_delete(&parser);
    yaml_emitter_delete(&emitter);

    return 1;

document_error:

    fprintf(stderr, "Memory error: Not enough memory for creating a document\n");

    yaml_event_delete(&input_event);
    yaml_document_delete(&output_document);
    yaml_parser_delete(&parser);
    yaml_emitter_delete(&emitter);

    return 1;
}
예제 #15
0
int
main(int argc, char *argv[])
{
    int number;
    int canonical = 0;
    int unicode = 0;

    number = 1;
    while (number < argc) {
        if (strcmp(argv[number], "-c") == 0) {
            canonical = 1;
        }
        else if (strcmp(argv[number], "-u") == 0) {
            unicode = 1;
        }
        else if (argv[number][0] == '-') {
            printf("Unknown option: '%s'\n", argv[number]);
            return 0;
        }
        if (argv[number][0] == '-') {
            if (number < argc-1) {
                memmove(argv+number, argv+number+1, (argc-number-1)*sizeof(char *));
            }
            argc --;
        }
        else {
            number ++;
        }
    }

    if (argc < 2) {
        printf("Usage: %s [-c] [-u] file1.yaml ...\n", argv[0]);
        return 0;
    }

    for (number = 1; number < argc; number ++)
    {
        FILE *file;
        yaml_parser_t parser;
        yaml_emitter_t emitter;
        yaml_event_t event;
        unsigned char buffer[BUFFER_SIZE+1];
        size_t written = 0;
        yaml_event_t events[MAX_EVENTS];
        size_t event_number = 0;
        int done = 0;
        int count = 0;
        int error = 0;
        int k;
        memset(buffer, 0, BUFFER_SIZE+1);
        memset(events, 0, MAX_EVENTS*sizeof(yaml_event_t));

        printf("[%d] Parsing, emitting, and parsing again '%s': ", number, argv[number]);
        fflush(stdout);

        file = fopen(argv[number], "rb");
        assert(file);

        assert(yaml_parser_initialize(&parser));
        yaml_parser_set_input_file(&parser, file);
        assert(yaml_emitter_initialize(&emitter));
        if (canonical) {
            yaml_emitter_set_canonical(&emitter, 1);
        }
        if (unicode) {
            yaml_emitter_set_unicode(&emitter, 1);
        }
        yaml_emitter_set_output_string(&emitter, buffer, BUFFER_SIZE, &written);

        while (!done)
        {
            if (!yaml_parser_parse(&parser, &event)) {
                error = 1;
                break;
            }

            done = (event.type == YAML_STREAM_END_EVENT);
            assert(event_number < MAX_EVENTS);
            assert(copy_event(&(events[event_number++]), &event));
            assert(yaml_emitter_emit(&emitter, &event) || 
                    print_output(argv[number], buffer, written, count));
            count ++;
        }

        yaml_parser_delete(&parser);
        assert(!fclose(file));
        yaml_emitter_delete(&emitter);

        if (!error)
        {
            count = done = 0;
            assert(yaml_parser_initialize(&parser));
            yaml_parser_set_input_string(&parser, buffer, written);

            while (!done)
            {
                assert(yaml_parser_parse(&parser, &event) || print_output(argv[number], buffer, written, count));
                done = (event.type == YAML_STREAM_END_EVENT);
                assert(compare_events(events+count, &event) || print_output(argv[number], buffer, written, count));
                yaml_event_delete(&event);
                count ++;
            }
            yaml_parser_delete(&parser);
        }

        for (k = 0; k < event_number; k ++) {
            yaml_event_delete(events+k);
        }

        printf("PASSED (length: %zd)\n", written);
        print_output(argv[number], buffer, written, -1);
    }

    return 0;
}
예제 #16
0
/*
 * Name: KeInitializeEx
 * Desc: Same as above, but initializes more engine components as specified in the settings
 *		 script.  The first param is the path to the YAML based file where the engine settings
 *       are stored.  Any components listed will be initialized in this function.
 */
bool KeInitializeEx( std::string settings_file, IKeRenderDevice** rd, IKeAudioDevice** ad )
{
	/* Set the current directory to our resource directory */
    KeSetCurrentPathToResourceDirectory();
    
    /* Initial debug logging */
    dbg = new NVDebug( KE_DBG_LEVEL, "debug.txt" );
    DISPDBG( KE_DBGLVL(0), "Initialization started\n" );
    
    /* Initialize SDL and the necessary sub-systems. For now, we only want to initialize 
       timing and events. */
    if( SDL_Init( SDL_INIT_EVENTS | SDL_INIT_TIMER ) != 0 )
	{
		DISPDBG( KE_ERROR, "Error initializing SDL timer and events!" );
	}
	else
	{
		DISPDBG( KE_DBGLVL(3), "SDL_Init(SDL_INIT_EVENTS | SDL_INIT_TIMER) = OK\n" );
	}
    
    /* Gather display modes */
    extern int KeGatherAllDisplayInformation();
    KeGatherAllDisplayInformation();
    
    /* Insert event handler for mobile/embedded platforms */
#ifdef __MOBILE_OS__
    extern int KeProcessAppEvents( void *userdata, SDL_Event *event );
    SDL_SetEventFilter( KeProcessAppEvents, KeGetContextPointer() );
#endif
   
    /* Reset keys */
    KeResetKeys();

	/* Open settings file */
	FILE* fp = fopen( settings_file.c_str(), "r" );
	if( !fp )
	{
		DISPDBG( KE_ERROR, "Error opening settings file!\nFile: " << settings_file << std::endl );
		return false;
	}

	/* Initialize YAML parser */
	yaml_parser_t yaml_parser;
	if( !yaml_parser_initialize( &yaml_parser ) )
	{
		fclose(fp);
		DISPDBG( KE_ERROR, "Error intiializing YAML parser!" );
		return false;
	}

	/* Read settings file */
	yaml_parser_set_input_file( &yaml_parser, fp );

	bool init_renderer = No, init_audio = No, init_leap_motion = No, init_kinect = No;
	KeRenderDeviceDesc rddesc;
	KeAudioDeviceDesc  addesc;

	ZeroMemory( &rddesc, sizeof( KeRenderDeviceDesc ) );
	ZeroMemory( &addesc, sizeof( KeAudioDeviceDesc ) );

	/* Parse the data */
	yaml_token_t token;

	do
	{
		static std::string keyval = " ", valueval = " ";
		static int key = No, value = No;

		yaml_parser_scan( &yaml_parser, &token );

		switch (token.type)
		{
		/* Stream start/end */
		case YAML_STREAM_START_TOKEN:	break;
		case YAML_STREAM_END_TOKEN:		break;

		/* Token types (read before actual token) */
        case YAML_KEY_TOKEN:   key = Yes; break;
        case YAML_VALUE_TOKEN: value = Yes; break;

		/* Block delimeters */
		case YAML_BLOCK_SEQUENCE_START_TOKEN: break;
		case YAML_BLOCK_ENTRY_TOKEN:          break;
		case YAML_BLOCK_END_TOKEN:            break;

		/* Data */
		case YAML_BLOCK_MAPPING_START_TOKEN:  
			if( value )
			{
				if( keyval == "RenderDevice" )
					init_renderer = Yes;
				if( keyval == "AudioDevice" )
					init_audio = Yes;
				if( keyval == "LeapMotionDevice" )
					init_leap_motion = Yes;
				if( keyval == "KinectDevice" )
					init_kinect = Yes;

				value = No;
			}
			break;
		case YAML_SCALAR_TOKEN:
                fprintf(stderr, "scalar %s \n", token.data.scalar.value);
                
                /* Key token value */
                if( key )
                {
                    keyval = (const char*) token.data.scalar.value;
                }
                
                /* Value token value */
                if( value )
                {
                    valueval = (const char*) token.data.scalar.value;
                    
					/* RenderDevice settings */
					if( keyval == "WindowWidth" )
						rddesc.width = atoi( valueval.c_str() );
					else if( keyval == "WindowHeight" )
						rddesc.height = atoi( valueval.c_str() );
					else if( keyval == "ColourBpp" )
						rddesc.colour_bpp = atoi( valueval.c_str() );
					else if( keyval == "DepthBpp" )
						rddesc.depth_bpp = atoi( valueval.c_str() );
					else if( keyval == "StencilBpp" )
						rddesc.stencil_bpp = atoi( valueval.c_str() );
					else if( keyval == "BufferCount" )
						rddesc.buffer_count = atoi( valueval.c_str() );
					else if( keyval == "RefreshRate" )
						rddesc.refresh_rate = atoi( valueval.c_str() );
					else if( keyval == "DeviceType" )
					{
						if( valueval == "OpenGL3" )		rddesc.device_type = KE_RENDERDEVICE_OGL3;
						if( valueval == "OpenGL4" )		rddesc.device_type = KE_RENDERDEVICE_OGL4;
						if( valueval == "Direct3D11" )	rddesc.device_type = KE_RENDERDEVICE_D3D11;
                        if( valueval == "Direct3D12" )	rddesc.device_type = KE_RENDERDEVICE_D3D12;
						if( valueval == "OpenGLES2" )	rddesc.device_type = KE_RENDERDEVICE_OGLES2;
						if( valueval == "OpenGLES3" )	rddesc.device_type = KE_RENDERDEVICE_OGLES3;
						if( valueval == "Metal" )		rddesc.device_type = KE_RENDERDEVICE_METAL;
                        if( valueval == "Vulkan" )      rddesc.device_type = KE_RENDERDEVICE_VULKAN;
					}
					else if( keyval == "Fullscreen" )
						rddesc.fullscreen = valueval == "Yes" ? Yes : No;

					/* AudioDevice settings */

						
                    /* Reset key and values */
                    keyval = " ", valueval = " ";
                }
                
                key = No, value = No;
                break;

		/* Others */
		default:
			fprintf( stderr, "Got token of type %d\n", token.type );
		}
		if( token.type != YAML_STREAM_END_TOKEN )
			yaml_token_delete( &token );
	} while( token.type != YAML_STREAM_END_TOKEN );
	yaml_token_delete( &token );

	/* Close YAML parser */
	yaml_parser_delete( &yaml_parser );
	fclose(fp);
 
	/* Create window and rendering device */
	if( init_renderer && rd != NULL )
	{
		if( !KeCreateWindowAndDevice( &rddesc, rd ) )
			return false;
	}

    /* Call user specified initialization routine */
    KeOnInitialize( KeGetContextPointer() );
    
	return true;
}
예제 #17
0
파일: config_file.c 프로젝트: hdanak/velox
void load_config()
{
    FILE * file;

    yaml_parser_t parser;
    yaml_document_t document;

    yaml_node_t * root;

    yaml_node_t * map;
    yaml_node_pair_t * pair;

    yaml_node_t * key, * value;

    char name[256];

    /* Look for velox.yaml in the config directories */
    file = open_config_file("velox.yaml");

    /* Nothing to do if there is no configuration file */
    if (file == NULL) return;

    yaml_parser_initialize(&parser);
    yaml_parser_set_input_file(&parser, file);

    if (!yaml_parser_load(&parser, &document))
    {
        fprintf(stderr, "Error parsing config file\n");
        goto cleanup;
    }

    /* The root node should be a mapping */
    map = yaml_document_get_root_node(&document);
    assert(map->type == YAML_MAPPING_NODE);

    /* For each key/value pair in the root mapping */
    for (pair = map->data.mapping.pairs.start; pair < map->data.mapping.pairs.top; ++pair)
    {
        key = yaml_document_get_node(&document, pair->key);
        value = yaml_document_get_node(&document, pair->value);

        assert(key->type == YAML_SCALAR_NODE);

        /* The module section */
        if (strcmp((const char *) key->data.scalar.value, "modules") == 0)
        {
            yaml_node_item_t * module_item;
            yaml_node_t * node;

            assert(value->type == YAML_SEQUENCE_NODE);

            printf("\n** Loading Modules **\n");

            /* For each module */
            for (module_item = value->data.sequence.items.start;
                module_item < value->data.sequence.items.top;
                ++module_item)
            {
                node = yaml_document_get_node(&document, *module_item);

                load_module((const char *) node->data.scalar.value);
            }
        }
        /* The border_width property */
        else if (strcmp((const char *) key->data.scalar.value, "border_width") == 0)
        {
            assert(value->type == YAML_SCALAR_NODE);

            border_width = strtoul((const char *) value->data.scalar.value, NULL, 10);
        }
    }

    yaml_document_delete(&document);

    printf("\n** Configuring Modules **\n");

    /* While we still have documents to parse */
    while (yaml_parser_load(&parser, &document))
    {
        /* If the document contains no root node, we are at the end */
        if (yaml_document_get_root_node(&document) == NULL)
        {
            yaml_document_delete(&document);
            break;
        }

        sscanf((const char *) yaml_document_get_root_node(&document)->tag, "!velox:%s", name);

        /* Configure the specified module with this YAML document */
        configure_module(name, &document);

        yaml_document_delete(&document);
    }

    cleanup:
        yaml_parser_delete(&parser);
        fclose(file);
}
예제 #18
0
int check_long_utf16(void)
{
    yaml_parser_t parser;
    int k = 0;
    int j;
    int failed = 0;
    unsigned char ch0, ch1;
    unsigned char *buffer = malloc(2+LONG*2);
    assert(buffer);
    printf("checking a long utf16 sequence...\n");
    buffer[k++] = '\xff';
    buffer[k++] = '\xfe';
    for (j = 0; j < LONG; j ++) {
        if (j % 2) {
            buffer[k++] = '\x10';
            buffer[k++] = '\x04';
        }
        else {
            buffer[k++] = '/';
            buffer[k++] = '\x04';
        }
    }
    yaml_parser_initialize(&parser);
    yaml_parser_set_input_string(&parser, buffer, 2+LONG*2);
    for (k = 0; k < LONG; k++) {
        if (!parser.unread) {
            if (!yaml_parser_update_buffer(&parser, 1)) {
                printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
                failed = 1;
                break;
            }
        }
        if (!parser.unread) {
            printf("\tnot enough characters at %d\n", k);
            failed = 1;
            break;
        }
        if (k % 2) {
            ch0 = '\xd0';
            ch1 = '\x90';
        }
        else {
            ch0 = '\xd0';
            ch1 = '\xaf';
        }
        if (parser.buffer.pointer[0] != ch0 || parser.buffer.pointer[1] != ch1) {
            printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n",
                   (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1],
                   (int)ch0, (int)ch1);
            failed = 1;
            break;
        }
        parser.buffer.pointer += 2;
        parser.unread -= 1;
    }
    if (!failed) {
        if (!yaml_parser_update_buffer(&parser, 1)) {
            printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
            failed = 1;
        }
        else if (parser.buffer.pointer[0] != '\0') {
            printf("\texpected NUL, found %X (eof=%d, unread=%d)\n", (int)parser.buffer.pointer[0], parser.eof, parser.unread);
            failed = 1;
        }
    }
    yaml_parser_delete(&parser);
    free(buffer);
    printf("checking a long utf16 sequence: %d fail(s)\n", failed);
    return failed;
}
예제 #19
0
파일: parser.c 프로젝트: tomonacci/psych
/*
 * call-seq:
 *    parser.parse(yaml)
 *
 * Parse the YAML document contained in +yaml+.  Events will be called on
 * the handler set on the parser instance.
 *
 * See Psych::Parser and Psych::Parser#handler
 */
static VALUE parse(VALUE self, VALUE yaml)
{
    yaml_parser_t parser;
    yaml_event_t event;

    yaml_parser_initialize(&parser);

    if(rb_respond_to(yaml, id_read)) {
	yaml_parser_set_input(&parser, io_reader, (void *)yaml);
    } else {
	yaml_parser_set_input_string(
		&parser,
		(const unsigned char *)StringValuePtr(yaml),
		(size_t)RSTRING_LEN(yaml)
		);
    }

    int done = 0;
#ifdef HAVE_RUBY_ENCODING_H
    int encoding = rb_enc_find_index("ASCII-8BIT");
#endif

    VALUE handler = rb_iv_get(self, "@handler");

    while(!done) {
	if(!yaml_parser_parse(&parser, &event)) {
	    size_t line   = parser.mark.line;
	    size_t column = parser.mark.column;

	    yaml_parser_delete(&parser);
	    rb_raise(ePsychSyntaxError, "couldn't parse YAML at line %d column %d",
		    (int)line, (int)column);
	}

	switch(event.type) {
	    case YAML_STREAM_START_EVENT:

#ifdef HAVE_RUBY_ENCODING_H
		switch(event.data.stream_start.encoding) {
		    case YAML_ANY_ENCODING:
			break;
		    case YAML_UTF8_ENCODING:
			encoding = rb_enc_find_index("UTF-8");
			break;
		    case YAML_UTF16LE_ENCODING:
			encoding = rb_enc_find_index("UTF-16LE");
			break;
		    case YAML_UTF16BE_ENCODING:
			encoding = rb_enc_find_index("UTF-16BE");
			break;
		    default:
			break;
		}
#endif

		rb_funcall(handler, id_start_stream, 1,
			INT2NUM((long)event.data.stream_start.encoding)
	      );
		break;
	    case YAML_DOCUMENT_START_EVENT:
		{
	// Grab the document version
	VALUE version = event.data.document_start.version_directive ?
	    rb_ary_new3(
		    (long)2,
		    INT2NUM((long)event.data.document_start.version_directive->major),
		    INT2NUM((long)event.data.document_start.version_directive->minor)
		 ) : rb_ary_new();

	// Get a list of tag directives (if any)
	VALUE tag_directives = rb_ary_new();
	if(event.data.document_start.tag_directives.start) {
	    yaml_tag_directive_t *start =
		event.data.document_start.tag_directives.start;
	    yaml_tag_directive_t *end =
		event.data.document_start.tag_directives.end;
	    for(; start != end; start++) {
		VALUE handle = Qnil;
		if(start->handle) {
		    handle = rb_str_new2((const char *)start->handle);
#ifdef HAVE_RUBY_ENCODING_H
		    rb_enc_associate_index(handle, encoding);
#endif
		}

		VALUE prefix = Qnil;
		if(start->prefix) {
		    prefix = rb_str_new2((const char *)start->prefix);
#ifdef HAVE_RUBY_ENCODING_H
		    rb_enc_associate_index(prefix, encoding);
#endif
		}

		VALUE pair = rb_ary_new3((long)2, handle, prefix);
		rb_ary_push(tag_directives, pair);
	    }
	}
	rb_funcall(handler, id_start_document, 3,
		version, tag_directives,
		event.data.document_start.implicit == 1 ? Qtrue : Qfalse
	    );
    }
		break;
	    case YAML_DOCUMENT_END_EVENT:
		rb_funcall(handler, id_end_document, 1,
			event.data.document_end.implicit == 1 ? Qtrue : Qfalse
	      );
		break;
	    case YAML_ALIAS_EVENT:
		{
	VALUE alias = Qnil;
	if(event.data.alias.anchor) {
	    alias = rb_str_new2((const char *)event.data.alias.anchor);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(alias, encoding);
#endif
	}

	rb_funcall(handler, id_alias, 1, alias);
    }
		break;
	    case YAML_SCALAR_EVENT:
		{
	VALUE val = rb_str_new(
		(const char *)event.data.scalar.value,
		(long)event.data.scalar.length
		);

#ifdef HAVE_RUBY_ENCODING_H
	rb_enc_associate_index(val, encoding);
#endif

	VALUE anchor = Qnil;
	if(event.data.scalar.anchor) {
	    anchor = rb_str_new2((const char *)event.data.scalar.anchor);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(anchor, encoding);
#endif
	}

	VALUE tag = Qnil;
	if(event.data.scalar.tag) {
	    tag = rb_str_new2((const char *)event.data.scalar.tag);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(tag, encoding);
#endif
	}

	VALUE plain_implicit =
	    event.data.scalar.plain_implicit == 0 ? Qfalse : Qtrue;

	VALUE quoted_implicit =
	    event.data.scalar.quoted_implicit == 0 ? Qfalse : Qtrue;

	VALUE style = INT2NUM((long)event.data.scalar.style);

	rb_funcall(handler, id_scalar, 6,
		val, anchor, tag, plain_implicit, quoted_implicit, style);
    }
		break;
	    case YAML_SEQUENCE_START_EVENT:
		{
	VALUE anchor = Qnil;
	if(event.data.sequence_start.anchor) {
	    anchor = rb_str_new2((const char *)event.data.sequence_start.anchor);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(anchor, encoding);
#endif
	}

	VALUE tag = Qnil;
	if(event.data.sequence_start.tag) {
	    tag = rb_str_new2((const char *)event.data.sequence_start.tag);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(tag, encoding);
#endif
	}

	VALUE implicit =
	    event.data.sequence_start.implicit == 0 ? Qfalse : Qtrue;

	VALUE style = INT2NUM((long)event.data.sequence_start.style);

	rb_funcall(handler, id_start_sequence, 4,
		anchor, tag, implicit, style);
    }
		break;
	    case YAML_SEQUENCE_END_EVENT:
		rb_funcall(handler, id_end_sequence, 0);
		break;
	    case YAML_MAPPING_START_EVENT:
		{
	VALUE anchor = Qnil;
	if(event.data.mapping_start.anchor) {
	    anchor = rb_str_new2((const char *)event.data.mapping_start.anchor);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(anchor, encoding);
#endif
	}

	VALUE tag = Qnil;
	if(event.data.mapping_start.tag) {
	    tag = rb_str_new2((const char *)event.data.mapping_start.tag);
#ifdef HAVE_RUBY_ENCODING_H
	    rb_enc_associate_index(tag, encoding);
#endif
	}

	VALUE implicit =
	    event.data.mapping_start.implicit == 0 ? Qfalse : Qtrue;

	VALUE style = INT2NUM((long)event.data.mapping_start.style);

	rb_funcall(handler, id_start_mapping, 4,
		anchor, tag, implicit, style);
    }
		break;
	    case YAML_MAPPING_END_EVENT:
		rb_funcall(handler, id_end_mapping, 0);
		break;
	    case YAML_NO_EVENT:
		rb_funcall(handler, id_empty, 0);
		break;
	    case YAML_STREAM_END_EVENT:
		rb_funcall(handler, id_end_stream, 0);
		done = 1;
		break;
	}
    }

    return self;
}
예제 #20
0
bool YamlParser::Parse(YamlDataHolder * dataHolder)
{
	yaml_parser_t parser;
	yaml_event_t event;
	
	int done = 0;
	
	/* Create the Parser object. */
	yaml_parser_initialize(&parser);
	
	yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING);
	
	/* Set a string input. */
	//yaml_parser_set_input_string(&parser, (const unsigned char*)pathName.c_str(), pathName.length());
		
	yaml_parser_set_input(&parser, read_handler, dataHolder);

	String lastMapKey;
	bool isKeyPresent = false;

	/* Read the event sequence. */
	while (!done) 
	{
		
		/* Get the next event. */
		if (!yaml_parser_parse(&parser, &event))
		{
			Logger::Error("[YamlParser::Parse] error: type: %d %s line: %d pos: %d", parser.error, parser.problem, parser.problem_mark.line, parser.problem_mark.column);
			break;
		}
		
		switch(event.type)
		{
		case YAML_ALIAS_EVENT:
			Logger::FrameworkDebug("[YamlParser::Parse] alias: %s", event.data.alias.anchor);
			break;
		
		case YAML_SCALAR_EVENT:
			{
				String scalarValue = (const char*)event.data.scalar.value;

				if (objectStack.empty())
				{
					YamlNode * node = YamlNode::CreateStringNode();
					node->Set(scalarValue);
					rootObject = node;
				}
				else
				{
					YamlNode * topContainer = objectStack.top();
					DVASSERT(topContainer->GetType() != YamlNode::TYPE_STRING);
					if (topContainer->GetType() == YamlNode::TYPE_MAP)
					{
						if (!isKeyPresent)
						{
							lastMapKey = scalarValue;
						}
						else
						{
							topContainer->Add(lastMapKey, scalarValue);
						}
						isKeyPresent = !isKeyPresent;
					}
					else if (topContainer->GetType() == YamlNode::TYPE_ARRAY)
					{
						topContainer->Add(scalarValue);
					}
				}
			}
			break;
		
		case YAML_DOCUMENT_START_EVENT:
			//Logger::FrameworkDebug("document start:");
			break;
		
		case YAML_DOCUMENT_END_EVENT:
			//Logger::FrameworkDebug("document end:");
			break;

		case YAML_SEQUENCE_START_EVENT:
			{
				YamlNode * node = YamlNode::CreateArrayNode();
				if (objectStack.empty())
				{
					rootObject = node;
				}
				else
				{
					YamlNode * topContainer = objectStack.top();
					DVASSERT(topContainer->GetType() != YamlNode::TYPE_STRING);
					if (topContainer->GetType() == YamlNode::TYPE_MAP)
					{
						DVASSERT(isKeyPresent);
						topContainer->AddNodeToMap(lastMapKey, node);
						isKeyPresent = false;
					}
					else if (topContainer->GetType() == YamlNode::TYPE_ARRAY)
					{
						topContainer->AddNodeToArray(node);
					}
				}
				objectStack.push(node);
			}break;
				
		case YAML_SEQUENCE_END_EVENT:
			{
				objectStack.pop();
			}break;
		
		case YAML_MAPPING_START_EVENT:
			{
				YamlNode * node = YamlNode::CreateMapNode();
				if (objectStack.empty())
				{
					rootObject = node;
				}
				else
				{
					YamlNode * topContainer = objectStack.top();
					if (topContainer->GetType() == YamlNode::TYPE_MAP)
					{
						DVASSERT(isKeyPresent);
						topContainer->AddNodeToMap(lastMapKey, node);
						isKeyPresent = false;
					}
					else if (topContainer->GetType() == YamlNode::TYPE_ARRAY)
					{
						topContainer->AddNodeToArray(node);
					}
				}
				objectStack.push(node);
			}
			break;
				
		case YAML_MAPPING_END_EVENT:
			{
				objectStack.pop();
			}
			break;
        default:
            break;
		};

		/* Are we finished? */
		done = (event.type == YAML_STREAM_END_EVENT);
		
		/* The application is responsible for destroying the event object. */
		yaml_event_delete(&event);
		
	}

	/* Destroy the Parser object. */
	yaml_parser_delete(&parser);

    DVASSERT(objectStack.size() == 0);

    return true;
}
int init_psdf_parser__()
{
  yaml_parser_initialize(&parser);
  yaml_parser_set_input_file(&parser, stdin);
  return 0;
}
LocalizationSystem::StringFile * LocalizationSystem::LoadFromYamlFile(const String & langID, const String & pathName)
{
	yaml_parser_t parser;
	yaml_event_t event;
	
	int done = 0;
	
	/* Create the Parser object. */
	yaml_parser_initialize(&parser);
	
	yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING);
	
	File * yamlFile = File::Create(pathName, File::OPEN | File::READ);
    if(!yamlFile) return NULL;
    
	dataHolder->fileSize = yamlFile->GetSize();
	dataHolder->data = new uint8[dataHolder->fileSize];
	dataHolder->dataOffset = 0;
	yamlFile->Read(dataHolder->data, dataHolder->fileSize);
	yamlFile->Release();
	
	yaml_parser_set_input(&parser, read_handler, dataHolder);
	
	WideString key;
	WideString value;
	bool isKey = true;
	StringFile * strFile = new StringFile();
	
	/* Read the event sequence. */
	while (!done) 
	{
		
		/* Get the next event. */
		if (!yaml_parser_parse(&parser, &event))
		{
			Logger::Debug("parsing error: type: %d %s line: %d pos: %d", parser.error, parser.problem, parser.problem_mark.line, parser.problem_mark.column);
			SafeDelete(strFile);
			break;
		}
				
		switch(event.type)
		{
			case YAML_ALIAS_EVENT:
				//Logger::Debug("alias: %s", event.data.alias.anchor);
				break;
				
			case YAML_SCALAR_EVENT:
			{
				
				if (isKey)
				{
					UTF8Utils::EncodeToWideString((uint8*)event.data.scalar.value, (int32)event.data.scalar.length, key);
				}else 
				{
					UTF8Utils::EncodeToWideString((uint8*)event.data.scalar.value, (int32)event.data.scalar.length, value);
					strFile->strings[key] = value;
				}
				
				isKey = !isKey;
			}
			break;
				
			case YAML_DOCUMENT_START_EVENT:
			{
				//Logger::Debug("document start:");
			}break;
				
			case YAML_DOCUMENT_END_EVENT:
			{	//Logger::Debug("document end:");
			}
				break;
				
			case YAML_SEQUENCE_START_EVENT:
			{
			}break;
				
			case YAML_SEQUENCE_END_EVENT:
			{
			}break;
				
			case YAML_MAPPING_START_EVENT:
			{
			}
			break;
				
			case YAML_MAPPING_END_EVENT:
			{
			}
			break;
                default:
                break;
		};
		
		/* Are we finished? */
		done = (event.type == YAML_STREAM_END_EVENT);
		
		/* The application is responsible for destroying the event object. */
		yaml_event_delete(&event);
		
	}
	
	yaml_parser_delete(&parser);	
	if (strFile)
	{
		strFile->pathName = pathName;
		strFile->langId = langID;
	}

	SafeDeleteArray(dataHolder->data);
	return strFile;
}
예제 #23
0
/*
 * call-seq:
 *    parser.parse(yaml)
 *
 * Parse the YAML document contained in +yaml+.  Events will be called on
 * the handler set on the parser instance.
 *
 * See Psych::Parser and Psych::Parser#handler
 */
static VALUE parse(int argc, VALUE *argv, VALUE self)
{
    VALUE yaml, path;
    yaml_parser_t * parser;
    yaml_event_t event;
    int done = 0;
    int tainted = 0;
    int state = 0;
    int parser_encoding = YAML_ANY_ENCODING;
    int encoding = rb_utf8_encindex();
    rb_encoding * internal_enc = rb_default_internal_encoding();
    VALUE handler = rb_iv_get(self, "@handler");

    if (rb_scan_args(argc, argv, "11", &yaml, &path) == 1) {
	if(rb_respond_to(yaml, id_path))
	    path = rb_funcall(yaml, id_path, 0);
	else
	    path = rb_str_new2("<unknown>");
    }

    TypedData_Get_Struct(self, yaml_parser_t, &psych_parser_type, parser);

    yaml_parser_delete(parser);
    yaml_parser_initialize(parser);

    if (OBJ_TAINTED(yaml)) tainted = 1;

    if (rb_respond_to(yaml, id_read)) {
	yaml = transcode_io(yaml, &parser_encoding);
	yaml_parser_set_encoding(parser, parser_encoding);
	yaml_parser_set_input(parser, io_reader, (void *)yaml);
	if (RTEST(rb_obj_is_kind_of(yaml, rb_cIO))) tainted = 1;
    } else {
	StringValue(yaml);
	yaml = transcode_string(yaml, &parser_encoding);
	yaml_parser_set_encoding(parser, parser_encoding);
	yaml_parser_set_input_string(
		parser,
		(const unsigned char *)RSTRING_PTR(yaml),
		(size_t)RSTRING_LEN(yaml)
		);
    }

    while(!done) {
	VALUE event_args[5];
	VALUE start_line, start_column, end_line, end_column;

	if(!yaml_parser_parse(parser, &event)) {
	    VALUE exception;

	    exception = make_exception(parser, path);
	    yaml_parser_delete(parser);
	    yaml_parser_initialize(parser);

	    rb_exc_raise(exception);
	}

	start_line = INT2NUM((long)event.start_mark.line);
	start_column = INT2NUM((long)event.start_mark.column);
	end_line = INT2NUM((long)event.end_mark.line);
	end_column = INT2NUM((long)event.end_mark.column);

	event_args[0] = handler;
	event_args[1] = start_line;
	event_args[2] = start_column;
	event_args[3] = end_line;
	event_args[4] = end_column;
	rb_protect(protected_event_location, (VALUE)event_args, &state);

	switch(event.type) {
	    case YAML_STREAM_START_EVENT:
	      {
		  VALUE args[2];

		  args[0] = handler;
		  args[1] = INT2NUM((long)event.data.stream_start.encoding);
		  rb_protect(protected_start_stream, (VALUE)args, &state);
	      }
	      break;
	  case YAML_DOCUMENT_START_EVENT:
	    {
		VALUE args[4];
		/* Get a list of tag directives (if any) */
		VALUE tag_directives = rb_ary_new();
		/* Grab the document version */
		VALUE version = event.data.document_start.version_directive ?
		    rb_ary_new3(
			(long)2,
			INT2NUM((long)event.data.document_start.version_directive->major),
			INT2NUM((long)event.data.document_start.version_directive->minor)
			) : rb_ary_new();

		if(event.data.document_start.tag_directives.start) {
		    yaml_tag_directive_t *start =
			event.data.document_start.tag_directives.start;
		    yaml_tag_directive_t *end =
			event.data.document_start.tag_directives.end;
		    for(; start != end; start++) {
			VALUE handle = Qnil;
			VALUE prefix = Qnil;
			if(start->handle) {
			    handle = rb_str_new2((const char *)start->handle);
			    if (tainted) OBJ_TAINT(handle);
			    PSYCH_TRANSCODE(handle, encoding, internal_enc);
			}

			if(start->prefix) {
			    prefix = rb_str_new2((const char *)start->prefix);
			    if (tainted) OBJ_TAINT(prefix);
			    PSYCH_TRANSCODE(prefix, encoding, internal_enc);
			}

			rb_ary_push(tag_directives, rb_ary_new3((long)2, handle, prefix));
		    }
		}
		args[0] = handler;
		args[1] = version;
		args[2] = tag_directives;
		args[3] = event.data.document_start.implicit == 1 ? Qtrue : Qfalse;
		rb_protect(protected_start_document, (VALUE)args, &state);
	    }
	    break;
	  case YAML_DOCUMENT_END_EVENT:
	    {
		VALUE args[2];

		args[0] = handler;
		args[1] = event.data.document_end.implicit == 1 ? Qtrue : Qfalse;
		rb_protect(protected_end_document, (VALUE)args, &state);
	    }
	    break;
	  case YAML_ALIAS_EVENT:
	    {
		VALUE args[2];
		VALUE alias = Qnil;
		if(event.data.alias.anchor) {
		    alias = rb_str_new2((const char *)event.data.alias.anchor);
		    if (tainted) OBJ_TAINT(alias);
		    PSYCH_TRANSCODE(alias, encoding, internal_enc);
		}

		args[0] = handler;
		args[1] = alias;
		rb_protect(protected_alias, (VALUE)args, &state);
	    }
	    break;
	  case YAML_SCALAR_EVENT:
	    {
		VALUE args[7];
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE plain_implicit, quoted_implicit, style;
		VALUE val = rb_str_new(
		    (const char *)event.data.scalar.value,
		    (long)event.data.scalar.length
		    );
		if (tainted) OBJ_TAINT(val);

		PSYCH_TRANSCODE(val, encoding, internal_enc);

		if(event.data.scalar.anchor) {
		    anchor = rb_str_new2((const char *)event.data.scalar.anchor);
		    if (tainted) OBJ_TAINT(anchor);
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
		}

		if(event.data.scalar.tag) {
		    tag = rb_str_new2((const char *)event.data.scalar.tag);
		    if (tainted) OBJ_TAINT(tag);
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
		}

		plain_implicit =
		    event.data.scalar.plain_implicit == 0 ? Qfalse : Qtrue;

		quoted_implicit =
		    event.data.scalar.quoted_implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.scalar.style);

		args[0] = handler;
		args[1] = val;
		args[2] = anchor;
		args[3] = tag;
		args[4] = plain_implicit;
		args[5] = quoted_implicit;
		args[6] = style;
		rb_protect(protected_scalar, (VALUE)args, &state);
	    }
	    break;
	  case YAML_SEQUENCE_START_EVENT:
	    {
		VALUE args[5];
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE implicit, style;
		if(event.data.sequence_start.anchor) {
		    anchor = rb_str_new2((const char *)event.data.sequence_start.anchor);
		    if (tainted) OBJ_TAINT(anchor);
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
		}

		tag = Qnil;
		if(event.data.sequence_start.tag) {
		    tag = rb_str_new2((const char *)event.data.sequence_start.tag);
		    if (tainted) OBJ_TAINT(tag);
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
		}

		implicit =
		    event.data.sequence_start.implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.sequence_start.style);

		args[0] = handler;
		args[1] = anchor;
		args[2] = tag;
		args[3] = implicit;
		args[4] = style;

		rb_protect(protected_start_sequence, (VALUE)args, &state);
	    }
	    break;
	  case YAML_SEQUENCE_END_EVENT:
	    rb_protect(protected_end_sequence, handler, &state);
	    break;
	  case YAML_MAPPING_START_EVENT:
	    {
		VALUE args[5];
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE implicit, style;
		if(event.data.mapping_start.anchor) {
		    anchor = rb_str_new2((const char *)event.data.mapping_start.anchor);
		    if (tainted) OBJ_TAINT(anchor);
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
		}

		if(event.data.mapping_start.tag) {
		    tag = rb_str_new2((const char *)event.data.mapping_start.tag);
		    if (tainted) OBJ_TAINT(tag);
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
		}

		implicit =
		    event.data.mapping_start.implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.mapping_start.style);

		args[0] = handler;
		args[1] = anchor;
		args[2] = tag;
		args[3] = implicit;
		args[4] = style;

		rb_protect(protected_start_mapping, (VALUE)args, &state);
	    }
	    break;
	  case YAML_MAPPING_END_EVENT:
	    rb_protect(protected_end_mapping, handler, &state);
	    break;
	  case YAML_NO_EVENT:
	    rb_protect(protected_empty, handler, &state);
	    break;
	  case YAML_STREAM_END_EVENT:
	    rb_protect(protected_end_stream, handler, &state);
	    done = 1;
	    break;
	}
	yaml_event_delete(&event);
	if (state) rb_jump_tag(state);
    }

    return self;
}
예제 #24
0
static ERL_NIF_TERM binary_to_libyaml_event_stream_rev(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    ErlNifBinary bin;
    ERL_NIF_TERM tail;
    yaml_parser_t parser;
    yaml_event_t event;
    yaml_error_type_t error;
    int done = 0;
    char msg[200];

    if (!enif_inspect_binary(env, argv[0], &bin))
    {
        return enif_make_badarg(env);
    }

    tail = enif_make_list(env,0);

    /* Create the Parser object. */
    yaml_parser_initialize(&parser);

    yaml_parser_set_input_string(&parser, bin.data, bin.size);

    /* Read the event sequence. */
    while (!done) {

        /* Get the next event. */
        if (!yaml_parser_parse(&parser, &event))
            goto parser_error;

        // convert and add to list
        tail = enif_make_list_cell(env, event_to_term(env,&event), tail);

        /* Are we finished? */
        done = (event.type == YAML_STREAM_END_EVENT);

        /* The application is responsible for destroying the event object. */
        yaml_event_delete(&event);

    }

    /* Destroy the Parser object. */
    yaml_parser_delete(&parser);

    return enif_make_tuple2(env,
                            enif_make_atom(env, "ok"),
                            tail);

    /* On error. */
parser_error:
    memset(msg,0, sizeof(msg));

    error = parser.error;
    switch (error)
    {
    case YAML_MEMORY_ERROR:
        snprintf(msg, sizeof(msg), "Memory error: Not enough memory for parsing\n");
        break;

    case YAML_READER_ERROR:
        if (parser.problem_value != -1) {
            snprintf(msg, sizeof(msg), "Reader error: %s: #%X at %zu\n", parser.problem,
                     parser.problem_value, parser.problem_offset);
        }
        else {
            fprintf(stderr, "Reader error: %s at %zu\n", parser.problem,
                    parser.problem_offset);
        }
        break;

    case YAML_SCANNER_ERROR:
        if (parser.context) {
            snprintf(msg, sizeof(msg), "Scanner error: %s at line %zu, column %zu\n"
                     "%s at line %zu, column %zu\n", parser.context,
                     parser.context_mark.line+1, parser.context_mark.column+1,
                     parser.problem, parser.problem_mark.line+1,
                     parser.problem_mark.column+1);
        }
        else {
            snprintf(msg, sizeof(msg), "Scanner error: %s at line %zu, column %zu\n",
                     parser.problem, parser.problem_mark.line+1,
                     parser.problem_mark.column+1);
        }
        break;

    case YAML_PARSER_ERROR:
        if (parser.context) {
            snprintf(msg, sizeof(msg), "Parser error: %s at line %zu, column %zu\n"
                     "%s at line %zu, column %zu\n", parser.context,
                     parser.context_mark.line+1, parser.context_mark.column+1,
                     parser.problem, parser.problem_mark.line+1,
                     parser.problem_mark.column+1);
        }
        else {
            snprintf(msg, sizeof(msg), "Parser error: %s at line %zu, column %zu\n",
                     parser.problem, parser.problem_mark.line+1,
                     parser.problem_mark.column+1);
        }
        break;
    default:
    	break;
    }



    /* Destroy the Parser object. */
    yaml_parser_delete(&parser);

    return enif_make_tuple2(env,
                            enif_make_atom(env, "error"),
                            enif_make_tuple2(env,
                                             enum_to_atom(env, error, error_type_atoms),
                                             cstr_to_binary(env,msg)));

}
예제 #25
0
파일: drop.c 프로젝트: gjb7/it276-zelda
bool _load_drop_config_from_yaml_file(char *path, entity_t *entity) {
    yaml_parser_t parser;
    yaml_event_t  event;
    FILE *input;
    char *currentKey = NULL;
    drop_t *drop_data = (drop_t *)entity->entity_data;
    
    yaml_parser_initialize(&parser);
    
    input = fopen(path, "rb");
    if (input == NULL) {
        goto error;
    }
    
    yaml_parser_set_input_file(&parser, input);
    
    do {
        int handledValue = 0;
        
        if (!yaml_parser_parse(&parser, &event)) {
            break;
        }
        
        switch (event.type) {
            case YAML_SCALAR_EVENT:
                if (!currentKey) {
                    char *aKey = (char *)event.data.scalar.value;
                    int length = (strlen(aKey) + 1);
                    
                    currentKey = malloc(length * sizeof(char));
                    strncpy(currentKey, aKey, length);
                    currentKey[length - 1] = '\0';
                }
                else {
                    if (strcmp(currentKey, "name") == 0) {
                        snprintf(entity->class_name, ENTITY_CLASS_NAME_LENGTH, "drop:%s", event.data.scalar.value);
                    }
                    else if (strcmp(currentKey, "sprite") == 0) {
                        char *spriteFile = (char *)event.data.scalar.value;
                        drop_data->sprite = animated_sprite_create(spriteFile);
                        animated_sprite_set_current_animation(drop_data->sprite, "idle");
                    }
                    else if (strcmp(currentKey, "target") == 0) {
                        drop_data->target = atoi((char *)event.data.scalar.value);
                    }
                    else if (strcmp(currentKey, "bounding_box") == 0) {
                        int x, y, width, height;
                        
                        sscanf((char *)event.data.scalar.value, "%i,%i,%i,%i", &x, &y, &width, &height);
                        entity->bounding_box = graphics_rect_make(x, y, width, height);
                    }
                    
                    handledValue = 1;
                }
                
                break;
            default:
                break;
        }
        
        if (handledValue) {
            free(currentKey);
            currentKey = NULL;
            
            handledValue = 0;
        }
        
        if (event.type != YAML_STREAM_END_EVENT) {
            yaml_event_delete(&event);
        }
    } while (event.type != YAML_STREAM_END_EVENT);
    
    yaml_event_delete(&event);
    
    yaml_parser_delete(&parser);
    
    fclose(input);
    
    return true;
    
error:
    yaml_event_delete(&event);
    yaml_parser_delete(&parser);
    fclose(input);
    
    return false;
}
예제 #26
0
int main (
    int     argc,
    char    *argv [])
{
    char    *fname = "/etc/apache2/conf.d/php.conf.yaml";
    FILE    *fh;

    if (argc > 1)
        fname = argv [1];

    fh = fopen(fname, "r");

    printf ("Openned :%s:\n", fname);

    yaml_parser_t parser;
    yaml_token_t  token;   /* New variable */

    /* Initialize parser */
    if(!yaml_parser_initialize(&parser))
        fputs("Failed to initialize parser!\n", stderr);
    if(fh == NULL)
        fputs("Failed to open file!\n", stderr);

    /* Set input file */
    yaml_parser_set_input_file(&parser, fh);

    /* START new code */
    do {
        yaml_parser_scan(&parser, &token);
        switch(token.type)
        {
        /* Stream start/end */
        case YAML_STREAM_START_TOKEN:
            puts("STREAM START");
            break;
        case YAML_STREAM_END_TOKEN:
            puts("STREAM END");
            break;
        /* Token types (read before actual token) */
        case YAML_KEY_TOKEN:
            printf("(Key token)   ");
            break;
        case YAML_VALUE_TOKEN:
            printf("(Value token) ");
            break;
        /* Block delimeters */
        case YAML_BLOCK_SEQUENCE_START_TOKEN:
            puts("<b>Start Block (Sequence)</b>");
            break;
        case YAML_BLOCK_ENTRY_TOKEN:
            puts("<b>Start Block (Entry)</b>");
            break;
        case YAML_BLOCK_END_TOKEN:
            puts("<b>End block</b>");
            break;
        /* Data */
        case YAML_BLOCK_MAPPING_START_TOKEN:
            puts("[Block mapping]");
            break;
        case YAML_SCALAR_TOKEN:
            printf("scalar %s \n", token.data.scalar.value);
            break;
        /* Others */
        default:
            printf("Got token of type %d\n", token.type);
        }

        if(token.type != YAML_STREAM_END_TOKEN)
            yaml_token_delete(&token);
    } while (token.type != YAML_STREAM_END_TOKEN);

    yaml_token_delete(&token);
    /* END new code */

    /* Cleanup */
    yaml_parser_delete(&parser);
    fclose(fh);

    return 0;
}