html5ever 0.14.0

High-performance browser-grade HTML5 parser
Documentation
// Copyright 2014-2015 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate phf_codegen;
#[macro_use] extern crate quote;
extern crate rustc_serialize;
extern crate syn;

use rustc_serialize::json::{Json, Decoder};
use rustc_serialize::Decodable;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

#[path = "macros/match_token.rs"]
mod match_token;

fn main() {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();

    let rules_rs = Path::new(&manifest_dir).join("src/tree_builder/rules.rs");
    match_token::expand_match_tokens(
        &rules_rs,
        &Path::new(&env::var("OUT_DIR").unwrap()).join("rules.rs"));

    named_entities_to_phf(
        &Path::new(&manifest_dir).join("data/entities.json"),
        &Path::new(&env::var("OUT_DIR").unwrap()).join("named_entities.rs"));

    println!("cargo:rerun-if-changed={}", rules_rs.display());
}

fn named_entities_to_phf(from: &Path, to: &Path) {
    // A struct matching the entries in entities.json.
    #[derive(RustcDecodable)]
    struct CharRef {
        codepoints: Vec<u32>,
        //characters: String,  // Present in the file but we don't need it
    }

    let json = Json::from_reader(&mut File::open(from).unwrap()).unwrap();
    let entities: HashMap<String, CharRef> = Decodable::decode(&mut Decoder::new(json)).unwrap();
    let mut entities: HashMap<&str, (u32, u32)> = entities.iter().map(|(name, char_ref)| {
        assert!(name.starts_with("&"));
        assert!(char_ref.codepoints.len() <= 2);
        (&name[1..], (char_ref.codepoints[0], *char_ref.codepoints.get(1).unwrap_or(&0)))
    }).collect();

    // Add every missing prefix of those keys, mapping to NULL characters.
    for key in entities.keys().cloned().collect::<Vec<_>>() {
        for n in 1 .. key.len() {
            entities.entry(&key[..n]).or_insert((0, 0));
        }
    }
    entities.insert("", (0, 0));

    let mut phf_map = phf_codegen::Map::new();
    for (key, value) in entities {
        phf_map.entry(key, &format!("{:?}", value));
    }

    let mut file = File::create(to).unwrap();
    write!(&mut file, "pub static NAMED_ENTITIES: Map<&'static str, (u32, u32)> = ").unwrap();
    phf_map.build(&mut file).unwrap();
    write!(&mut file, ";\n").unwrap();
}