<commit_before>/*
 * Copyright 2014 Cloudius Systems
 */

#ifndef SSTRING_HH_
#define SSTRING_HH_

#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
#include "core/temporary_buffer.hh"

template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
    union contents {
        struct external_type {
            char* str;
            size_type size;
            int8_t pad;
        } external;
        struct internal_type {
            char str[max_size];
            int8_t size;
        } internal;
        static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
        static_assert(max_size <= 127, "max_size too large");
    } u;
    bool is_internal() const noexcept {
        return u.internal.size >= 0;
    }
    bool is_external() const noexcept {
        return !is_internal();
    }
    const char* str() const {
        return is_internal() ? u.internal.str : u.external.str;
    }
    char* str() {
        return is_internal() ? u.internal.str : u.external.str;
    }
public:
    struct initialized_later {};

    basic_sstring() noexcept {
        u.internal.size = 0;
        u.internal.str[0] = '\0';
    }
    basic_sstring(const basic_sstring& x) {
        if (x.is_internal()) {
            u.internal = x.u.internal;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char*>(std::malloc(x.u.external.size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
            u.external.size = x.u.external.size;
        }
    }
    basic_sstring(basic_sstring&& x) noexcept {
        u = x.u;
        x.u.internal.size = 0;
        x.u.internal.str[0] = '\0';
    }
    basic_sstring(initialized_later, size_t size) {
        if (size_type(size) != size) {
            throw std::overflow_error("sstring overflow");
        }
        if (size + 1 <= sizeof(u.internal.str)) {
            u.internal.str[size] = '\0';
            u.internal.size = size;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char*>(std::malloc(size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            u.external.size = size;
            u.external.str[size] = '\0';
        }
    }
    basic_sstring(const char_type* x, size_t size) {
        if (size_type(size) != size) {
            throw std::overflow_error("sstring overflow");
        }
        if (size + 1 <= sizeof(u.internal.str)) {
            std::copy(x, x + size, u.internal.str);
            u.internal.str[size] = '\0';
            u.internal.size = size;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char*>(std::malloc(size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            u.external.size = size;
            std::copy(x, x + size, u.external.str);
            u.external.str[size] = '\0';
        }
    }
    basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
    basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
    basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
    basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
    basic_sstring(const std::basic_string<char_type>& s)
        : basic_sstring(s.data(), s.size()) {}
    ~basic_sstring() noexcept {
        if (is_external()) {
            std::free(u.external.str);
        }
    }
    basic_sstring& operator=(const basic_sstring& x) {
        basic_sstring tmp(x);
        swap(tmp);
        return *this;
    }
    basic_sstring& operator=(basic_sstring&& x) noexcept {
        if (this != &x) {
            swap(x);
            x.reset();
        }
        return *this;
    }
    operator std::string() const {
        return { str(), size() };
    }
    size_t size() const noexcept {
        return is_internal() ? u.internal.size : u.external.size;
    }
    bool empty() const noexcept {
        return u.internal.size == 0;
    }
    void reset() noexcept {
        if (is_external()) {
            std::free(u.external.str);
        }
        u.internal.size = 0;
        u.internal.str[0] = '\0';
    }
    temporary_buffer<char_type> release() && {
        if (is_external()) {
            auto ptr = u.external.str;
            auto size = u.external.size;
            u.external.str = nullptr;
            u.external.size = 0;
            return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr));
        } else {
            auto buf = temporary_buffer<char_type>(u.internal.size);
            std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write());
            u.internal.size = 0;
            u.internal.str[0] = '\0';
            return buf;
        }
    }
    void swap(basic_sstring& x) noexcept {
        contents tmp;
        tmp = x.u;
        x.u = u;
        u = tmp;
    }
    const char* c_str() const {
        return str();
    }
    const char_type* begin() const { return str(); }
    const char_type* end() const { return str() + size(); }
    char_type* begin() { return str(); }
    char_type* end() { return str() + size(); }
    bool operator==(const basic_sstring& x) const {
        return size() == x.size() && std::equal(begin(), end(), x.begin());
    }
    bool operator!=(const basic_sstring& x) const {
        return !operator==(x);
    }
    basic_sstring operator+(const basic_sstring& x) const {
        basic_sstring ret(initialized_later(), size() + x.size());
        std::copy(begin(), end(), ret.begin());
        std::copy(x.begin(), x.end(), ret.begin() + size());
        return ret;
    }
    basic_sstring& operator+=(const basic_sstring& x) {
        return *this = *this + x;
    }

    operator std::experimental::string_view() const {
        return std::experimental::string_view(str(), size());
    }
};

template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }

template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }

template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }

template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }

template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }

template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }

template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
    return str_len(first) + str_len(second, tail...);
}

template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
          basic_sstring<char_type, size_type, max_size>& y) noexcept
{
    return x.swap(y);
}

template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
        const basic_sstring<char_type, size_type, max_size>& s) {
    return os.write(s.begin(), s.size());
}

namespace std {

template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
    size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
        return std::hash<std::experimental::string_view>()(s);
    }
};

}

using sstring = basic_sstring<char, uint32_t, 15>;

static inline
char* copy_str_to(char* dst) {
    return dst;
}

template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
    return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}

template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
    String ret(sstring::initialized_later(), str_len(args...));
    copy_str_to(ret.begin(), args...);
    return ret;
}

template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);

template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
    char tmp[sizeof(value) * 3 + 3];
    auto len = std::sprintf(tmp, fmt, value);
    return sstring(tmp, len);
}

template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
    return to_sstring_sprintf(value, "%d");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
    return to_sstring_sprintf(value, "%u");
}

template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%ld");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%lu");
}

template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%lld");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%llu");
}

template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
    return string_type(value);
}

template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
    return value;
}

template <typename string_type = sstring>
static string_type to_sstring(const temporary_buffer<char>& buf) {
    return string_type(buf.get(), buf.size());
}

template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    bool first = true;
    os << "{";
    for (auto&& elem : v) {
        if (!first) {
            os << ", ";
        } else {
            first = false;
        }
        os << elem;
    }
    os << "}";
    return os;
}

#endif /* SSTRING_HH_ */
<commit_msg>sstring: fix character type<commit_after>/*
 * Copyright 2014 Cloudius Systems
 */

#ifndef SSTRING_HH_
#define SSTRING_HH_

#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
#include "core/temporary_buffer.hh"

template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
    union contents {
        struct external_type {
            char_type* str;
            size_type size;
            int8_t pad;
        } external;
        struct internal_type {
            char_type str[max_size];
            int8_t size;
        } internal;
        static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
        static_assert(max_size <= 127, "max_size too large");
    } u;
    bool is_internal() const noexcept {
        return u.internal.size >= 0;
    }
    bool is_external() const noexcept {
        return !is_internal();
    }
    const char_type* str() const {
        return is_internal() ? u.internal.str : u.external.str;
    }
    char_type* str() {
        return is_internal() ? u.internal.str : u.external.str;
    }
public:
    struct initialized_later {};

    basic_sstring() noexcept {
        u.internal.size = 0;
        u.internal.str[0] = '\0';
    }
    basic_sstring(const basic_sstring& x) {
        if (x.is_internal()) {
            u.internal = x.u.internal;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
            u.external.size = x.u.external.size;
        }
    }
    basic_sstring(basic_sstring&& x) noexcept {
        u = x.u;
        x.u.internal.size = 0;
        x.u.internal.str[0] = '\0';
    }
    basic_sstring(initialized_later, size_t size) {
        if (size_type(size) != size) {
            throw std::overflow_error("sstring overflow");
        }
        if (size + 1 <= sizeof(u.internal.str)) {
            u.internal.str[size] = '\0';
            u.internal.size = size;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            u.external.size = size;
            u.external.str[size] = '\0';
        }
    }
    basic_sstring(const char_type* x, size_t size) {
        if (size_type(size) != size) {
            throw std::overflow_error("sstring overflow");
        }
        if (size + 1 <= sizeof(u.internal.str)) {
            std::copy(x, x + size, u.internal.str);
            u.internal.str[size] = '\0';
            u.internal.size = size;
        } else {
            u.internal.size = -1;
            u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
            if (!u.external.str) {
                throw std::bad_alloc();
            }
            u.external.size = size;
            std::copy(x, x + size, u.external.str);
            u.external.str[size] = '\0';
        }
    }
    basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
    basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
    basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
    basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
    basic_sstring(const std::basic_string<char_type>& s)
        : basic_sstring(s.data(), s.size()) {}
    ~basic_sstring() noexcept {
        if (is_external()) {
            std::free(u.external.str);
        }
    }
    basic_sstring& operator=(const basic_sstring& x) {
        basic_sstring tmp(x);
        swap(tmp);
        return *this;
    }
    basic_sstring& operator=(basic_sstring&& x) noexcept {
        if (this != &x) {
            swap(x);
            x.reset();
        }
        return *this;
    }
    operator std::string() const {
        return { str(), size() };
    }
    size_t size() const noexcept {
        return is_internal() ? u.internal.size : u.external.size;
    }
    bool empty() const noexcept {
        return u.internal.size == 0;
    }
    void reset() noexcept {
        if (is_external()) {
            std::free(u.external.str);
        }
        u.internal.size = 0;
        u.internal.str[0] = '\0';
    }
    temporary_buffer<char_type> release() && {
        if (is_external()) {
            auto ptr = u.external.str;
            auto size = u.external.size;
            u.external.str = nullptr;
            u.external.size = 0;
            return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr));
        } else {
            auto buf = temporary_buffer<char_type>(u.internal.size);
            std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write());
            u.internal.size = 0;
            u.internal.str[0] = '\0';
            return buf;
        }
    }
    void swap(basic_sstring& x) noexcept {
        contents tmp;
        tmp = x.u;
        x.u = u;
        u = tmp;
    }
    const char_type* c_str() const {
        return str();
    }
    const char_type* begin() const { return str(); }
    const char_type* end() const { return str() + size(); }
    char_type* begin() { return str(); }
    char_type* end() { return str() + size(); }
    bool operator==(const basic_sstring& x) const {
        return size() == x.size() && std::equal(begin(), end(), x.begin());
    }
    bool operator!=(const basic_sstring& x) const {
        return !operator==(x);
    }
    basic_sstring operator+(const basic_sstring& x) const {
        basic_sstring ret(initialized_later(), size() + x.size());
        std::copy(begin(), end(), ret.begin());
        std::copy(x.begin(), x.end(), ret.begin() + size());
        return ret;
    }
    basic_sstring& operator+=(const basic_sstring& x) {
        return *this = *this + x;
    }

    operator std::experimental::string_view() const {
        return std::experimental::string_view(str(), size());
    }
};

template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }

template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }

template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }

template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }

template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }

template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }

template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
    return str_len(first) + str_len(second, tail...);
}

template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
          basic_sstring<char_type, size_type, max_size>& y) noexcept
{
    return x.swap(y);
}

template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
        const basic_sstring<char_type, size_type, max_size>& s) {
    return os.write(s.begin(), s.size());
}

namespace std {

template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
    size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
        return std::hash<std::experimental::string_view>()(s);
    }
};

}

using sstring = basic_sstring<char, uint32_t, 15>;

static inline
char* copy_str_to(char* dst) {
    return dst;
}

template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
    return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}

template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
    String ret(sstring::initialized_later(), str_len(args...));
    copy_str_to(ret.begin(), args...);
    return ret;
}

template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);

template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
    char tmp[sizeof(value) * 3 + 3];
    auto len = std::sprintf(tmp, fmt, value);
    return sstring(tmp, len);
}

template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
    return to_sstring_sprintf(value, "%d");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
    return to_sstring_sprintf(value, "%u");
}

template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%ld");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%lu");
}

template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%lld");
}

template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
    return to_sstring_sprintf(value, "%llu");
}

template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
    return string_type(value);
}

template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
    return value;
}

template <typename string_type = sstring>
static string_type to_sstring(const temporary_buffer<char>& buf) {
    return string_type(buf.get(), buf.size());
}

template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    bool first = true;
    os << "{";
    for (auto&& elem : v) {
        if (!first) {
            os << ", ";
        } else {
            first = false;
        }
        os << elem;
    }
    os << "}";
    return os;
}

#endif /* SSTRING_HH_ */
<|endoftext|>


<commit_before>// Convert a non-negative integer to its english words representation. Given
// input is guaranteed to be less than 231 - 1.
// For example,
// 123 -> "One Hundred Twenty Three"
// 12345 -> "Twelve Thousand Three Hundred Forty Five"
// 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
// Seven"

class Solution {
  public:
    string numberToWords(int num) {
        std::array<int> vals = {1e9, 1e6, 1e3, 100, 90, 80, 70, 60, 50, 40, 30,
                                20,  19,  18,  17,  16, 15, 14, 13, 12, 11, 10,
                                9,   8,   7,   6,   5,  4,  3,  2,  1};
        std::array<string> words = {
            "Billion", "Million", "Thousand", "Hundred",  "Ninety",
            "Eighty",  "Seventy", "Sixty",    "Fifty",    "Forty",
            "Thirty",  "Twenty",  "Nineteen", "Eighteen", "Seventeen",
            "Sixteen", "Fifteen", "Fourteen", "Thirteen", "Twelve",
            "Eleven",  "Ten",     "Nine",     "Eight",    "Seven",
            "Six",     "Five",    "Four",     "Three",    "Two",
            "One"};
    }
};<commit_msg>update 273<commit_after>// Convert a non-negative integer to its english words representation. Given
// input is guaranteed to be less than 231 - 1.
// For example,
// 123 -> "One Hundred Twenty Three"
// 12345 -> "Twelve Thousand Three Hundred Forty Five"
// 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
// Seven"

class Solution {
    string smallNumToWords(int num) {
        vector<string> less20 = {"One",       "Two",      "Three",   "Four",
                                 "Five",      "Six",      "Seven",   "Eight",
                                 "Nine",      "Ten",      "Eleven",  "Twelve",
                                 "Thirteen",  "Fourteen", "Fifteen", "Sixteen",
                                 "Seventeen", "Eighteen", "Nineteen"};
        vector<string> tens = {"Twenty",  "Thirty", "Forty",  "Fifty",  "Sixty",
                               "Seventy", "Eighty", "Ninety"};
        int t = 0;
        string result;
        // assume 123
        if ((t = num / 100) > 0) {
            // t = 1
            result += less20[t - 1] + " Hundred";
        }
        if ((t = num % 100) > 19) {
            if (!result.empty())
                result += " ";
            // t = 23, 23 / 10 - 2 = 0
            result += tens[t / 10 - 2];
            if (t % 10 > 0)
                result += " " + less20[t % 10 - 1];
        } else if ((t = num % 20) > 0) {
            if (!result.empty())
                result += " ";
            // t = 3
            result += less20[t - 1];
        }
        return result;
    }

  public:
    string numberToWords(int num) {
        if (!num)
            return "Zero";

        string result;
        if (num >= 1000000000)
            result += smallNumToWords(num / 1000000000) + " Billion";
        num %= 1000000000;
        if (num >= 1000000) {
            if (!result.empty())
                result += " ";
            result += smallNumToWords(num / 1000000) + " Million";
        }
        num %= 1000000;
        if (num  >= 1000) {
            if (!result.empty())
                result += " ";
            result += smallNumToWords(num / 1000) + " Thousand";
        }
        num %= 1000;
        if (!result.empty() && num)
            result += " ";
        result += smallNumToWords(num);

        return result;
    }
};<|endoftext|>


<commit_before>// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(HOST_OS_FUCHSIA)

#include "vm/os.h"

#include <errno.h>
#include <lib/fdio/util.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>

#include <fuchsia/timezone/cpp/fidl.h>

#include "lib/component/cpp/startup_context.h"
#include "lib/svc/cpp/services.h"

#include "platform/assert.h"
#include "vm/zone.h"

namespace dart {

#ifndef PRODUCT

DEFINE_FLAG(bool,
            generate_perf_events_symbols,
            false,
            "Generate events symbols for profiling with perf");

#endif  // !PRODUCT

const char* OS::Name() {
  return "fuchsia";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

// TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to
// directly get timezone.
//
// Putting this hack right now due to CP-120 as I need to remove
// component:ConnectToEnvironmentServices and this is the only thing that is
// blocking it and FL-98 will take time.
static fuchsia::timezone::TimezoneSyncPtr tz;

static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch,
                                                 int32_t* local_offset,
                                                 int32_t* dst_offset) {
  zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000,
                                                    local_offset, dst_offset);
  if (status != ZX_OK) {
    return status;
  }
  *local_offset *= 60;
  *dst_offset *= 60;
  return ZX_OK;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  // TODO(abarth): Handle time zone changes.
  static const auto* tz_name = new std::string([] {
#ifdef USE_STD_FOR_NON_NULLABLE_FIDL_FIELDS
    std::string result;
    tz->GetTimezoneId(&result);
    return result;
#else
    fidl::StringPtr result;
    tz->GetTimezoneId(&result);
    return *result;
#endif
  }());
  return tz_name->c_str();
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      seconds_since_epoch, &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset + dst_offset : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset : 0;
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentMonotonicTicks() {
  return zx_clock_get(ZX_CLOCK_MONOTONIC);
}

int64_t OS::GetCurrentMonotonicFrequency() {
  return kNanosecondsPerSecond;
}

int64_t OS::GetCurrentMonotonicMicros() {
  int64_t ticks = GetCurrentMonotonicTicks();
  ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond);
  return ticks / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentThreadCPUMicros() {
  return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond;
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_fuchsia.cc
intptr_t OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

intptr_t OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 32;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_CONF);
}

void OS::Sleep(int64_t millis) {
  SleepMicros(millis * kMicrosecondsPerMillisecond);
}

void OS::SleepMicros(int64_t micros) {
  zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond));
}

void OS::DebugBreak() {
  UNIMPLEMENTED();
}

DART_NOINLINE uintptr_t OS::GetProgramCounter() {
  return reinterpret_cast<uintptr_t>(
      __builtin_extract_return_addr(__builtin_return_address(0)));
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  Utils::VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  } else if (str[0] == '+') {
    i = 1;
  }
  if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  if (base == 16) {
    // Unsigned 64-bit hexadecimal integer literals are allowed but
    // immediately interpreted as signed 64-bit integers.
    *value = static_cast<int64_t>(strtoull(str, &endptr, base));
  } else {
    *value = strtoll(str, &endptr, base);
  }
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
#ifndef PRODUCT
  if (FLAG_generate_perf_events_symbols) {
    UNIMPLEMENTED();
  }
#endif  // !PRODUCT
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::Init() {
  auto environment_services = std::make_shared<component::Services>();
  auto env_service_root = component::subtle::CreateStaticServiceRootHandle();
  environment_services->Bind(std::move(env_service_root));
  environment_services->ConnectToService(tz.NewRequest());
}

void OS::Cleanup() {}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart

#endif  // defined(HOST_OS_FUCHSIA)
<commit_msg>[fuchsia] Clean-up after the FIDL string/vector types transition<commit_after>// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(HOST_OS_FUCHSIA)

#include "vm/os.h"

#include <errno.h>
#include <lib/fdio/util.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>

#include <fuchsia/timezone/cpp/fidl.h>

#include "lib/component/cpp/startup_context.h"
#include "lib/svc/cpp/services.h"

#include "platform/assert.h"
#include "vm/zone.h"

namespace dart {

#ifndef PRODUCT

DEFINE_FLAG(bool,
            generate_perf_events_symbols,
            false,
            "Generate events symbols for profiling with perf");

#endif  // !PRODUCT

const char* OS::Name() {
  return "fuchsia";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

// TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to
// directly get timezone.
//
// Putting this hack right now due to CP-120 as I need to remove
// component:ConnectToEnvironmentServices and this is the only thing that is
// blocking it and FL-98 will take time.
static fuchsia::timezone::TimezoneSyncPtr tz;

static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch,
                                                 int32_t* local_offset,
                                                 int32_t* dst_offset) {
  zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000,
                                                    local_offset, dst_offset);
  if (status != ZX_OK) {
    return status;
  }
  *local_offset *= 60;
  *dst_offset *= 60;
  return ZX_OK;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  // TODO(abarth): Handle time zone changes.
  static const auto* tz_name = new std::string([] {
    std::string result;
    tz->GetTimezoneId(&result);
    return result;
  }());
  return tz_name->c_str();
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      seconds_since_epoch, &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset + dst_offset : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset : 0;
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentMonotonicTicks() {
  return zx_clock_get(ZX_CLOCK_MONOTONIC);
}

int64_t OS::GetCurrentMonotonicFrequency() {
  return kNanosecondsPerSecond;
}

int64_t OS::GetCurrentMonotonicMicros() {
  int64_t ticks = GetCurrentMonotonicTicks();
  ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond);
  return ticks / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentThreadCPUMicros() {
  return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond;
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_fuchsia.cc
intptr_t OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

intptr_t OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 32;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_CONF);
}

void OS::Sleep(int64_t millis) {
  SleepMicros(millis * kMicrosecondsPerMillisecond);
}

void OS::SleepMicros(int64_t micros) {
  zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond));
}

void OS::DebugBreak() {
  UNIMPLEMENTED();
}

DART_NOINLINE uintptr_t OS::GetProgramCounter() {
  return reinterpret_cast<uintptr_t>(
      __builtin_extract_return_addr(__builtin_return_address(0)));
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  Utils::VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  } else if (str[0] == '+') {
    i = 1;
  }
  if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  if (base == 16) {
    // Unsigned 64-bit hexadecimal integer literals are allowed but
    // immediately interpreted as signed 64-bit integers.
    *value = static_cast<int64_t>(strtoull(str, &endptr, base));
  } else {
    *value = strtoll(str, &endptr, base);
  }
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
#ifndef PRODUCT
  if (FLAG_generate_perf_events_symbols) {
    UNIMPLEMENTED();
  }
#endif  // !PRODUCT
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::Init() {
  auto environment_services = std::make_shared<component::Services>();
  auto env_service_root = component::subtle::CreateStaticServiceRootHandle();
  environment_services->Bind(std::move(env_service_root));
  environment_services->ConnectToService(tz.NewRequest());
}

void OS::Cleanup() {}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart

#endif  // defined(HOST_OS_FUCHSIA)
<|endoftext|>


<commit_before>/**
 *
 *  \file example8.cc
 *  \remark This file is part of VITA.
 *  \details Building blocks run test.
 *
 *  Copyright (C) 2011-2013 EOS di Manlio Morini.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this file,
 *  You can obtain one at http://mozilla.org/MPL/2.0/
 *
 */

#include <cstdlib>
#include <iostream>
#include <fstream>

#include "adf.h"
#include "distribution.h"
#include "environment.h"
#include "interpreter.h"
#include "primitive/factory.h"

int main(int argc, char *argv[])
{
  using namespace vita;

  environment env(true);

  env.code_length = argc > 1 ? atoi(argv[1]) : 5;
  const unsigned n(argc > 2 ? atoi(argv[2]) : 1);

  symbol_factory &factory(symbol_factory::instance());
  env.insert(factory.make(d_double, -200, 200));
  env.insert(factory.make("FADD"));
  env.insert(factory.make("FSUB"));
  env.insert(factory.make("FMUL"));
  env.insert(factory.make("FIFL"));
  env.insert(factory.make("FIFE"));
  env.insert(factory.make("FABS"));
  env.insert(factory.make("FLN"));

  for (unsigned k(0); k < n; ++k)
  {
    // We build, by repeated trials, an individual with an effective size
    // greater than 4.
    individual base(env, true);
    size_t base_es(base.eff_size());
    while (base_es < 5)
    {
      base = individual(env, true);
      base_es = base.eff_size();
    }

    std::cout << std::string(40, '-') << std::endl << "BASE" << std::endl;
    base.list(std::cout);
    std::cout << std::endl;

    std::list<locus> bl(base.blocks());
    for (auto i(bl.begin()); i != bl.end(); ++i)
    {
      individual blk(base.get_block(*i));

      std::cout << std::endl << "BLOCK at locus " << *i << std::endl;
      blk.list(std::cout);
      const any val(interpreter(blk).run());
      if (val.empty())
        std::cout << "Incorrect output.";
      else
        std::cout << "Output: " << interpreter::to_string(val);
      std::cout << std::endl;

      if (blk.eff_size() <= 20)
      {
        std::vector<locus> replaced;
        individual blk2(blk.generalize(2, &replaced));

        std::vector<index_t> positions(replaced.size());
        std::vector<category_t> categories(replaced.size());
        for (size_t j(0); j < replaced.size(); ++j)
        {
          positions[j]  = replaced[j][locus_index];
          categories[j] = replaced[j][locus_category];
        }

        symbol_ptr f(new adf(blk2, categories, 100));
        env.insert(f);
        std::cout << std::endl << f->display() << std::endl;
        blk2.list(std::cout);

        individual blk3(blk.replace({{f, positions}}));
        std::cout << std::endl;
        blk3.list(std::cout);
        const any val3(interpreter(blk3).run());
        if (val3.empty())
          std::cout << "Incorrect output.";
        else
          std::cout << "Output: " << interpreter::to_string(val3);
        std::cout << std::endl << std::endl;

        if (val.empty() != val3.empty() ||
            (!val.empty() && !val3.empty() &&
             interpreter::to_string(val) != interpreter::to_string(val3)))
        {
          std::cout << "ADF EVAL ERROR." << std::endl;
          return EXIT_FAILURE;
        }
      }
      else
        std::cout << "Skipping block at line " << *i << std::endl;
    }
  }

  return EXIT_SUCCESS;
}
<commit_msg>[cleanup] example8.cc<commit_after>/**
 *
 *  \file example8.cc
 *  \remark This file is part of VITA.
 *  \details Building blocks run test.
 *
 *  Copyright (C) 2011-2013 EOS di Manlio Morini.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this file,
 *  You can obtain one at http://mozilla.org/MPL/2.0/
 *
 */

#include <cstdlib>
#include <iostream>
#include <fstream>

#include "adf.h"
#include "distribution.h"
#include "environment.h"
#include "interpreter.h"
#include "primitive/factory.h"

int main(int argc, char *argv[])
{
  using namespace vita;

  environment env(true);

  env.code_length = argc > 1 ? atoi(argv[1]) : 5;
  const unsigned n(argc > 2 ? atoi(argv[2]) : 1);

  symbol_factory &factory(symbol_factory::instance());
  env.insert(factory.make(d_double, -200, 200));
  env.insert(factory.make("FADD"));
  env.insert(factory.make("FSUB"));
  env.insert(factory.make("FMUL"));
  env.insert(factory.make("FIFL"));
  env.insert(factory.make("FIFE"));
  env.insert(factory.make("FABS"));
  env.insert(factory.make("FLN"));

  for (unsigned k(0); k < n; ++k)
  {
    // We build, by repeated trials, an individual with an effective size
    // greater than 4.
    individual base(env, true);
    size_t base_es(base.eff_size());
    while (base_es < 5)
    {
      base = individual(env, true);
      base_es = base.eff_size();
    }

    std::cout << std::string(40, '-') << std::endl << "BASE" << std::endl;
    base.list(std::cout);
    std::cout << std::endl;

    std::list<locus> bl(base.blocks());
    for (const locus &l : bl)
    {
      individual blk(base.get_block(l));

      std::cout << std::endl << "BLOCK at locus " << l << std::endl;
      blk.list(std::cout);
      const any val(interpreter(blk).run());
      if (val.empty())
        std::cout << "Empty output.";
      else
        std::cout << "Output: " << interpreter::to_string(val);
      std::cout << std::endl;

      if (blk.eff_size() <= 20)
      {
        std::vector<locus> replaced;
        individual blk2(blk.generalize(2, &replaced));

        std::vector<index_t> positions(replaced.size());
        std::vector<category_t> categories(replaced.size());
        for (size_t j(0); j < replaced.size(); ++j)
        {
          positions[j]  = replaced[j][locus_index];
          categories[j] = replaced[j][locus_category];
        }

        symbol_ptr f(std::make_shared<adf>(blk2, categories, 100));
        env.insert(f);
        std::cout << std::endl << f->display() << std::endl;
        blk2.list(std::cout);

        individual blk3(blk.replace({{f, positions}}));
        std::cout << std::endl;
        blk3.list(std::cout);
        const any val3(interpreter(blk3).run());
        if (val3.empty())
          std::cout << "Empty output.";
        else
          std::cout << "Output: " << interpreter::to_string(val3);
        std::cout << std::endl << std::endl;

        if (val.empty() != val3.empty() ||
            (!val.empty() && !val3.empty() &&
             interpreter::to_string(val) != interpreter::to_string(val3)))
        {
          std::cerr << "ADF EVAL ERROR." << std::endl;
          return EXIT_FAILURE;
        }
      }
      else
        std::cout << "Skipping block at line " << l << std::endl;
    }
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

#include "ninja.h"

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#include <memory>
#include <string>
#include <unordered_set>

#include "command.h"
#include "dep.h"
#include "eval.h"
#include "log.h"
#include "string_piece.h"
#include "stringprintf.h"
#include "strutil.h"
#include "var.h"

static StringPiece FindCommandLineFlagWithArg(StringPiece cmd,
                                              StringPiece name) {
  size_t index = cmd.find(name);
  if (index == string::npos)
    return StringPiece();

  StringPiece val = TrimLeftSpace(cmd.substr(index + name.size()));
  index = val.find(name);
  while (index != string::npos) {
    val = TrimLeftSpace(val.substr(index + name.size()));
    index = val.find(name);
  }

  index = val.find(' ');
  CHECK(index != string::npos);
  return val.substr(0, index);
}

static bool StripPrefix(StringPiece p, StringPiece* s) {
  if (!HasPrefix(*s, p))
    return false;
  *s = s->substr(p.size());
  return true;
}

static bool IsAndroidCompileCommand(StringPiece cmd) {
  if (!StripPrefix("prebuilts/", &cmd))
    return false;
  if (!StripPrefix("gcc/", &cmd) && !StripPrefix("clang/", &cmd))
    return false;

  size_t index = cmd.find(' ');
  if (index == string::npos)
    return false;
  StringPiece cc = cmd.substr(0, index);
  if (!HasSuffix(cc, "gcc") && !HasSuffix(cc, "g++") &&
      !HasSuffix(cc, "clang") && !HasSuffix(cc, "clang++")) {
    return false;
  }

  cmd = cmd.substr(index);
  return cmd.find(" -c ") != string::npos;
}

static bool GetDepfileFromCommandImpl(StringPiece cmd, string* out) {
  if (cmd.find(StringPiece(" -MD ")) == string::npos &&
      cmd.find(StringPiece(" -MMD ")) == string::npos) {
    return false;
  }

  StringPiece mf = FindCommandLineFlagWithArg(cmd, StringPiece(" -MF "));
  if (!mf.empty()) {
    mf.AppendToString(out);
    return true;
  }

  StringPiece o = FindCommandLineFlagWithArg(cmd, StringPiece(" -o "));
  if (o.empty()) {
    ERROR("Cannot find the depfile in %s", cmd.as_string().c_str());
    return false;
  }

  StripExt(o).AppendToString(out);
  *out += ".d";
  return true;
}

bool GetDepfileFromCommand(StringPiece cmd, string* out) {
  CHECK(cmd.get(cmd.size()-1) == ' ');

  if (!GetDepfileFromCommandImpl(cmd, out))
    return false;

  // A hack for Android - llvm-rs-cc seems not to emit a dep file.
  if (cmd.find("bin/llvm-rs-cc ") != string::npos) {
    return false;
  }

  // TODO: A hack for Makefiles generated by automake.

  // A hack for Android to get .P files instead of .d.
  string p;
  StripExt(*out).AppendToString(&p);
  p += ".P";
  if (cmd.find(p) != string::npos) {
    *out = p;
    return true;
  }

  // A hack for Android. For .s files, GCC does not use C
  // preprocessor, so it ignores -MF flag.
  string as = "/";
  StripExt(Basename(*out)).AppendToString(&as);
  as += ".s";
  if (cmd.find(as) != string::npos) {
    return false;
  }

  return true;
}

class NinjaGenerator {
 public:
  explicit NinjaGenerator(Evaluator* ev)
      : ce_(ev), ev_(ev), fp_(NULL), rule_id_(0) {
    ev_->set_avoid_io(true);
    if (g_goma_dir)
      gomacc_ = StringPrintf("%s/gomacc ", g_goma_dir);
  }

  ~NinjaGenerator() {
    ev_->set_avoid_io(false);
  }

  void Generate(const vector<DepNode*>& nodes) {
    GenerateShell();
    GenerateNinja(nodes);
  }

 private:
  string GenRuleName() {
    return StringPrintf("rule%d", rule_id_++);
  }

  StringPiece TranslateCommand(const char* in) {
    const size_t orig_size = cmd_buf_.size();
    bool prev_backslash = false;
    char quote = 0;
    bool done = false;
    for (; *in && !done; in++) {
      switch (*in) {
        case '#':
          if (quote == 0 && !prev_backslash) {
            done = true;
            break;
          }

        case '\'':
        case '"':
        case '`':
          if (quote) {
            if (quote == *in)
              quote = 0;
          } else if (!prev_backslash) {
            quote = *in;
          }
          cmd_buf_ += *in;
          break;

        case '$':
          cmd_buf_ += "$$";
          break;

        case '\t':
          cmd_buf_ += ' ';
          break;

        case '\n':
          if (prev_backslash) {
            cmd_buf_[cmd_buf_.size()-1] = ' ';
          } else {
            cmd_buf_ += ' ';
          }
          break;

        case '\\':
          prev_backslash = !prev_backslash;
          cmd_buf_ += '\\';
          break;

        default:
          cmd_buf_ += *in;
          prev_backslash = false;
      }
    }

    while (true) {
      char c = cmd_buf_[cmd_buf_.size()-1];
      if (!isspace(c) && c != ';')
        break;
      cmd_buf_.resize(cmd_buf_.size() - 1);
    }

    return StringPiece(cmd_buf_.data() + orig_size,
                       cmd_buf_.size() - orig_size);
  }

  bool GenShellScript(const vector<Command*>& commands) {
    bool use_gomacc = false;
    bool should_ignore_error = false;
    cmd_buf_.clear();
    for (const Command* c : commands) {
      if (!cmd_buf_.empty()) {
        if (should_ignore_error) {
          cmd_buf_ += " ; ";
        } else {
          cmd_buf_ += " && ";
        }
      }
      should_ignore_error = c->ignore_error;

      const char* in = c->cmd->c_str();
      while (isspace(*in))
        in++;

      bool needs_subshell = commands.size() > 1;
      if (*in == '(') {
        needs_subshell = false;
      }

      if (needs_subshell)
        cmd_buf_ += '(';

      size_t cmd_start = cmd_buf_.size();
      StringPiece translated = TranslateCommand(in);
      if (translated.empty()) {
        cmd_buf_ += "true";
      } else if (g_goma_dir && IsAndroidCompileCommand(translated)) {
        cmd_buf_.insert(cmd_start, gomacc_);
        use_gomacc = true;
      }

      if (c == commands.back() && c->ignore_error) {
        cmd_buf_ += " ; true";
      }

      if (needs_subshell)
        cmd_buf_ += ')';
    }
    return g_goma_dir && !use_gomacc;
  }

  void EmitDepfile() {
    cmd_buf_ += ' ';
    string depfile;
    bool result = GetDepfileFromCommand(cmd_buf_, &depfile);
    cmd_buf_.resize(cmd_buf_.size()-1);
    if (!result)
      return;
    fprintf(fp_, " depfile = %s\n", depfile.c_str());
  }

  void EmitNode(DepNode* node) {
    auto p = done_.insert(node->output);
    if (!p.second)
      return;

    if (node->cmds.empty() && node->deps.empty() && !node->is_phony)
      return;

    vector<Command*> commands;
    ce_.Eval(node, &commands);

    string rule_name = "phony";
    bool use_local_pool = false;
    if (!commands.empty()) {
      rule_name = GenRuleName();
      fprintf(fp_, "rule %s\n", rule_name.c_str());
      fprintf(fp_, " description = build $out\n");

      use_local_pool |= GenShellScript(commands);
      EmitDepfile();

      // It seems Linux is OK with ~130kB.
      // TODO: Find this number automatically.
      if (cmd_buf_.size() > 100 * 1000) {
        fprintf(fp_, " rspfile = $out.rsp\n");
        fprintf(fp_, " rspfile_content = %s\n", cmd_buf_.c_str());
        fprintf(fp_, " command = sh $out.rsp\n");
      } else {
        fprintf(fp_, " command = %s\n", cmd_buf_.c_str());
      }
    }

    EmitBuild(node, rule_name);
    if (use_local_pool)
      fprintf(fp_, " pool = local_pool\n");

    for (DepNode* d : node->deps) {
      EmitNode(d);
    }
  }

  void EmitBuild(DepNode* node, const string& rule_name) {
    fprintf(fp_, "build %s: %s", node->output.c_str(), rule_name.c_str());
    vector<Symbol> order_onlys;
    for (DepNode* d : node->deps) {
      fprintf(fp_, " %s", d->output.c_str());
    }
    if (!node->order_onlys.empty()) {
      fprintf(fp_, " ||");
      for (DepNode* d : node->order_onlys) {
        fprintf(fp_, " %s", d->output.c_str());
      }
    }
    fprintf(fp_, "\n");
  }

  void GenerateNinja(const vector<DepNode*>& nodes) {
    fp_ = fopen("build.ninja", "wb");
    if (fp_ == NULL)
      PERROR("fopen(build.ninja) failed");

    fprintf(fp_, "# Generated by kati\n");
    fprintf(fp_, "\n");

    if (g_goma_dir) {
      fprintf(fp_, "pool local_pool\n");
      // TODO: Decide the appropriate number based on the number of cores.
      fprintf(fp_, " depth = %d\n", 32);
    }

    for (DepNode* node : nodes) {
      EmitNode(node);
    }

    fclose(fp_);
  }

  void GenerateShell() {
    FILE* fp = fopen("ninja.sh", "wb");
    if (fp == NULL)
      PERROR("fopen(ninja.sh) failed");

    shared_ptr<string> shell = ev_->EvalVar(kShellSym);
    if (shell->empty())
      shell = make_shared<string>("/bin/sh");
    fprintf(fp, "#!%s\n", shell->c_str());

    for (const auto& p : ev_->exports()) {
      if (p.second) {
        shared_ptr<string> val = ev_->EvalVar(p.first);
        fprintf(fp, "export %s=%s\n", p.first.c_str(), val->c_str());
      } else {
        fprintf(fp, "unset %s\n", p.first.c_str());
      }
    }

    if (g_goma_dir) {
      fprintf(fp, "exec ninja -j300 \"$@\"\n");
    } else {
      fprintf(fp, "exec ninja \"$@\"\n");
    }

    if (chmod("ninja.sh", 0755) != 0)
      PERROR("chmod ninja.sh failed");
  }

  CommandEvaluator ce_;
  Evaluator* ev_;
  FILE* fp_;
  unordered_set<Symbol> done_;
  int rule_id_;
  string cmd_buf_;
  string gomacc_;
};

void GenerateNinja(const vector<DepNode*>& nodes, Evaluator* ev) {
  NinjaGenerator ng(ev);
  ng.Generate(nodes);
}
<commit_msg>[C++] Emit nodes referenced as order-only<commit_after>// Copyright 2015 Google Inc. All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

#include "ninja.h"

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#include <memory>
#include <string>
#include <unordered_set>

#include "command.h"
#include "dep.h"
#include "eval.h"
#include "log.h"
#include "string_piece.h"
#include "stringprintf.h"
#include "strutil.h"
#include "var.h"

static StringPiece FindCommandLineFlagWithArg(StringPiece cmd,
                                              StringPiece name) {
  size_t index = cmd.find(name);
  if (index == string::npos)
    return StringPiece();

  StringPiece val = TrimLeftSpace(cmd.substr(index + name.size()));
  index = val.find(name);
  while (index != string::npos) {
    val = TrimLeftSpace(val.substr(index + name.size()));
    index = val.find(name);
  }

  index = val.find(' ');
  CHECK(index != string::npos);
  return val.substr(0, index);
}

static bool StripPrefix(StringPiece p, StringPiece* s) {
  if (!HasPrefix(*s, p))
    return false;
  *s = s->substr(p.size());
  return true;
}

static bool IsAndroidCompileCommand(StringPiece cmd) {
  if (!StripPrefix("prebuilts/", &cmd))
    return false;
  if (!StripPrefix("gcc/", &cmd) && !StripPrefix("clang/", &cmd))
    return false;

  size_t index = cmd.find(' ');
  if (index == string::npos)
    return false;
  StringPiece cc = cmd.substr(0, index);
  if (!HasSuffix(cc, "gcc") && !HasSuffix(cc, "g++") &&
      !HasSuffix(cc, "clang") && !HasSuffix(cc, "clang++")) {
    return false;
  }

  cmd = cmd.substr(index);
  return cmd.find(" -c ") != string::npos;
}

static bool GetDepfileFromCommandImpl(StringPiece cmd, string* out) {
  if (cmd.find(StringPiece(" -MD ")) == string::npos &&
      cmd.find(StringPiece(" -MMD ")) == string::npos) {
    return false;
  }

  StringPiece mf = FindCommandLineFlagWithArg(cmd, StringPiece(" -MF "));
  if (!mf.empty()) {
    mf.AppendToString(out);
    return true;
  }

  StringPiece o = FindCommandLineFlagWithArg(cmd, StringPiece(" -o "));
  if (o.empty()) {
    ERROR("Cannot find the depfile in %s", cmd.as_string().c_str());
    return false;
  }

  StripExt(o).AppendToString(out);
  *out += ".d";
  return true;
}

bool GetDepfileFromCommand(StringPiece cmd, string* out) {
  CHECK(cmd.get(cmd.size()-1) == ' ');

  if (!GetDepfileFromCommandImpl(cmd, out))
    return false;

  // A hack for Android - llvm-rs-cc seems not to emit a dep file.
  if (cmd.find("bin/llvm-rs-cc ") != string::npos) {
    return false;
  }

  // TODO: A hack for Makefiles generated by automake.

  // A hack for Android to get .P files instead of .d.
  string p;
  StripExt(*out).AppendToString(&p);
  p += ".P";
  if (cmd.find(p) != string::npos) {
    *out = p;
    return true;
  }

  // A hack for Android. For .s files, GCC does not use C
  // preprocessor, so it ignores -MF flag.
  string as = "/";
  StripExt(Basename(*out)).AppendToString(&as);
  as += ".s";
  if (cmd.find(as) != string::npos) {
    return false;
  }

  return true;
}

class NinjaGenerator {
 public:
  explicit NinjaGenerator(Evaluator* ev)
      : ce_(ev), ev_(ev), fp_(NULL), rule_id_(0) {
    ev_->set_avoid_io(true);
    if (g_goma_dir)
      gomacc_ = StringPrintf("%s/gomacc ", g_goma_dir);
  }

  ~NinjaGenerator() {
    ev_->set_avoid_io(false);
  }

  void Generate(const vector<DepNode*>& nodes) {
    GenerateShell();
    GenerateNinja(nodes);
  }

 private:
  string GenRuleName() {
    return StringPrintf("rule%d", rule_id_++);
  }

  StringPiece TranslateCommand(const char* in) {
    const size_t orig_size = cmd_buf_.size();
    bool prev_backslash = false;
    char quote = 0;
    bool done = false;
    for (; *in && !done; in++) {
      switch (*in) {
        case '#':
          if (quote == 0 && !prev_backslash) {
            done = true;
            break;
          }

        case '\'':
        case '"':
        case '`':
          if (quote) {
            if (quote == *in)
              quote = 0;
          } else if (!prev_backslash) {
            quote = *in;
          }
          cmd_buf_ += *in;
          break;

        case '$':
          cmd_buf_ += "$$";
          break;

        case '\t':
          cmd_buf_ += ' ';
          break;

        case '\n':
          if (prev_backslash) {
            cmd_buf_[cmd_buf_.size()-1] = ' ';
          } else {
            cmd_buf_ += ' ';
          }
          break;

        case '\\':
          prev_backslash = !prev_backslash;
          cmd_buf_ += '\\';
          break;

        default:
          cmd_buf_ += *in;
          prev_backslash = false;
      }
    }

    while (true) {
      char c = cmd_buf_[cmd_buf_.size()-1];
      if (!isspace(c) && c != ';')
        break;
      cmd_buf_.resize(cmd_buf_.size() - 1);
    }

    return StringPiece(cmd_buf_.data() + orig_size,
                       cmd_buf_.size() - orig_size);
  }

  bool GenShellScript(const vector<Command*>& commands) {
    bool use_gomacc = false;
    bool should_ignore_error = false;
    cmd_buf_.clear();
    for (const Command* c : commands) {
      if (!cmd_buf_.empty()) {
        if (should_ignore_error) {
          cmd_buf_ += " ; ";
        } else {
          cmd_buf_ += " && ";
        }
      }
      should_ignore_error = c->ignore_error;

      const char* in = c->cmd->c_str();
      while (isspace(*in))
        in++;

      bool needs_subshell = commands.size() > 1;
      if (*in == '(') {
        needs_subshell = false;
      }

      if (needs_subshell)
        cmd_buf_ += '(';

      size_t cmd_start = cmd_buf_.size();
      StringPiece translated = TranslateCommand(in);
      if (translated.empty()) {
        cmd_buf_ += "true";
      } else if (g_goma_dir && IsAndroidCompileCommand(translated)) {
        cmd_buf_.insert(cmd_start, gomacc_);
        use_gomacc = true;
      }

      if (c == commands.back() && c->ignore_error) {
        cmd_buf_ += " ; true";
      }

      if (needs_subshell)
        cmd_buf_ += ')';
    }
    return g_goma_dir && !use_gomacc;
  }

  void EmitDepfile() {
    cmd_buf_ += ' ';
    string depfile;
    bool result = GetDepfileFromCommand(cmd_buf_, &depfile);
    cmd_buf_.resize(cmd_buf_.size()-1);
    if (!result)
      return;
    fprintf(fp_, " depfile = %s\n", depfile.c_str());
  }

  void EmitNode(DepNode* node) {
    auto p = done_.insert(node->output);
    if (!p.second)
      return;

    if (node->cmds.empty() && node->deps.empty() && !node->is_phony)
      return;

    vector<Command*> commands;
    ce_.Eval(node, &commands);

    string rule_name = "phony";
    bool use_local_pool = false;
    if (!commands.empty()) {
      rule_name = GenRuleName();
      fprintf(fp_, "rule %s\n", rule_name.c_str());
      fprintf(fp_, " description = build $out\n");

      use_local_pool |= GenShellScript(commands);
      EmitDepfile();

      // It seems Linux is OK with ~130kB.
      // TODO: Find this number automatically.
      if (cmd_buf_.size() > 100 * 1000) {
        fprintf(fp_, " rspfile = $out.rsp\n");
        fprintf(fp_, " rspfile_content = %s\n", cmd_buf_.c_str());
        fprintf(fp_, " command = sh $out.rsp\n");
      } else {
        fprintf(fp_, " command = %s\n", cmd_buf_.c_str());
      }
    }

    EmitBuild(node, rule_name);
    if (use_local_pool)
      fprintf(fp_, " pool = local_pool\n");

    for (DepNode* d : node->deps) {
      EmitNode(d);
    }
    for (DepNode* d : node->order_onlys) {
      EmitNode(d);
    }
  }

  void EmitBuild(DepNode* node, const string& rule_name) {
    fprintf(fp_, "build %s: %s", node->output.c_str(), rule_name.c_str());
    vector<Symbol> order_onlys;
    for (DepNode* d : node->deps) {
      fprintf(fp_, " %s", d->output.c_str());
    }
    if (!node->order_onlys.empty()) {
      fprintf(fp_, " ||");
      for (DepNode* d : node->order_onlys) {
        fprintf(fp_, " %s", d->output.c_str());
      }
    }
    fprintf(fp_, "\n");
  }

  void GenerateNinja(const vector<DepNode*>& nodes) {
    fp_ = fopen("build.ninja", "wb");
    if (fp_ == NULL)
      PERROR("fopen(build.ninja) failed");

    fprintf(fp_, "# Generated by kati\n");
    fprintf(fp_, "\n");

    if (g_goma_dir) {
      fprintf(fp_, "pool local_pool\n");
      // TODO: Decide the appropriate number based on the number of cores.
      fprintf(fp_, " depth = %d\n", 32);
    }

    for (DepNode* node : nodes) {
      EmitNode(node);
    }

    fclose(fp_);
  }

  void GenerateShell() {
    FILE* fp = fopen("ninja.sh", "wb");
    if (fp == NULL)
      PERROR("fopen(ninja.sh) failed");

    shared_ptr<string> shell = ev_->EvalVar(kShellSym);
    if (shell->empty())
      shell = make_shared<string>("/bin/sh");
    fprintf(fp, "#!%s\n", shell->c_str());

    for (const auto& p : ev_->exports()) {
      if (p.second) {
        shared_ptr<string> val = ev_->EvalVar(p.first);
        fprintf(fp, "export %s=%s\n", p.first.c_str(), val->c_str());
      } else {
        fprintf(fp, "unset %s\n", p.first.c_str());
      }
    }

    if (g_goma_dir) {
      fprintf(fp, "exec ninja -j300 \"$@\"\n");
    } else {
      fprintf(fp, "exec ninja \"$@\"\n");
    }

    if (chmod("ninja.sh", 0755) != 0)
      PERROR("chmod ninja.sh failed");
  }

  CommandEvaluator ce_;
  Evaluator* ev_;
  FILE* fp_;
  unordered_set<Symbol> done_;
  int rule_id_;
  string cmd_buf_;
  string gomacc_;
};

void GenerateNinja(const vector<DepNode*>& nodes, Evaluator* ev) {
  NinjaGenerator ng(ev);
  ng.Generate(nodes);
}
<|endoftext|>


<commit_before>// Copyright 2010 The RE2 Authors.  All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "re2/set.h"

#include <stddef.h>
#include <algorithm>
#include <memory>

#include "util/util.h"
#include "util/logging.h"
#include "re2/pod_array.h"
#include "re2/prog.h"
#include "re2/re2.h"
#include "re2/regexp.h"
#include "re2/stringpiece.h"

namespace re2 {

RE2::Set::Set(const RE2::Options& options, RE2::Anchor anchor) {
  options_.Copy(options);
  options_.set_never_capture(true);  // might unblock some optimisations
  anchor_ = anchor;
  prog_ = NULL;
  compiled_ = false;
  size_ = 0;
}

RE2::Set::~Set() {
  for (size_t i = 0; i < elem_.size(); i++)
    elem_[i].second->Decref();
  delete prog_;
}

int RE2::Set::Add(const StringPiece& pattern, std::string* error) {
  if (compiled_) {
    LOG(DFATAL) << "RE2::Set::Add() called after compiling";
    return -1;
  }

  Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>(
    options_.ParseFlags());
  RegexpStatus status;
  re2::Regexp* re = Regexp::Parse(pattern, pf, &status);
  if (re == NULL) {
    if (error != NULL)
      *error = status.Text();
    if (options_.log_errors())
      LOG(ERROR) << "Error parsing '" << pattern << "': " << status.Text();
    return -1;
  }

  // Concatenate with match index and push on vector.
  int n = static_cast<int>(elem_.size());
  re2::Regexp* m = re2::Regexp::HaveMatch(n, pf);
  if (re->op() == kRegexpConcat) {
    int nsub = re->nsub();
    PODArray<re2::Regexp*> sub(nsub + 1);
    for (int i = 0; i < nsub; i++)
      sub[i] = re->sub()[i]->Incref();
    sub[nsub] = m;
    re->Decref();
    re = re2::Regexp::Concat(sub.data(), nsub + 1, pf);
  } else {
    re2::Regexp* sub[2];
    sub[0] = re;
    sub[1] = m;
    re = re2::Regexp::Concat(sub, 2, pf);
  }
  elem_.emplace_back(std::string(pattern), re);
  return n;
}

bool RE2::Set::Compile() {
  if (compiled_) {
    LOG(DFATAL) << "RE2::Set::Compile() called more than once";
    return false;
  }
  compiled_ = true;
  size_ = static_cast<int>(elem_.size());

  // Sort the elements by their patterns. This is good enough for now
  // until we have a Regexp comparison function. (Maybe someday...)
  std::sort(elem_.begin(), elem_.end(),
            [](const Elem& a, const Elem& b) -> bool {
              return a.first < b.first;
            });

  PODArray<re2::Regexp*> sub(size_);
  for (int i = 0; i < size_; i++)
    sub[i] = elem_[i].second;
  elem_.clear();
  elem_.shrink_to_fit();

  Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>(
    options_.ParseFlags());
  re2::Regexp* re = re2::Regexp::Alternate(sub.data(), size_, pf);

  prog_ = Prog::CompileSet(re, anchor_, options_.max_mem());
  re->Decref();
  return prog_ != NULL;
}

bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v) const {
  return Match(text, v, NULL);
}

bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v,
                     ErrorInfo* error_info) const {
  if (!compiled_) {
    LOG(DFATAL) << "RE2::Set::Match() called before compiling";
    if (error_info != NULL)
      error_info->kind = kNotCompiled;
    return false;
  }
  bool dfa_failed = false;
  std::unique_ptr<SparseSet> matches;
  if (v != NULL) {
    matches.reset(new SparseSet(size_));
    v->clear();
  }
  bool ret = prog_->SearchDFA(text, text, Prog::kAnchored, Prog::kManyMatch,
                              NULL, &dfa_failed, matches.get());
  if (dfa_failed) {
    if (options_.log_errors())
      LOG(ERROR) << "DFA out of memory: "
                 << "program size " << prog->size() << ", "
                 << "list count " << prog->list_count() << ", "
                 << "bytemap range " << prog->bytemap_range();
    if (error_info != NULL)
      error_info->kind = kOutOfMemory;
    return false;
  }
  if (ret == false) {
    if (error_info != NULL)
      error_info->kind = kNoError;
    return false;
  }
  if (v != NULL) {
    if (matches->empty()) {
      LOG(DFATAL) << "RE2::Set::Match() matched, but no matches returned?!";
      if (error_info != NULL)
        error_info->kind = kInconsistent;
      return false;
    }
    v->assign(matches->begin(), matches->end());
  }
  if (error_info != NULL)
    error_info->kind = kNoError;
  return true;
}

}  // namespace re2
<commit_msg>Aiieee. Add a missing underscore.<commit_after>// Copyright 2010 The RE2 Authors.  All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "re2/set.h"

#include <stddef.h>
#include <algorithm>
#include <memory>

#include "util/util.h"
#include "util/logging.h"
#include "re2/pod_array.h"
#include "re2/prog.h"
#include "re2/re2.h"
#include "re2/regexp.h"
#include "re2/stringpiece.h"

namespace re2 {

RE2::Set::Set(const RE2::Options& options, RE2::Anchor anchor) {
  options_.Copy(options);
  options_.set_never_capture(true);  // might unblock some optimisations
  anchor_ = anchor;
  prog_ = NULL;
  compiled_ = false;
  size_ = 0;
}

RE2::Set::~Set() {
  for (size_t i = 0; i < elem_.size(); i++)
    elem_[i].second->Decref();
  delete prog_;
}

int RE2::Set::Add(const StringPiece& pattern, std::string* error) {
  if (compiled_) {
    LOG(DFATAL) << "RE2::Set::Add() called after compiling";
    return -1;
  }

  Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>(
    options_.ParseFlags());
  RegexpStatus status;
  re2::Regexp* re = Regexp::Parse(pattern, pf, &status);
  if (re == NULL) {
    if (error != NULL)
      *error = status.Text();
    if (options_.log_errors())
      LOG(ERROR) << "Error parsing '" << pattern << "': " << status.Text();
    return -1;
  }

  // Concatenate with match index and push on vector.
  int n = static_cast<int>(elem_.size());
  re2::Regexp* m = re2::Regexp::HaveMatch(n, pf);
  if (re->op() == kRegexpConcat) {
    int nsub = re->nsub();
    PODArray<re2::Regexp*> sub(nsub + 1);
    for (int i = 0; i < nsub; i++)
      sub[i] = re->sub()[i]->Incref();
    sub[nsub] = m;
    re->Decref();
    re = re2::Regexp::Concat(sub.data(), nsub + 1, pf);
  } else {
    re2::Regexp* sub[2];
    sub[0] = re;
    sub[1] = m;
    re = re2::Regexp::Concat(sub, 2, pf);
  }
  elem_.emplace_back(std::string(pattern), re);
  return n;
}

bool RE2::Set::Compile() {
  if (compiled_) {
    LOG(DFATAL) << "RE2::Set::Compile() called more than once";
    return false;
  }
  compiled_ = true;
  size_ = static_cast<int>(elem_.size());

  // Sort the elements by their patterns. This is good enough for now
  // until we have a Regexp comparison function. (Maybe someday...)
  std::sort(elem_.begin(), elem_.end(),
            [](const Elem& a, const Elem& b) -> bool {
              return a.first < b.first;
            });

  PODArray<re2::Regexp*> sub(size_);
  for (int i = 0; i < size_; i++)
    sub[i] = elem_[i].second;
  elem_.clear();
  elem_.shrink_to_fit();

  Regexp::ParseFlags pf = static_cast<Regexp::ParseFlags>(
    options_.ParseFlags());
  re2::Regexp* re = re2::Regexp::Alternate(sub.data(), size_, pf);

  prog_ = Prog::CompileSet(re, anchor_, options_.max_mem());
  re->Decref();
  return prog_ != NULL;
}

bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v) const {
  return Match(text, v, NULL);
}

bool RE2::Set::Match(const StringPiece& text, std::vector<int>* v,
                     ErrorInfo* error_info) const {
  if (!compiled_) {
    LOG(DFATAL) << "RE2::Set::Match() called before compiling";
    if (error_info != NULL)
      error_info->kind = kNotCompiled;
    return false;
  }
  bool dfa_failed = false;
  std::unique_ptr<SparseSet> matches;
  if (v != NULL) {
    matches.reset(new SparseSet(size_));
    v->clear();
  }
  bool ret = prog_->SearchDFA(text, text, Prog::kAnchored, Prog::kManyMatch,
                              NULL, &dfa_failed, matches.get());
  if (dfa_failed) {
    if (options_.log_errors())
      LOG(ERROR) << "DFA out of memory: "
                 << "program size " << prog_->size() << ", "
                 << "list count " << prog_->list_count() << ", "
                 << "bytemap range " << prog_->bytemap_range();
    if (error_info != NULL)
      error_info->kind = kOutOfMemory;
    return false;
  }
  if (ret == false) {
    if (error_info != NULL)
      error_info->kind = kNoError;
    return false;
  }
  if (v != NULL) {
    if (matches->empty()) {
      LOG(DFATAL) << "RE2::Set::Match() matched, but no matches returned?!";
      if (error_info != NULL)
        error_info->kind = kInconsistent;
      return false;
    }
    v->assign(matches->begin(), matches->end());
  }
  if (error_info != NULL)
    error_info->kind = kNoError;
  return true;
}

}  // namespace re2
<|endoftext|>


<commit_before>/*
    silence.cpp  -  LV2 Toolkit API Demonstration Plugin

    Copyright (C) 2012  Michael Fisher <mfisher31@gmail.com>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of
    the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/
/**
   @file silence.cpp
   Demonstrates LV2 URID mapping, Log, and State Save/Restore
 */

#include <iostream>
#include <vector>
#include <cstdlib>

#include <lvtk/plugin.hpp>

#include "silence.h"

using namespace lvtk;
using std::vector;

#define LVTK_SILENCE_URI "http://lvtoolkit.org/plugins/silence"
#define LVTK_SILENCE_PREFIX LVTK_SILENCE_URI "#"
#define LVTK_SILENCE_MSG LVTK_SILENCE_PREFIX "msg"

class Silence : public Plugin<Silence, URID<true>, State<true> >
{
public:

    Silence (double rate)
    : Plugin<Silence, URID<true>, State<true> > (1)
      {
        urids.atom_String = map (LV2_ATOM__String);
        urids.silence_msg = map (LVTK_SILENCE_MSG);
        urids.midi_type   = map (LV2_MIDI__MidiEvent);
      }

    void
    run(uint32_t nframes)
    {
        float *out = p(0);

        check_midi();

        for (int i = 0; i < nframes; i++)
        {
            out[i] = 0.0f;
        }
    }

    StateStatus
    save (StateStore &store, uint32_t flags, const FeatureVec &features)
    {
        const char* msg = "Sorry I can't hear you. Please speak up";

        return store (urids.silence_msg, (void*)msg,
                strlen(msg), urids.atom_String,
                STATE_IS_POD | STATE_IS_PORTABLE);
    }

    StateStatus
    restore (StateRetrieve &retrieve, uint32_t flags, const FeatureVec &features)
    {
        size_t size;
        uint32_t type,fs;

        const void *message = retrieve (urids.silence_msg, &size, &type, &fs);
        if (message)
        {
            std::cout << "[silence] " << (char*)message << std::endl;
            return STATE_SUCCESS;
        }

        return STATE_ERR_UNKNOWN;
    }

private:

    void
    check_midi ()
    {
        const LV2_Atom_Sequence* midiseq = p<LV2_Atom_Sequence> (p_midi);
        LV2_ATOM_SEQUENCE_FOREACH(midiseq, ev)
        {
            uint32_t frame_offset = ev->time.frames;
            if (ev->body.type == urids.midi_type)
            {
                std::cout << "MIDI\n";
            }
        }
    }

    struct SilenceURIs {
        LV2_URID atom_String;
        LV2_URID silence_msg;
        LV2_URID midi_type;
    } urids;

};

static int _ = Silence::register_class (LVTK_SILENCE_URI);
<commit_msg>Code style<commit_after>/*
    silence.cpp  -  LV2 Toolkit API Demonstration Plugin

    Copyright (C) 2012  Michael Fisher <mfisher31@gmail.com>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of
    the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/
/**
   @file silence.cpp
   Demonstrates LV2 URID mapping, Log, and State Save/Restore
 */

#include <iostream>
#include <vector>
#include <cstdlib>

#include <lvtk/plugin.hpp>

#include "silence.h"

using namespace lvtk;
using std::vector;

#define LVTK_SILENCE_URI "http://lvtoolkit.org/plugins/silence"
#define LVTK_SILENCE_PREFIX LVTK_SILENCE_URI "#"
#define LVTK_SILENCE_MSG LVTK_SILENCE_PREFIX "msg"

class Silence : public Plugin<Silence, URID<true>, State<true> >
{
public:

    Silence (double rate)
        : Plugin<Silence, URID<true>, State<true> > (1)
    {
        urids.atom_String = map (LV2_ATOM__String);
        urids.silence_msg = map (LVTK_SILENCE_MSG);
        urids.midi_type   = map (LV2_MIDI__MidiEvent);
    }

    void
    run(uint32_t nframes)
    {
        float *out = p(0);

        check_midi();

        for (int i = 0; i < nframes; i++)
        {
            out[i] = 0.0f;
        }
    }

    StateStatus
    save (StateStore &store, uint32_t flags, const FeatureVec &features)
    {
        const char* msg = "Sorry I can't hear you. Please speak up";

        return store (urids.silence_msg, (void*)msg,
                strlen(msg), urids.atom_String,
                STATE_IS_POD | STATE_IS_PORTABLE);
    }

    StateStatus
    restore (StateRetrieve &retrieve, uint32_t flags, const FeatureVec &features)
    {
        size_t size;
        uint32_t type,fs;

        const void *message = retrieve (urids.silence_msg, &size, &type, &fs);
        if (message)
        {
            std::cout << "[silence] " << (char*)message << std::endl;
            return STATE_SUCCESS;
        }

        return STATE_ERR_UNKNOWN;
    }

private:

    void
    check_midi ()
    {
        const LV2_Atom_Sequence* midiseq = p<LV2_Atom_Sequence> (p_midi);
        LV2_ATOM_SEQUENCE_FOREACH(midiseq, ev)
        {
            uint32_t frame_offset = ev->time.frames;
            if (ev->body.type == urids.midi_type)
            {
                std::cout << "MIDI\n";
            }
        }
    }

    struct SilenceURIs {
        LV2_URID atom_String;
        LV2_URID silence_msg;
        LV2_URID midi_type;
    } urids;

};

static int _ = Silence::register_class (LVTK_SILENCE_URI);
<|endoftext|>


<commit_before>#include <Patcher/Maj.hpp>

#include <QObject>
#include <QUrl>
#include <QFile>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>

#include <QEventLoop>

namespace patcher
{

    Maj::Maj(Config& conf,int action,std::string filename,std::string url): action(action), filename(filename), url(url),config(conf), done(false)
    {
    }

    bool Maj::apply()
    {
        bool ok = true;
        switch(action)
        {
            case 1: //new
            {
                ok = download();
                if (ok)
                    write();
            }break;
            case 2: //maj
            {
                ok = replace();
            }break;
            case 3: //delete
            {
                ok = erase();
            }break;
            default: //unknow
            {
                ok = false;
            }break;
        }
        done = ok;
        return ok;
    }

    bool Maj::download()
    {
        std::cout<<"[patcher] download file \""<<filename<<"\" from "<<url<<" "<<std::flush;

        QUrl base_url(config.getUrl().c_str());
        QUrl relative_url(url.c_str());
        QUrl url =  base_url.resolved(relative_url);

        QNetworkRequest request;
        request.setUrl(url);

        QNetworkAccessManager networkManager;
        QNetworkReply* reply = networkManager.get(request);

        QEventLoop loop;
        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        //open file
        QFile localFile(("download/"+filename).c_str());
        if (!localFile.open(QIODevice::WriteOnly))
        {
            std::cout<<"Failed"<<std::endl;
            return false;
        }
        //write in it
        localFile.write(reply->readAll());
        localFile.close();
        delete reply;

        std::cout<<"Ok"<<std::endl;
        return true;
    }

    bool Maj::erase()
    {
        bool ok = true;
        return ok;
    }

    bool Maj::replace()
    {
        bool ok = download();
        if(ok)
        {
            erase();
            ok = write();
        }
        return ok;
    }

    bool Maj::write()
    {
        bool ok = true;
        return ok;
    }

    std::ostream& operator<<(std::ostream& output,const Maj& self)
    {
        output<<"{action:"<<self.action
            <<",\nfilename:"<<self.filename
            <<",\nurl:"<<self.url
            <<",\ndone:"<<self.done
            <<"}";
        return output;
    }
}
<commit_msg>add exe right on exe<commit_after>#include <Patcher/Maj.hpp>

#include <QObject>
#include <QUrl>
#include <QFile>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>

#include <QEventLoop>

#include <stdio.h>

namespace patcher
{

    Maj::Maj(Config& conf,int action,std::string filename,std::string url): action(action), filename(filename), url(url),config(conf), done(false)
    {
    }

    bool Maj::apply()
    {
        bool ok = true;
        switch(action)
        {
            case 1: //new
            {
                ok = download();
                if (ok)
                    write();
            }break;
            case 2: //maj
            {
                ok = replace();
            }break;
            case 3: //delete
            {
                ok = erase();
            }break;
            default: //unknow
            {
                ok = false;
            }break;
        }
        done = ok;
        return ok;
    }

    bool Maj::download()
    {
        std::cout<<"[patcher] download file \""<<filename<<"\" from "<<url<<" "<<std::flush;

        QUrl base_url(config.getUrl().c_str());
        QUrl relative_url(url.c_str());
        QUrl url =  base_url.resolved(relative_url);

        QNetworkRequest request;
        request.setUrl(url);

        QNetworkAccessManager networkManager;
        QNetworkReply* reply = networkManager.get(request);

        QEventLoop loop;
        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        //open file
        QFile localFile(("download/"+filename).c_str());
        if (!localFile.open(QIODevice::WriteOnly))
        {
            std::cout<<"Failed"<<std::endl;
            return false;
        }
        //write in it
        localFile.write(reply->readAll());
        localFile.close();
        delete reply;

        std::cout<<"Ok"<<std::endl;
        return true;
    }

    bool Maj::erase()
    {
        return QFile::remove(filename.c_str());
    }

    bool Maj::replace()
    {
        bool ok = download();
        if(ok)
        {
            erase();
            ok = write();
        }
        return ok;
    }

    bool Maj::write()
    {
        bool ok = ::rename(("download/"+filename).c_str(),filename.c_str()) == 0;
        if (filename == Config::softname)
            QFile::setPermissions(filename.c_str(),
                                  QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner
                                  |QFile::ReadGroup|QFile::ExeGroup
                                  |QFile::ReadOther|QFile::ExeOther
                                  );
        return ok;
    }

    std::ostream& operator<<(std::ostream& output,const Maj& self)
    {
        output<<"{action:"<<self.action
            <<",\nfilename:"<<self.filename
            <<",\nurl:"<<self.url
            <<",\ndone:"<<self.done
            <<"}";
        return output;
    }
}
<|endoftext|>