hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
12e10725a43323eb33c9dc7992a4ac8b08d177f1
38,093
hh
C++
src/systemc/ext/dt/bit/sc_proxy.hh
mingbai/hybrid-gem5
1e0e559d6f15e6597082b387191926148d6ff4f0
[ "BSD-3-Clause" ]
2
2020-10-18T07:40:21.000Z
2020-10-18T07:48:26.000Z
src/systemc/ext/dt/bit/sc_proxy.hh
isaacyhe/gem5
f54c0929883254eaface4e516b62a80c098b411f
[ "BSD-3-Clause" ]
null
null
null
src/systemc/ext/dt/bit/sc_proxy.hh
isaacyhe/gem5
f54c0929883254eaface4e516b62a80c098b411f
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** sc_proxy.h -- Proxy base class for vector data types. This class is created for several purposes: 1) hiding operators from the global namespace that would be otherwise found by Koenig lookup 2) avoiding repeating the same operations in every class including proxies that could also be achieved by common base class, but this method allows 3) improve performance by using non-virtual functions Original Author: Gene Bushuyev, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // $Log: sc_proxy.h,v $ // Revision 1.3 2010/12/07 20:09:07 acg // Andy Goodrich: Fix for returning enough data // // Revision 1.2 2009/02/28 00:26:14 acg // Andy Goodrich: bug fixes. // // Revision 1.1.1.1 2006/12/15 20:31:36 acg // SystemC 2.2 // // Revision 1.3 2006/01/13 18:53:53 acg // Andy Goodrich: added $Log command so that CVS comments are reproduced in // the source. // #ifndef __SYSTEMC_EXT_DT_BIT_SC_PROXY_HH__ #define __SYSTEMC_EXT_DT_BIT_SC_PROXY_HH__ #include <iostream> #include "../../utils/functions.hh" #include "../int/sc_int_base.hh" #include "../int/sc_signed.hh" #include "../int/sc_uint_base.hh" #include "../int/sc_unsigned.hh" #include "sc_bit.hh" #include "sc_logic.hh" namespace sc_dt { // classes defined in this module template <class X> class sc_proxy; // forward class declarations class sc_bv_base; class sc_lv_base; template <class X> class sc_bitref_r; template <class X> class sc_bitref; template <class X> class sc_subref_r; template <class X> class sc_subref; template <class X, class Y> class sc_concref_r; template <class X, class Y> class sc_concref; const int SC_DIGIT_SIZE = BITS_PER_BYTE * sizeof(sc_digit); const sc_digit SC_DIGIT_ZERO = (sc_digit)0; const sc_digit SC_DIGIT_ONE = (sc_digit)1; const sc_digit SC_DIGIT_TWO = (sc_digit)2; void sc_proxy_out_of_bounds(const char *msg=NULL, int64 val=0); // assignment functions; forward declarations template <class X, class Y> inline void assign_p_(sc_proxy<X> &px, const sc_proxy<Y> &py); // Vector types that are not derived from sc_proxy must have a length() // function and an operator []. template <class X, class T> inline void assign_v_(sc_proxy<X> &px, const T &a); // other functions; forward declarations const std::string convert_to_bin(const char *s); const std::string convert_to_fmt(const std::string &s, sc_numrep numrep, bool); // ---------------------------------------------------------------------------- // CLASS TEMPLATE : sc_proxy_traits // // Template traits helper to select the correct bit/value/vector_types for // sc_proxy-based vector classes. // // All types derived from/based on a bit-vector contain typedef to a plain // bool, all others point to the sc_logic_value_t/sc_logic/sc_lv_base types. // ---------------------------------------------------------------------------- template <typename X> struct sc_proxy_traits; template <> struct sc_proxy_traits<sc_bv_base> { typedef sc_proxy_traits<sc_bv_base> traits_type; typedef bool value_type; typedef sc_logic bit_type; // sc_logic needed for mixed expressions typedef sc_bv_base vector_type; }; template <> struct sc_proxy_traits<sc_lv_base> { typedef sc_proxy_traits<sc_lv_base> traits_type; typedef sc_logic_value_t value_type; typedef sc_logic bit_type; typedef sc_lv_base vector_type; }; template <typename X> struct sc_proxy_traits<sc_bitref_r<X> > : sc_proxy_traits<X> {}; template <typename X> struct sc_proxy_traits<sc_bitref<X> > : sc_proxy_traits<X> {}; template <typename X> struct sc_proxy_traits<sc_subref_r<X> > : sc_proxy_traits<X> {}; template <typename X> struct sc_proxy_traits<sc_subref<X> > : sc_proxy_traits<X> {}; template <typename X> struct sc_proxy_traits<sc_proxy<X> > : sc_proxy_traits<X> {}; template <typename X, typename Y> struct sc_mixed_proxy_traits_helper : sc_proxy_traits<sc_lv_base> {}; // logic vector by default template <typename X> struct sc_mixed_proxy_traits_helper<X, X> : X {}; template <typename X, typename Y> struct sc_proxy_traits<sc_concref_r<X, Y> > : sc_mixed_proxy_traits_helper< typename X::traits_type, typename Y::traits_type> {}; template <typename X, typename Y> struct sc_proxy_traits<sc_concref<X, Y> > : sc_mixed_proxy_traits_helper< typename X::traits_type, typename Y::traits_type> {}; // ---------------------------------------------------------------------------- // CLASS TEMPLATE : sc_proxy // // Base class template for bit/logic vector classes. // (Barton/Nackmann implementation) // ---------------------------------------------------------------------------- template <class X> class sc_proxy // #### : public sc_value_base { public: typedef typename sc_proxy_traits<X>::traits_type traits_type; typedef typename traits_type::bit_type bit_type; typedef typename traits_type::value_type value_type; // virtual destructor virtual ~sc_proxy() {} // casts X &back_cast() { return static_cast<X &>(*this); } const X &back_cast() const { return static_cast<const X &>(*this); } // assignment operators template <class Y> X & assign_(const sc_proxy<Y> &a) { assign_p_(*this, a); return back_cast(); } X &assign_(const char *a); X &assign_(const bool *a); X &assign_(const sc_logic *a); X & assign_(const sc_unsigned &a) { assign_v_(*this, a); return back_cast(); } X & assign_(const sc_signed &a) { assign_v_(*this, a); return back_cast(); } X &assign_(const sc_uint_base &a) { return assign_((uint64)a); } X &assign_(const sc_int_base &a) { return assign_((int64)a); } X &assign_(unsigned int a); X &assign_(int a); X &assign_(unsigned long a); X &assign_(long a); X &assign_(uint64 a); X &assign_(int64 a); // bitwise operators and functions // bitwise complement X &b_not(); const sc_lv_base operator ~ () const; // bitwise and X &operator &= (const char *b); X &operator &= (const bool *b); X &operator &= (const sc_logic *b); X &operator &= (const sc_unsigned &b); X &operator &= (const sc_signed &b); X &operator &= (const sc_uint_base &b) { return operator &= ((uint64)b); } X &operator &= (const sc_int_base &b) { return operator &= ((int64)b); } X &operator &= (unsigned long b); X &operator &= (long b); X &operator &= (unsigned int b) { return operator &= ((unsigned long)b); } X &operator &= (int b) { return operator &= ((long)b); } X &operator &= (uint64 b); X &operator &= (int64 b); const sc_lv_base operator & (const char *b) const; const sc_lv_base operator & (const bool *b) const; const sc_lv_base operator & (const sc_logic *b) const; const sc_lv_base operator & (const sc_unsigned &b) const; const sc_lv_base operator & (const sc_signed &b) const; const sc_lv_base operator & (const sc_uint_base &b) const; const sc_lv_base operator & (const sc_int_base &b) const; const sc_lv_base operator & (unsigned long b) const; const sc_lv_base operator & (long b) const; const sc_lv_base operator & (unsigned int b) const; const sc_lv_base operator & (int b) const; const sc_lv_base operator & (uint64 b) const; const sc_lv_base operator & (int64 b) const; // bitwise or X &operator |= (const char *b); X &operator |= (const bool *b); X &operator |= (const sc_logic *b); X &operator |= (const sc_unsigned &b); X &operator |= (const sc_signed &b); X &operator |= (const sc_uint_base &b) { return operator |= ((uint64)b); } X &operator |= (const sc_int_base &b) { return operator |= ((int64)b); } X &operator |= (unsigned long b); X &operator |= (long b); X &operator |= (unsigned int b) { return operator |= ((unsigned long)b); } X &operator |= (int b) { return operator |= ((long)b); } X &operator |= (uint64 b); X &operator |= (int64 b); const sc_lv_base operator | (const char *b) const; const sc_lv_base operator | (const bool *b) const; const sc_lv_base operator | (const sc_logic *b) const; const sc_lv_base operator | (const sc_unsigned &b) const; const sc_lv_base operator | (const sc_signed &b) const; const sc_lv_base operator | (const sc_uint_base &b) const; const sc_lv_base operator | (const sc_int_base &b) const; const sc_lv_base operator | (unsigned long b) const; const sc_lv_base operator | (long b) const; const sc_lv_base operator | (unsigned int b) const; const sc_lv_base operator | (int b) const; const sc_lv_base operator | (uint64 b) const; const sc_lv_base operator | (int64 b) const; // bitwise xor X &operator ^= (const char *b); X &operator ^= (const bool *b); X &operator ^= (const sc_logic *b); X &operator ^= (const sc_unsigned &b); X &operator ^= (const sc_signed &b); X &operator ^= (const sc_uint_base &b) { return operator ^= ((uint64)b); } X &operator ^= (const sc_int_base &b) { return operator ^= ((int64)b); } X &operator ^= (unsigned long b); X &operator ^= (long b); X &operator ^= (unsigned int b) { return operator ^= ((unsigned long)b); } X &operator ^= (int b) { return operator ^= ((long)b); } X &operator ^= (uint64 b); X &operator ^= (int64 b); const sc_lv_base operator ^ (const char *b) const; const sc_lv_base operator ^ (const bool *b) const; const sc_lv_base operator ^ (const sc_logic *b) const; const sc_lv_base operator ^ (const sc_unsigned &b) const; const sc_lv_base operator ^ (const sc_signed &b) const; const sc_lv_base operator ^ (const sc_uint_base &b) const; const sc_lv_base operator ^ (const sc_int_base &b) const; const sc_lv_base operator ^ (unsigned long b) const; const sc_lv_base operator ^ (long b) const; const sc_lv_base operator ^ (unsigned int b) const; const sc_lv_base operator ^ (int b) const; const sc_lv_base operator ^ (uint64 b) const; const sc_lv_base operator ^ (int64 b) const; // bitwise left shift X &operator <<= (int n); const sc_lv_base operator << (int n) const; // bitwise right shift X &operator >>= (int n); const sc_lv_base operator >> (int n) const; // bitwise left rotate X &lrotate(int n); // bitwise right rotate X &rrotate(int n); // bitwise reverse X &reverse(); // bit selection sc_bitref<X> operator [] (int i) { return sc_bitref<X>(back_cast(), i); } sc_bitref_r<X> operator [] (int i) const { return sc_bitref_r<X>(back_cast(), i); } sc_bitref<X> bit(int i) { return sc_bitref<X>(back_cast(), i); } sc_bitref_r<X> bit(int i) const { return sc_bitref_r<X>(back_cast(), i); } // part selection sc_subref<X> operator () (int hi, int lo) { return sc_subref<X>(back_cast(), hi, lo); } sc_subref_r<X> operator () (int hi, int lo) const { return sc_subref_r<X>(back_cast(), hi, lo); } sc_subref<X> range(int hi, int lo) { return sc_subref<X>(back_cast(), hi, lo); } sc_subref_r<X> range(int hi, int lo) const { return sc_subref_r<X>(back_cast(), hi, lo); } // reduce functions value_type and_reduce() const; value_type nand_reduce() const { return sc_logic::not_table[and_reduce()]; } value_type or_reduce() const; value_type nor_reduce() const { return sc_logic::not_table[or_reduce()]; } value_type xor_reduce() const; value_type xnor_reduce() const { return sc_logic::not_table[xor_reduce()]; } // relational operators bool operator == (const char *b) const; bool operator == (const bool *b) const; bool operator == (const sc_logic *b) const; bool operator == (const sc_unsigned &b) const; bool operator == (const sc_signed &b) const; bool operator == (const sc_uint_base &b) const; bool operator == (const sc_int_base &b) const; bool operator == (unsigned long b) const; bool operator == (long b) const; bool operator == (unsigned int b) const; bool operator == (int b) const; bool operator == (uint64 b) const; bool operator == (int64 b) const; // explicit conversions to character string const std::string to_string() const; const std::string to_string(sc_numrep) const; const std::string to_string(sc_numrep, bool) const; // explicit conversions inline int64 to_int64() const { return to_anything_signed(); } inline uint64 to_uint64() const; int to_int() const { return (int)to_anything_signed(); } unsigned int to_uint() const { return (unsigned int)to_anything_unsigned(); } long to_long() const { return (long)to_anything_signed(); } unsigned long to_ulong() const { return (unsigned long)to_anything_unsigned(); } // other methods void print(::std::ostream &os=::std::cout) const { // The test below will force printing in binary if decimal is // specified. if (sc_io_base(os, SC_DEC) == SC_DEC) os << to_string(); else os << to_string(sc_io_base(os, SC_BIN), sc_io_show_base(os)); } void scan(::std::istream &is=::std::cin); protected: void check_bounds(int n) const; // check if bit n accessible void check_wbounds(int n) const; // check if word n accessible sc_digit to_anything_unsigned() const; int64 to_anything_signed() const; }; // ---------------------------------------------------------------------------- // bitwise operators and functions // bitwise and template <class X, class Y> inline X &operator &= (sc_proxy<X> &px, const sc_proxy<Y> &py); template <class X, class Y> inline const sc_lv_base operator & ( const sc_proxy<X> &px, const sc_proxy<Y> &py); #define DECL_BITWISE_AND_OP_T(tp) \ template <class X> \ inline const sc_lv_base operator & (tp b, const sc_proxy<X> &px); DECL_BITWISE_AND_OP_T(const char *) DECL_BITWISE_AND_OP_T(const bool *) DECL_BITWISE_AND_OP_T(const sc_logic *) DECL_BITWISE_AND_OP_T(const sc_unsigned &) DECL_BITWISE_AND_OP_T(const sc_signed &) DECL_BITWISE_AND_OP_T(const sc_uint_base &) DECL_BITWISE_AND_OP_T(const sc_int_base &) DECL_BITWISE_AND_OP_T(unsigned long) DECL_BITWISE_AND_OP_T(long) DECL_BITWISE_AND_OP_T(unsigned int) DECL_BITWISE_AND_OP_T(int) DECL_BITWISE_AND_OP_T(uint64) DECL_BITWISE_AND_OP_T(int64) #undef DECL_BITWISE_AND_OP_T // bitwise or template <class X, class Y> inline X &operator |= (sc_proxy<X> &px, const sc_proxy<Y> &py); template <class X, class Y> inline const sc_lv_base operator | ( const sc_proxy<X> &px, const sc_proxy<Y> &py); #define DECL_BITWISE_OR_OP_T(tp) \ template <class X> \ inline const sc_lv_base operator | (tp a, const sc_proxy<X> &px); DECL_BITWISE_OR_OP_T(const char *) DECL_BITWISE_OR_OP_T(const bool *) DECL_BITWISE_OR_OP_T(const sc_logic *) DECL_BITWISE_OR_OP_T(const sc_unsigned &) DECL_BITWISE_OR_OP_T(const sc_signed &) DECL_BITWISE_OR_OP_T(const sc_uint_base &) DECL_BITWISE_OR_OP_T(const sc_int_base &) DECL_BITWISE_OR_OP_T(unsigned long) DECL_BITWISE_OR_OP_T(long) DECL_BITWISE_OR_OP_T(unsigned int) DECL_BITWISE_OR_OP_T(int) DECL_BITWISE_OR_OP_T(uint64) DECL_BITWISE_OR_OP_T(int64) #undef DECL_BITWISE_OR_OP_T // bitwise xor template <class X, class Y> inline X &operator ^= (sc_proxy<X> &px, const sc_proxy<Y> &py); template <class X, class Y> inline const sc_lv_base operator ^ ( const sc_proxy<X> &px, const sc_proxy<Y> &py); #define DECL_BITWISE_XOR_OP_T(tp) \ template <class X> \ inline const sc_lv_base operator ^ (tp a, const sc_proxy<X> &px); DECL_BITWISE_XOR_OP_T(const char *) DECL_BITWISE_XOR_OP_T(const bool *) DECL_BITWISE_XOR_OP_T(const sc_logic *) DECL_BITWISE_XOR_OP_T(const sc_unsigned &) DECL_BITWISE_XOR_OP_T(const sc_signed &) DECL_BITWISE_XOR_OP_T(const sc_uint_base &) DECL_BITWISE_XOR_OP_T(const sc_int_base &) DECL_BITWISE_XOR_OP_T(unsigned long) DECL_BITWISE_XOR_OP_T(long) DECL_BITWISE_XOR_OP_T(unsigned int) DECL_BITWISE_XOR_OP_T(int) DECL_BITWISE_XOR_OP_T(uint64) DECL_BITWISE_XOR_OP_T(int64) #undef DECL_BITWISE_XOR_OP_T // relational operators template <class X, class Y> inline bool operator == (const sc_proxy<X> &px, const sc_proxy<Y> &py); template <class X, class Y> inline bool operator != (const sc_proxy<X> &px, const sc_proxy<Y> &py); #define DECL_REL_OP_T(tp) \ template <class X> \ inline bool operator == (tp b, const sc_proxy<X> &px); \ \ template <class X> \ inline bool operator != (const sc_proxy<X> &px, tp b); \ \ template <class X> \ inline bool operator != (tp b, const sc_proxy<X> &px); DECL_REL_OP_T(const char *) DECL_REL_OP_T(const bool *) DECL_REL_OP_T(const sc_logic *) DECL_REL_OP_T(const sc_unsigned &) DECL_REL_OP_T(const sc_signed &) DECL_REL_OP_T(const sc_uint_base &) DECL_REL_OP_T(const sc_int_base &) DECL_REL_OP_T(unsigned long) DECL_REL_OP_T(long) DECL_REL_OP_T(unsigned int) DECL_REL_OP_T(int) DECL_REL_OP_T(uint64) DECL_REL_OP_T(int64) #undef DECL_REL_OP_T // l-value concatenation // Due to the fact that temporary objects cannot be passed to non-const // references, we have to enumerate, use call by value, and use dynamic // memory allocation (and deallocation). // IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII template <class X> inline void get_words_(const X &x, int wi, sc_digit &x_dw, sc_digit &x_cw) { x_dw = x.get_word(wi); x_cw = x.get_cword(wi); } template <class X> inline void set_words_(X &x, int wi, sc_digit x_dw, sc_digit x_cw) { x.set_word(wi, x_dw); x.set_cword(wi, x_cw); } template <class X> inline void extend_sign_w_(X &x, int wi, bool sign) { int sz = x.size(); unsigned int sgn = (sign ? ~SC_DIGIT_ZERO : SC_DIGIT_ZERO); for (int i = wi; i < sz; ++i) { set_words_(x, i, sgn, SC_DIGIT_ZERO); } } // assignment functions template <class X, class Y> inline void assign_p_(sc_proxy<X> &px, const sc_proxy<Y> &py) { if ((void *)&px != (void *)&py) { X &x = px.back_cast(); const Y &y = py.back_cast(); int sz = x.size(); int min_sz = sc_min(sz, y.size()); int i = 0; for (; i < min_sz; ++i) { set_words_(x, i, y.get_word(i), y.get_cword(i)); } // extend with zeros extend_sign_w_(x, i, false); x.clean_tail(); } } // Vector types that are not derived from sc_proxy, sc_int_base, // sc_uint_base, sc_signed, or sc_unsigned, must have a length() // function and an operator []. The vector argument type must support // accessing bits that are beyond the msb. The vector argument type // decides what to do there (e.g. sign extension or zero padding). template <class X, class T> inline void assign_v_(sc_proxy<X> &px, const T &a) { X &x = px.back_cast(); int i; int len_x = x.length(); int len_a = a.length(); if (len_a > len_x) len_a = len_x; for (i = 0; i < len_a; ++i) { x.set_bit(i, sc_logic_value_t((bool)a[i])); } for (; i < len_x; ++i) { x.set_bit(i, sc_logic_value_t(false)); } } template <class X> inline void assign_v_(sc_proxy<X> &px, const sc_int_base &a) { X &x = px.back_cast(); int i; bool sign = a < 0; int len_x = x.length(); int len_a = a.length(); if ( len_a > len_x ) len_a = len_x; for (i = 0; i < len_a; ++i) { x.set_bit(i, sc_logic_value_t((bool)a[i])); } for (; i < len_x; ++i) { x.set_bit(i, sc_logic_value_t(sign)); } } template <class X> inline void assign_v_(sc_proxy<X> &px, const sc_signed &a) { X &x = px.back_cast(); int i; bool sign = a < 0; int len_x = x.length(); int len_a = a.length(); if (len_a > len_x) len_a = len_x; for (i = 0; i < len_a; ++i) { x.set_bit(i, sc_logic_value_t((bool)a[i])); } for (; i < len_x; ++i) { x.set_bit(i, sc_logic_value_t(sign)); } } template <class X> inline void assign_v_(sc_proxy<X> &px, const sc_uint_base &a) { X &x = px.back_cast(); int i; int len_x = x.length(); int len_a = a.length(); if (len_a > len_x) len_a = len_x; for (i = 0; i < len_a; ++i) { x.set_bit(i, sc_logic_value_t((bool)a[i])); } for (; i < len_x; ++i) { x.set_bit(i, sc_logic_value_t(false)); } } template <class X> inline void assign_v_(sc_proxy<X> &px, const sc_unsigned &a) { X &x = px.back_cast(); int i; int len_x = x.length(); int len_a = a.length(); if (len_a > len_x) len_a = len_x; for (i = 0; i < len_a; ++i) { x.set_bit(i, sc_logic_value_t((bool)a[i])); } for (; i < len_x; ++i) { x.set_bit(i, sc_logic_value_t(false)); } } // assignment operators template <class X> inline X & sc_proxy<X>::assign_(const char *a) { X &x = back_cast(); std::string s = convert_to_bin(a); int len = x.length(); int s_len = s.length() - 1; int min_len = sc_min(len, s_len); int i = 0; for (; i < min_len; ++i) { char c = s[s_len - i - 1]; x.set_bit(i, sc_logic::char_to_logic[(int)c]); } // if formatted, fill the rest with sign(s), otherwise fill with zeros sc_logic_value_t fill = (s[s_len] == 'F' ? sc_logic_value_t(s[0] - '0') : sc_logic_value_t(0)); for (; i < len; ++i) { x.set_bit(i, fill); } return x; } template <class X> inline X & sc_proxy<X>::assign_(const bool *a) { // the length of 'a' must be larger than or equal to the length of 'this' X &x = back_cast(); int len = x.length(); for (int i = 0; i < len; ++i) { x.set_bit(i, sc_logic_value_t(a[i])); } return x; } template <class X> inline X & sc_proxy<X>::assign_(const sc_logic *a) { // the length of 'a' must be larger than or equal to the length of 'this' X &x = back_cast(); int len = x.length(); for (int i = 0; i < len; ++i) { x.set_bit(i, a[i].value()); } return x; } template <class X> inline X & sc_proxy<X>::assign_(unsigned int a) { X &x = back_cast(); set_words_(x, 0, (sc_digit)a, SC_DIGIT_ZERO); // extend with zeros extend_sign_w_(x, 1, false); x.clean_tail(); return x; } template <class X> inline X & sc_proxy<X>::assign_(int a) { X &x = back_cast(); set_words_(x, 0, (sc_digit)a, SC_DIGIT_ZERO); // extend with sign(a) extend_sign_w_(x, 1, (a < 0)); x.clean_tail(); return x; } #if SC_LONG_64 template <class X> inline X & sc_proxy<X>::assign_(unsigned long a) { X &x = back_cast(); set_words_(x, 0, ((sc_digit)a & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); if (x.size() > 1) { set_words_(x, 1, ((sc_digit)(a >> SC_DIGIT_SIZE) & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); // extend with zeros extend_sign_w_(x, 2, false); } x.clean_tail(); return x; } template <class X> inline X & sc_proxy<X>::assign_(long a) { X &x = back_cast(); set_words_(x, 0, ((sc_digit)a & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); if (x.size() > 1) { set_words_(x, 1, ((sc_digit)((uint64)a >> SC_DIGIT_SIZE) & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); // extend with sign(a) extend_sign_w_(x, 2, (a < 0)); } x.clean_tail(); return x; } #else template <class X> inline X & sc_proxy<X>::assign_(unsigned long a) { X &x = back_cast(); set_words_(x, 0, (sc_digit)a, SC_DIGIT_ZERO); // extend with zeros extend_sign_w_(x, 1, false); x.clean_tail(); return x; } template <class X> inline X & sc_proxy<X>::assign_(long a) { X &x = back_cast(); set_words_(x, 0, (sc_digit)a, SC_DIGIT_ZERO); // extend with sign(a) extend_sign_w_(x, 1, (a < 0)); x.clean_tail(); return x; } #endif template <class X> inline X & sc_proxy<X>::assign_(uint64 a) { X &x = back_cast(); set_words_(x, 0, ((sc_digit)a & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); if (x.size() > 1) { set_words_(x, 1, ((sc_digit) (a >> SC_DIGIT_SIZE) & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO ); // extend with zeros extend_sign_w_(x, 2, false); } x.clean_tail(); return x; } template <class X> inline X & sc_proxy<X>::assign_(int64 a) { X &x = back_cast(); set_words_(x, 0, ((sc_digit)a & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO); if (x.size() > 1) { set_words_(x, 1, ((sc_digit)((uint64)a >> SC_DIGIT_SIZE) & ~SC_DIGIT_ZERO), SC_DIGIT_ZERO ); // extend with sign(a) extend_sign_w_(x, 2, (a < 0)); } x.clean_tail(); return x; } // bitwise operators and functions // bitwise complement template <class X> inline X & sc_proxy<X>::b_not() { X &x = back_cast(); int sz = x.size(); for (int i = 0; i < sz; ++i) { sc_digit x_dw, x_cw; get_words_(x, i, x_dw, x_cw); x.set_word(i, x_cw | ~x_dw); } x.clean_tail(); return x; } // bitwise and template <class X, class Y> inline X & b_and_assign_(sc_proxy<X> &px, const sc_proxy<Y> &py) { X &x = px.back_cast(); const Y &y = py.back_cast(); sc_assert(x.length() == y.length()); int sz = x.size(); for (int i = 0; i < sz; ++i) { sc_digit x_dw, x_cw, y_dw, y_cw; get_words_(x, i, x_dw, x_cw); get_words_(y, i, y_dw, y_cw); sc_digit cw = (x_dw & y_cw) | (x_cw & y_dw) | (x_cw & y_cw); sc_digit dw = cw | (x_dw & y_dw); set_words_(x, i, dw, cw); } // tail cleaning not needed return x; } // bitwise or template <class X, class Y> inline X & b_or_assign_(sc_proxy<X> &px, const sc_proxy<Y> &py) { X &x = px.back_cast(); const Y &y = py.back_cast(); sc_assert(x.length() == y.length()); int sz = x.size(); for (int i = 0; i < sz; ++i) { sc_digit x_dw, x_cw, y_dw, y_cw; get_words_(x, i, x_dw, x_cw); get_words_(y, i, y_dw, y_cw); sc_digit cw = (x_cw & y_cw) | (x_cw & ~y_dw) | (~x_dw & y_cw); sc_digit dw = cw | x_dw | y_dw; set_words_(x, i, dw, cw); } // tail cleaning not needed return x; } // bitwise xor template <class X, class Y> inline X & b_xor_assign_(sc_proxy<X> &a, const sc_proxy<Y> &b) { X &x = a.back_cast(); const Y &y = b.back_cast(); sc_assert(x.length() == y.length()); int sz = x.size(); for (int i = 0; i < sz; ++i) { sc_digit x_dw, x_cw, y_dw, y_cw; get_words_(x, i, x_dw, x_cw); get_words_(y, i, y_dw, y_cw); sc_digit cw = x_cw | y_cw; sc_digit dw = cw | (x_dw ^ y_dw); set_words_( x, i, dw, cw ); } // tail cleaning not needed return x; } // bitwise left shift template <class X> inline X & sc_proxy<X>::operator <<= (int n) { X &x = back_cast(); if (n < 0) { sc_proxy_out_of_bounds("left shift operation is only allowed with " "positive shift values, shift value = ", n); return x; } if (n >= x.length()) { extend_sign_w_(x, 0, false); // no tail cleaning needed return x; } int sz = x.size(); int wn = n / SC_DIGIT_SIZE; int bn = n % SC_DIGIT_SIZE; if (wn != 0) { // shift words int i = sz - 1; for (; i >= wn; --i) { set_words_(x, i, x.get_word(i - wn), x.get_cword(i - wn)); } for (; i >= 0; --i) { set_words_(x, i, SC_DIGIT_ZERO, SC_DIGIT_ZERO); } } if (bn != 0) { // shift bits for (int i = sz - 1; i >= 1; --i) { sc_digit x_dw, x_cw; get_words_(x, i, x_dw, x_cw); x_dw <<= bn; x_dw |= x.get_word(i - 1) >> (SC_DIGIT_SIZE - bn); x_cw <<= bn; x_cw |= x.get_cword(i - 1) >> (SC_DIGIT_SIZE - bn); set_words_(x, i, x_dw, x_cw); } sc_digit x_dw, x_cw; get_words_(x, 0, x_dw, x_cw); x_dw <<= bn; x_cw <<= bn; set_words_(x, 0, x_dw, x_cw); } x.clean_tail(); return x; } // bitwise right shift template <class X> inline X & sc_proxy<X>::operator >>= (int n) { X &x = back_cast(); if (n < 0) { sc_proxy_out_of_bounds("right shift operation is only allowed with " "positive shift values, shift value = ", n); return x; } if (n >= x.length()) { extend_sign_w_(x, 0, false); // no tail cleaning needed return x; } int sz = x.size(); int wn = n / SC_DIGIT_SIZE; int bn = n % SC_DIGIT_SIZE; if (wn != 0) { // shift words int i = 0; for (; i < (sz - wn); ++i) { set_words_(x, i, x.get_word(i + wn), x.get_cword(i + wn)); } for (; i < sz; ++i) { set_words_(x, i, SC_DIGIT_ZERO, SC_DIGIT_ZERO); } } if (bn != 0) { // shift bits for (int i = 0; i < (sz - 1); ++i) { sc_digit x_dw, x_cw; get_words_(x, i, x_dw, x_cw); x_dw >>= bn; x_dw |= x.get_word(i + 1) << (SC_DIGIT_SIZE - bn); x_cw >>= bn; x_cw |= x.get_cword(i + 1) << (SC_DIGIT_SIZE - bn); set_words_(x, i, x_dw, x_cw); } sc_digit x_dw, x_cw; get_words_(x, sz - 1, x_dw, x_cw); x_dw >>= bn; x_cw >>= bn; set_words_(x, sz - 1, x_dw, x_cw); } x.clean_tail(); return x; } // bitwise left rotate template <class X> inline const sc_lv_base lrotate(const sc_proxy<X> &x, int n); // bitwise right rotate template <class X> inline const sc_lv_base rrotate(const sc_proxy<X>& x, int n); // bitwise reverse template <class X> inline X & sc_proxy<X>::reverse() { X &x = back_cast(); int len = x.length(); int half_len = len / 2; for (int i = 0, j = len - 1; i < half_len; ++ i, --j) { value_type t = x.get_bit(i); x.set_bit(i, x.get_bit(j)); x.set_bit(j, t); } return x; } template <class X> inline const sc_lv_base reverse(const sc_proxy<X> &a); // reduce functions template <class X> inline typename sc_proxy<X>::value_type sc_proxy<X>::and_reduce() const { const X &x = back_cast(); value_type result = value_type(1); int len = x.length(); for (int i = 0; i < len; ++i) { result = sc_logic::and_table[result][x.get_bit(i)]; } return result; } template <class X> inline typename sc_proxy<X>::value_type sc_proxy<X>::or_reduce() const { const X &x = back_cast(); value_type result = value_type(0); int len = x.length(); for (int i = 0; i < len; ++i) { result = sc_logic::or_table[result][x.get_bit(i)]; } return result; } template <class X> inline typename sc_proxy<X>::value_type sc_proxy<X>::xor_reduce() const { const X &x = back_cast(); value_type result = value_type(0); int len = x.length(); for (int i = 0; i < len; ++i) { result = sc_logic::xor_table[result][x.get_bit(i)]; } return result; } // relational operators template <class X, class Y> inline bool operator != (const sc_proxy<X> &px, const sc_proxy<Y> &py) { return !(px == py); } #define DEFN_REL_OP_T(tp) \ template <class X> \ inline bool operator == (tp b, const sc_proxy<X> &px) { return (px == b); } \ \ template <class X> \ inline bool operator != (const sc_proxy<X> &px, tp b) { return !(px == b); } \ \ template <class X> \ inline bool operator != (tp b, const sc_proxy<X> &px) { return !(px == b); } DEFN_REL_OP_T(const char *) DEFN_REL_OP_T(const bool *) DEFN_REL_OP_T(const sc_logic *) DEFN_REL_OP_T(const sc_unsigned &) DEFN_REL_OP_T(const sc_signed &) DEFN_REL_OP_T(const sc_uint_base &) DEFN_REL_OP_T(const sc_int_base &) DEFN_REL_OP_T(unsigned long) DEFN_REL_OP_T(long) DEFN_REL_OP_T(unsigned int) DEFN_REL_OP_T(int) DEFN_REL_OP_T(uint64) DEFN_REL_OP_T(int64) #undef DEFN_REL_OP_T // explicit conversions to character string template <class X> inline const std::string sc_proxy<X>::to_string() const { const X &x = back_cast(); int len = x.length(); std::string s; // (len + 1); for (int i = 0; i < len; ++i) { s += sc_logic::logic_to_char[x.get_bit(len - i - 1)]; } return s; } template <class X> inline const std::string sc_proxy<X>::to_string(sc_numrep numrep) const { return convert_to_fmt(to_string(), numrep, true); } template <class X> inline const std::string sc_proxy<X>::to_string(sc_numrep numrep, bool w_prefix) const { return convert_to_fmt(to_string(), numrep, w_prefix); } // other methods template <class X> inline void sc_proxy<X>::scan(::std::istream &is) { std::string s; is >> s; back_cast() = s.c_str(); } template <class X> inline void sc_proxy<X>::check_bounds(int n) const // check if bit n accessible { if (n < 0 || n >= back_cast().length()) { sc_proxy_out_of_bounds(NULL, n); sc_core::sc_abort(); // can't recover from here } } template <class X> inline void sc_proxy<X>::check_wbounds(int n) const // check if word n accessible { if (n < 0 || n >= back_cast().size()) { sc_proxy_out_of_bounds(NULL, n); sc_core::sc_abort(); // can't recover from here } } template <class X> inline sc_digit sc_proxy<X>::to_anything_unsigned() const { // only 0 word is returned // can't convert logic values other than 0 and 1 const X &x = back_cast(); int len = x.length(); if (x.get_cword(0) != SC_DIGIT_ZERO) { SC_REPORT_WARNING("vector contains 4-value logic", 0); } sc_digit w = x.get_word(0); if (len >= SC_DIGIT_SIZE) { return w; } return (w & (~SC_DIGIT_ZERO >> (SC_DIGIT_SIZE - len))); } template <class X> inline uint64 sc_proxy<X>::to_uint64() const { // words 1 and 0 returned. // can't convert logic values other than 0 and 1 const X &x = back_cast(); int len = x.length(); if (x.get_cword(0) != SC_DIGIT_ZERO) { SC_REPORT_WARNING("vector contains 4-value logic", 0); } uint64 w = x.get_word(0); if (len > SC_DIGIT_SIZE) { if (x.get_cword(1) != SC_DIGIT_ZERO) { SC_REPORT_WARNING("vector contains 4-value logic", 0); } uint64 w1 = x.get_word(1); w = w | (w1 << SC_DIGIT_SIZE); return w; } else if (len == SC_DIGIT_SIZE) { return w; } else { return (w & (~SC_DIGIT_ZERO >> (SC_DIGIT_SIZE - len))); } } template <class X> inline int64 sc_proxy<X>::to_anything_signed() const { const X &x = back_cast(); int len = x.length(); int64 w = 0; if (len > SC_DIGIT_SIZE) { if (x.get_cword(1) != SC_DIGIT_ZERO) SC_REPORT_WARNING("vector contains 4-value logic", 0); w = x.get_word(1); } if (x.get_cword(0) != SC_DIGIT_ZERO) SC_REPORT_WARNING("vector contains 4-value logic", 0); w = (w << SC_DIGIT_SIZE) | x.get_word(0); if (len >= 64) { return w; } uint64 zero = 0; value_type sgn = x.get_bit(len - 1); if (sgn == 0) { return (int64)(w & (~zero >> (64 - len))); } else { return (int64)(w | (~zero << len)); } } // ---------------------------------------------------------------------------- // functional notation for the reduce methods template <class X> inline typename sc_proxy<X>::value_type and_reduce(const sc_proxy<X> &a) { return a.and_reduce(); } template <class X> inline typename sc_proxy<X>::value_type nand_reduce(const sc_proxy<X> &a) { return a.nand_reduce(); } template <class X> inline typename sc_proxy<X>::value_type or_reduce(const sc_proxy<X> &a) { return a.or_reduce(); } template <class X> inline typename sc_proxy<X>::value_type nor_reduce(const sc_proxy<X> &a) { return a.nor_reduce(); } template <class X> inline typename sc_proxy<X>::value_type xor_reduce(const sc_proxy<X> &a) { return a.xor_reduce(); } template <class X> inline typename sc_proxy<X>::value_type xnor_reduce(const sc_proxy<X> &a) { return a.xnor_reduce(); } // ---------------------------------------------------------------------------- template <class X> inline ::std::ostream & operator << (::std::ostream &os, const sc_proxy<X> &a) { a.print(os); return os; } template <class X> inline ::std::istream & operator >> (::std::istream &is, sc_proxy<X> &a) { a.scan(is); return is; } } // namespace sc_dt #endif // __SYSTEMC_EXT_DT_BIT_SC_PROXY_HH__
27.30681
79
0.610191
[ "vector" ]
12e44505be69de26b6f4f9b54bf563ac78d57301
1,985
cpp
C++
camera_ueye.cpp
fhwedel-hoe/ueye_mjpeg_streamer
3aec9638ffa764b22e798753a312ac5e8b61a468
[ "MIT" ]
2
2020-03-13T01:56:32.000Z
2020-08-19T22:12:10.000Z
camera_ueye.cpp
fhwedel-hoe/ueye_mjpeg_streamer
3aec9638ffa764b22e798753a312ac5e8b61a468
[ "MIT" ]
null
null
null
camera_ueye.cpp
fhwedel-hoe/ueye_mjpeg_streamer
3aec9638ffa764b22e798753a312ac5e8b61a468
[ "MIT" ]
1
2021-02-06T19:49:33.000Z
2021-02-06T19:49:33.000Z
#include "camera_ueye.hpp" #include <stdexcept> extern "C" { std::unique_ptr<Camera> init_camera() { return std::make_unique<Camera_ueye>(); } } void abortOnError(const int status, const char *msg) { if (status != 0) { throw std::runtime_error(std::string(msg)+std::to_string(status)); } } Camera_ueye::Camera_ueye() : Camera() { /* initialize first available camera */ int nRet = is_InitCamera(&hCam, 0); abortOnError(nRet, "InitCamera failed with error code: "); /* receive sensor info */ SENSORINFO sensorInfo; nRet = is_GetSensorInfo(hCam, &sensorInfo); abortOnError(nRet, "Receving sensor info failed with error code: "); /* receive camera image size */ nRet = is_AOI(hCam, IS_AOI_IMAGE_GET_AOI, &rectAoi, sizeof(rectAoi)); abortOnError(nRet, "Receving image aoi failed with error code: "); /* set color mode */ nRet = is_SetColorMode(hCam, IS_CM_BGR8_PACKED); abortOnError(nRet, "Setting color mode failed with error code: "); /* allocate image buffer */ int nMemoryId; nRet = is_AllocImageMem(hCam, rectAoi.s32Width, rectAoi.s32Height, 24, &pMemoryBuffer, &nMemoryId); abortOnError(nRet, "Allocating image memory failed with error code: "); sData = rectAoi.s32Width * rectAoi.s32Height * 3; /* set allocated image buffer active */ nRet = is_SetImageMem(hCam, pMemoryBuffer, nMemoryId); abortOnError(nRet, "Setting image memory active failed with error code: "); } Camera_ueye::~Camera_ueye() { /* close camera */ int nRet = is_ExitCamera(hCam); abortOnError(nRet, "exit camera failed with error code: "); } RawImage Camera_ueye::grab_frame() { /* capture a single frame */ int nRet = is_FreezeVideo(hCam, IS_WAIT); unsigned char* pData = reinterpret_cast<unsigned char*>(pMemoryBuffer); /* wrap C array */ return RawImage(std::vector<unsigned char>(pData,pData+sData), rectAoi.s32Width, rectAoi.s32Height, TJPF_BGR); }
33.644068
114
0.68665
[ "vector" ]
12e52d739cab1dd8353a3198bdc97439796077e0
926
cc
C++
node_addons/sourceId2Coordinates/src/index.cc
quitrk/jitsi-meet-electron-utils
5e51b139be77c1f01baae623ea2abd6ee6c4e8c0
[ "Apache-2.0" ]
7
2021-11-11T16:11:32.000Z
2022-03-24T21:28:48.000Z
node_addons/sourceId2Coordinates/src/index.cc
quitrk/jitsi-meet-electron-utils
5e51b139be77c1f01baae623ea2abd6ee6c4e8c0
[ "Apache-2.0" ]
34
2021-11-10T13:30:12.000Z
2022-03-29T17:00:58.000Z
node_addons/sourceId2Coordinates/src/index.cc
quitrk/jitsi-meet-electron-utils
5e51b139be77c1f01baae623ea2abd6ee6c4e8c0
[ "Apache-2.0" ]
4
2021-11-11T13:45:32.000Z
2022-03-22T14:17:52.000Z
#include <napi.h> #include "sourceId2Coordinates.h" Napi::Value sourceId2CoordinatesWrapper(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); const int sourceID = info[0].As<Napi::Number>().Int32Value(); Napi::Object obj = Napi::Object::New(env); Point coordinates; if(!sourceId2Coordinates(sourceID, &coordinates)) { // return undefined if sourceId2Coordinates function fail. return env.Undefined(); } else { // return the coordinates if sourceId2Coordinates function succeed. obj.Set(Napi::String::New(env, "x"), Napi::Number::New(env, coordinates.x)); obj.Set(Napi::String::New(env, "y"), Napi::Number::New(env, coordinates.y)); return obj; } } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "sourceId2Coordinates"), Napi::Function::New(env, sourceId2CoordinatesWrapper)); return exports; } NODE_API_MODULE(sourceId2CoordinatesModule, Init)
31.931034
116
0.730022
[ "object" ]
12e82265522807e93bd0baa4331aac9aeaf4da2a
27,592
cc
C++
src/meshing/GeniusLoader.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
src/meshing/GeniusLoader.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
src/meshing/GeniusLoader.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
/*** DEVSIM Copyright 2013 Devsim LLC 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. ***/ #include "GeniusLoader.hh" #include "OutputStream.hh" #include "Region.hh" #include "GlobalData.hh" #include "Device.hh" #include "Coordinate.hh" #include "Contact.hh" #include "Interface.hh" #include "dsAssert.hh" #include "Node.hh" #include "Edge.hh" #include "Triangle.hh" #include "Tetrahedron.hh" #include "ModelCreate.hh" #include "ObjectHolder.hh" #include "NodeSolution.hh" #include <sstream> namespace dsMesh { namespace { /* local node index are 1 based in cgns */ void processNodes(const MeshNodeList_t &mnlist, const std::vector<Coordinate *> &clist, std::vector<Node *> &node_list) { node_list.clear(); node_list.resize(mnlist.size()+1); for (size_t node_index = 0; node_index < mnlist.size(); ++node_index) { const MeshNode &mesh_node = mnlist[node_index]; const size_t cindex = mesh_node.Index(); dsAssert(cindex < clist.size(), "UNEXPECTED"); dsAssert(clist[cindex] != 0, "UNEXPECTED"); Node *tp = new Node(node_index, clist[cindex]); node_list[node_index+1] = tp; } } void processEdges(const MeshEdgeList_t &tl, const std::vector<Node *> &nlist, std::vector<const Edge *> &edge_list) { MeshEdgeList_t::const_iterator tit = tl.begin(); for (size_t ti = 0; tit != tl.end(); ++tit, ++ti) { const size_t index0 = tit->Index0(); const size_t index1 = tit->Index1(); dsAssert(index0 < nlist.size(), "UNEXPECTED"); dsAssert(index1 < nlist.size(), "UNEXPECTED"); dsAssert(nlist[index0] != 0, "UNEXPECTED"); dsAssert(nlist[index1] != 0, "UNEXPECTED"); Edge *tp = new Edge(ti, nlist[index0], nlist[index1]); edge_list.push_back(tp); } } void processTriangles(const MeshTriangleList_t &tl, const std::vector<Node *> &nlist, std::vector<const Triangle *> &triangle_list) { MeshTriangleList_t::const_iterator tit = tl.begin(); for (size_t ti = 0; tit != tl.end(); ++tit, ++ti) { const size_t index0 = tit->Index0(); const size_t index1 = tit->Index1(); const size_t index2 = tit->Index2(); dsAssert(index0 < nlist.size(), "UNEXPECTED"); dsAssert(index1 < nlist.size(), "UNEXPECTED"); dsAssert(index2 < nlist.size(), "UNEXPECTED"); // size_t nlistsize = nlist.size(); dsAssert(nlist[index0] != 0, "UNEXPECTED"); dsAssert(nlist[index1] != 0, "UNEXPECTED"); dsAssert(nlist[index2] != 0, "UNEXPECTED"); Triangle *tp = new Triangle(ti, nlist[index0], nlist[index1], nlist[index2]); triangle_list.push_back(tp); } } void processTetrahedra(const MeshTetrahedronList_t &tl, const std::vector<Node *> &nlist, std::vector<const Tetrahedron *> &tetrahedron_list) { MeshTetrahedronList_t::const_iterator tit = tl.begin(); for (size_t ti = 0; tit != tl.end(); ++tit, ++ti) { const size_t index0 = tit->Index0(); const size_t index1 = tit->Index1(); const size_t index2 = tit->Index2(); const size_t index3 = tit->Index3(); dsAssert(index0 < nlist.size(), "UNEXPECTED"); dsAssert(index1 < nlist.size(), "UNEXPECTED"); dsAssert(index2 < nlist.size(), "UNEXPECTED"); dsAssert(index3 < nlist.size(), "UNEXPECTED"); dsAssert(nlist[index0] != 0, "UNEXPECTED"); dsAssert(nlist[index1] != 0, "UNEXPECTED"); dsAssert(nlist[index2] != 0, "UNEXPECTED"); dsAssert(nlist[index3] != 0, "UNEXPECTED"); // std::cerr << "DEBUG "; // std::cerr // << nlist[index0]->GetIndex() << "\t" // << nlist[index1]->GetIndex() << "\t" // << nlist[index2]->GetIndex() << "\t" // << nlist[index3]->GetIndex() << "\t" // << std::endl; // ; Tetrahedron *tp = new Tetrahedron(ti, nlist[index0], nlist[index1], nlist[index2], nlist[index3]); tetrahedron_list.push_back(tp); } } } GeniusLoader::GeniusLoader(const std::string &n) : Mesh(n), dimension(0), resistive_metal(false) { //// Arbitrary number meshCoordinateList.reserve(10000); } GeniusLoader::~GeniusLoader() { } void GeniusLoader::AddRegion(GeniusRegionPtr grip) { const std::string &region_name = grip->region; geniusRegionMap[region_name] = grip; GeniusRegion &ri = *grip; std::vector<double> &x = ri.vec_x; std::vector<double> &y = ri.vec_y; std::vector<double> &z = ri.vec_z; std::vector<int> &ni = ri.global_node_index; for (size_t i = 0; i < x.size(); ++i) { AddCoordinate(ni[i], MeshCoordinate(x[i], y[i], z[i])); } std::vector<double>(0).swap(x); std::vector<double>(0).swap(y); std::vector<double>(0).swap(z); std::vector<GeniusBoundaryPtr> &bocos = ri.bocos; for (size_t i = 0; i < bocos.size(); ++i) { GeniusBoundaryPtr bip = bocos[i]; if (bip->label.empty()) { geniusBoundaryMap[bip->name].push_back(bip); } else { geniusBoundaryMap[bip->label].push_back(bip); } } } std::vector<int> *GeniusLoader::GetGeniusRegionBoundaryPoints(const std::string &genius_region_name, const std::string &genius_boundary_name) { std::vector<int> *ret = NULL; do { if (!HasGeniusRegion(genius_region_name)) { std::ostringstream os; os << "Cannot find genius region " << genius_region_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = NULL; break; } GeniusRegion &genius_region = GetGeniusRegion(genius_region_name); if (!genius_region.HasBoundary(genius_boundary_name)) { std::ostringstream os; os << "Cannot find genius boundary " << genius_boundary_name << " on genius region.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); break; } GeniusBoundary &genius_boundary = genius_region.GetBoundary(genius_boundary_name); if (genius_boundary.points.empty()) { std::ostringstream os; os << "Cannot find points genius boundary " << genius_boundary_name << " on genius region " << genius_region_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); break; } else { ret = &(genius_boundary.points); } } while(0); return ret; } bool GeniusLoader::Instantiate_(const std::string &deviceName, std::string &errorString) { bool ret = true; GlobalData &gdata = GlobalData::GetInstance(); if (gdata.GetDevice(deviceName)) { std::ostringstream os; os << deviceName << " already exists\n"; errorString += os.str(); ret = false; return ret; } DevicePtr dp = new Device(deviceName, dimension); gdata.AddDevice(dp); Device::CoordinateList_t coordinate_list(meshCoordinateList.size()); for (size_t i = 0; i < meshCoordinateList.size(); ++i) { const MeshCoordinate &mc = (meshCoordinateList[i]); CoordinatePtr new_coordinate = new Coordinate(mc.GetX(), mc.GetY(), mc.GetZ()); coordinate_list[i] = new_coordinate; dp->AddCoordinate(new_coordinate); } { std::ostringstream os; os << "Device " << deviceName << " has " << meshCoordinateList.size() << " coordinates.\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } std::map<std::string, std::vector<NodePtr> > RegionNameToNodeMap; //// For each name in the region map, we create a list of nodes which are indexes { MeshNodeList_t mesh_nodes; MeshTetrahedronList_t mesh_tetrahedra; MeshTriangleList_t mesh_triangles; MeshEdgeList_t mesh_edges; ConstTetrahedronList tetrahedronList; ConstTriangleList triangleList; ConstEdgeList edgeList; for (MapToRegionInfo_t::const_iterator rit = regionMap.begin(); rit != regionMap.end(); ++rit) { mesh_nodes.clear(); tetrahedronList.clear(); triangleList.clear(); edgeList.clear(); const std::string &regionName = rit->first; const GeniusRegionInfo &rinfo = rit->second; const std::string &genius_region_name = rinfo.genius_region_name; Region *regionptr = dp->GetRegion(regionName); if (!regionptr) { regionptr = new Region(regionName, rinfo.material, dimension, dp); dp->AddRegion(regionptr); } Region &region = *regionptr; if (!HasGeniusRegion(genius_region_name)) { std::ostringstream os; os << "Cannot find genius region " << genius_region_name << " for region " << regionName << "\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } GeniusRegion &genius_region = GetGeniusRegion(genius_region_name); const std::vector<int> &gni = genius_region.global_node_index; mesh_nodes.reserve(gni.size()); //// mesh_nodes reference global coordinate index through gni for (size_t i = 0; i < gni.size(); ++i) { mesh_nodes.push_back(MeshNode(gni[i])); } { std::ostringstream os; os << "Region " << regionName << " has " << mesh_nodes.size() << " nodes.\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } std::vector<NodePtr> &nodeList = RegionNameToNodeMap[regionName]; processNodes(mesh_nodes, coordinate_list, nodeList); for (size_t i = 1; i < nodeList.size(); ++i) { region.AddNode(nodeList[i]); } { std::ostringstream os; os << "Region " << regionName << " has " << nodeList.size() << " nodes.\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } if (dimension == 3) { processTetrahedra(geniusShapesMap[regionName].Tetrahedra, nodeList, tetrahedronList); region.AddTetrahedronList(tetrahedronList); } if (dimension >= 2) { processTriangles(geniusShapesMap[regionName].Triangles, nodeList, triangleList); region.AddTriangleList(triangleList); } processEdges(geniusShapesMap[regionName].Lines, nodeList, edgeList); region.AddEdgeList(edgeList); region.FinalizeMesh(); CreateDefaultModels(&region); for (std::map<std::string, std::vector<double> >::iterator sit = genius_region.solutions.begin(); sit != genius_region.solutions.end(); ++sit) { const std::string &sname = sit->first; NodeSolution *nodesol = new NodeSolution(sname, &region); std::vector<double> &nval = sit->second; const size_t nlen = nval.size(); bool is_uniform = true; const double val0 = nval[0]; for (size_t i = 1; i < nlen; ++i) { if (val0 != nval[i]) { is_uniform = false; break; } } if (is_uniform) { nodesol->SetValues(val0); } else { nodesol->SetValues(nval); } } { for (std::map<std::string, std::string>::iterator sit = genius_region.units.begin(); sit != genius_region.units.end(); ++sit) { const std::string &sname = sit->first; gdata.AddDBEntryOnRegion(deviceName, regionName, sname, ObjectHolder(sit->second)); } } } } //// Now process the contact { ConstNodeList cnodes; for (MapToContactInfo_t::const_iterator cit = contactMap.begin(); cit != contactMap.end(); ++cit) { const std::string &contactName = cit->first; const GeniusContactInfo &cinfo = cit->second; const std::string &regionName = cinfo.region; const std::string &materialName = cinfo.material; if ((!RegionNameToNodeMap.count(regionName)) || (!HasRegionInfo(regionName))) { std::ostringstream os; os << "Contact " << contactName << " references non-existent region name " << regionName << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } GeniusRegionInfo &rinfo = GetRegionInfo(regionName); const std::string &genius_region_name = rinfo.genius_region_name; /** these are the 1 based nodes on the Map */ const std::vector<NodePtr> &nodeList = RegionNameToNodeMap[regionName]; /// This is the genius name of the boundary condition const std::string &genius_boundary_name = cinfo.boundary_name; Region *regionptr = dp->GetRegion(regionName); if (!regionptr) { std::ostringstream os; os << "Contact " << contactName << " references non-existent region name " << regionName << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } Contact *contactptr = dp->GetContact(contactName); if (contactptr) { std::ostringstream os; os << "Contact " << contactName << " on region " << regionName << " being instantiated multiple times.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } { std::vector<int> *pp = GetGeniusRegionBoundaryPoints(genius_region_name, genius_boundary_name); if (!pp) { ret = false; continue; } cnodes.clear(); std::vector<int> &points = *pp; const size_t plen = points.size(); const size_t nlen = nodeList.size(); dsAssert ((plen > 0), "UNEXPECTED mesh problem"); for (size_t i = 0; i < plen; ++i) { size_t pindex = static_cast<size_t>(points[i]); dsAssert ((pindex > 1) || (pindex < nlen), "UNEXPECTED mesh problem"); ConstNodePtr np = nodeList[pindex]; cnodes.push_back(np); } } dp->AddContact(new Contact(contactName, regionptr, cnodes, materialName)); std::ostringstream os; os << "Contact " << contactName << " in region " << regionName << " with " << cnodes.size() << " nodes" << "\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } } { ConstNodeList inodes0; ConstNodeList inodes1; MeshNodeList_t mesh_nodes; for (MapToInterfaceInfo_t::const_iterator iit = interfaceMap.begin(); iit != interfaceMap.end(); ++iit) { mesh_nodes.clear(); const std::string &interfaceName = iit->first; const GeniusInterfaceInfo &iinfo = iit->second; const std::string &regionName0 = iinfo.region0; const std::string &regionName1 = iinfo.region1; const std::string &genius_boundary_name = iinfo.boundary_name; if ((!RegionNameToNodeMap.count(regionName0)) || (!HasRegionInfo(regionName0))) { std::ostringstream os; os << "Interface " << interfaceName << " references non-existent region name " << regionName0 << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } if ((!RegionNameToNodeMap.count(regionName1)) || (!HasRegionInfo(regionName1))) { std::ostringstream os; os << "Interface " << interfaceName << " references non-existent region name " << regionName1 << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } GeniusRegionInfo &rinfo0 = GetRegionInfo(regionName0); GeniusRegionInfo &rinfo1 = GetRegionInfo(regionName1); const std::vector<NodePtr> &nodeList0 = RegionNameToNodeMap[regionName0]; const std::vector<NodePtr> &nodeList1 = RegionNameToNodeMap[regionName1]; Region *regionptr0 = dp->GetRegion(regionName0); Region *regionptr1 = dp->GetRegion(regionName1); if (!regionptr0) { std::ostringstream os; os << "Interface " << interfaceName << " references non-existent region name " << regionName0 << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } if (!regionptr1) { std::ostringstream os; os << "Interface " << interfaceName << " references non-existent region name " << regionName1 << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } Interface *interfaceptr = dp->GetInterface(interfaceName); if (interfaceptr) { std::ostringstream os; os << "Interface " << interfaceName << " on regions " << regionName0 << " and " << regionName1 << " being instantiated multiple times.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } const std::string &genius_region_name0 = rinfo0.genius_region_name; const std::string &genius_region_name1 = rinfo1.genius_region_name; std::vector<int> *pp0 = GetGeniusRegionBoundaryPoints(genius_region_name0, genius_boundary_name); std::vector<int> *pp1 = GetGeniusRegionBoundaryPoints(genius_region_name1, genius_boundary_name); if (!(pp0 && pp1)) { ret = false; continue; } std::vector<int> &points0 = *pp0; std::vector<int> &points1 = *pp1; if (points0.size() != points1.size()) { std::ostringstream os; os << "Interface " << interfaceName << " on regions " << regionName0 << " and " << regionName1 << " has points mismatch.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); ret = false; continue; } const size_t plen = points0.size(); const size_t nlen0 = nodeList0.size(); const size_t nlen1 = nodeList1.size(); dsAssert ((plen > 0), "UNEXPECTED mesh problem"); inodes0.clear(); inodes1.clear(); for (size_t i = 0; i < plen; ++i) { const size_t pindex0 = static_cast<size_t>(points0[i]); const size_t pindex1 = static_cast<size_t>(points1[i]); dsAssert ((pindex0 > 1) || (pindex0 < nlen0), "UNEXPECTED mesh problem"); dsAssert ((pindex1 > 1) || (pindex1 < nlen1), "UNEXPECTED mesh problem"); ConstNodePtr np0 = nodeList0[pindex0]; ConstNodePtr np1 = nodeList1[pindex1]; inodes0.push_back(np0); inodes1.push_back(np1); } dp->AddInterface(new Interface(interfaceName, regionptr0, regionptr1, inodes0, inodes1)); std::ostringstream os; os << "Adding interface " << interfaceName << " with " << inodes0.size() << ", " << inodes1.size() << " nodes" << "\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } } gdata.AddDBEntryOnDevice(deviceName, "magic_number", ObjectHolder(GetMagicNumber())); //// TODO: input scaling factor? return ret; } ///// This function should mostly just do error checking bool GeniusLoader::Finalize_(std::string &errorString) { bool ret = true; /// Mesh coordinates are over the entire device { for (MapToRegionInfo_t::iterator it = regionMap.begin(); it != regionMap.end(); ++it) { const std::string &region_name = it->first; const std::string &genius_region_name = it->second.genius_region_name; Shapes &region_shapes = geniusShapesMap[region_name]; MapToGeniusRegion_t::iterator jit = geniusRegionMap.find(genius_region_name); if (jit != geniusRegionMap.end()) { region_shapes.AddShapes(jit->second->genius_shapes); } else { ret = false; std::ostringstream os; os << "Genius region name " << genius_region_name << " does not exist.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } } } { for (MapToContactInfo_t::iterator it = contactMap.begin(); it != contactMap.end(); ++it) { const std::string &contact_name = it->first; const std::string &region_name = it->second.region; const std::string &boco_name = it->second.boundary_name; MapToRegionInfo_t::iterator rit = regionMap.find(region_name); if (rit == regionMap.end()) { ret = false; std::ostringstream os; os << "Region name " << region_name << " does not exist for contact " << contact_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } else { bool boco_found = false; const std::string &genius_region_name = rit->second.genius_region_name; GeniusRegion &genius_region = *(geniusRegionMap[genius_region_name]); boco_found = genius_region.HasBoundary(boco_name); if (!boco_found) { ret = false; std::ostringstream os; os << "Region name " << region_name << " does not have contact " << contact_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } } } } { for (MapToInterfaceInfo_t::iterator it = interfaceMap.begin(); it != interfaceMap.end(); ++it) { const std::string &interface_name = it->first; const std::string &region0_name = it->second.region0; const std::string &region1_name = it->second.region1; const std::string &boco_name = it->second.boundary_name; MapToRegionInfo_t::iterator rit0 = regionMap.find(region0_name); MapToRegionInfo_t::iterator rit1 = regionMap.find(region1_name); if (rit0 == regionMap.end()) { ret = false; std::ostringstream os; os << "Region name " << region0_name << " does not exist for interface " << interface_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } if (rit1 == regionMap.end()) { ret = false; std::ostringstream os; os << "Region name " << region1_name << " does not exist for interface " << interface_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } if (ret) { const std::string &genius_region0_name = rit0->second.genius_region_name; const std::string &genius_region1_name = rit1->second.genius_region_name; GeniusRegion &genius_region0 = *(geniusRegionMap[genius_region0_name]); GeniusRegion &genius_region1 = *(geniusRegionMap[genius_region1_name]); bool boco0_found = genius_region0.HasBoundary(boco_name); if (!boco0_found) { ret = false; std::ostringstream os; os << "Region name " << region0_name << " does not have interface " << interface_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } bool boco1_found = genius_region0.HasBoundary(boco_name); if (!boco1_found) { ret = false; std::ostringstream os; os << "Region name " << region1_name << " does not have interface " << interface_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } if (ret) { if (genius_region0.GetBoundary(boco_name).points.size() != genius_region1.GetBoundary(boco_name).points.size()) { ret = false; std::ostringstream os; os << "Regions " << region0_name << " and " << region1_name << " have point mismatch for interface " << interface_name << ".\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } } } } } for (ShapesMap_t::iterator it = geniusShapesMap.begin(); it != geniusShapesMap.end(); ++it) { Shapes &shapes = it->second; if (shapes.GetNumberOfTypes() != 1) { ret = false; std::ostringstream os; os << "Region name " << it->first << " has multiple element types.\n"; OutputStream::WriteOut(OutputStream::ERROR, os.str()); } else if (shapes.GetDimension() > dimension) { dimension = shapes.GetDimension(); } shapes.DecomposeAndUniquify(); { std::ostringstream os; os << "Region name " << it->first << " has " << shapes.Tetrahedra.size() << " Tetrahedra.\n"; os << "Region name " << it->first << " has " << shapes.Triangles.size() << " Triangles.\n"; os << "Region name " << it->first << " has " << shapes.Lines.size() << " Lines.\n"; os << "Region name " << it->first << " has " << shapes.Points.size() << " Points.\n"; OutputStream::WriteOut(OutputStream::INFO, os.str()); } } errorString += "Check log for errors.\n"; if (ret) { this->SetFinalized(); } return ret; } ObjectHolder GeniusLoader::GetMeshInfo() { ObjectHolderMap_t ret; /* RESISTIVE */ ret["resistive"] = ObjectHolder(GetResistive()); ret["dimension"] = ObjectHolder(static_cast<int>(GetDimension())); std::map<std::string, std::set<std::string> > boundary_to_region; ObjectHolderMap_t regions; ObjectHolderList_t solutions; for (MapToGeniusRegion_t::iterator rit = geniusRegionMap.begin(); rit != geniusRegionMap.end(); ++rit) { const std::string &region_name = rit->first; GeniusRegion &genius_region = *(rit->second); ObjectHolderMap_t region_map; region_map["material"] = ObjectHolder(genius_region.material); ObjectHolderMap_t boundary_map; for (std::vector<GeniusBoundaryPtr>::iterator bit = genius_region.bocos.begin(); bit != genius_region.bocos.end(); ++bit) { std::string name = (*bit)->name; if (!(*bit)->label.empty()) { name = (*bit)->label; } boundary_map[name] = ObjectHolder((*bit)->has_electrode); boundary_to_region[name].insert(region_name); } region_map["boundary_info"] = ObjectHolder(boundary_map); /* map keys are automatically sorted */ solutions.clear(); for (std::map<std::string, std::vector<double> >::iterator sit = genius_region.solutions.begin(); sit != genius_region.solutions.end(); ++sit) { solutions.push_back(ObjectHolder(sit->first)); } region_map["solutions"] = ObjectHolder(solutions); regions[region_name] = ObjectHolder(region_map); } ret["regions"] = ObjectHolder(regions); ObjectHolderMap_t bmap; ObjectHolderList_t ohl; for (std::map<std::string, std::set<std::string> >::iterator it = boundary_to_region.begin(); it != boundary_to_region.end(); ++it) { ohl.clear(); std::set<std::string> &region_names = it->second; for (std::set<std::string>::iterator jt = region_names.begin(); jt != region_names.end(); ++jt) { ohl.push_back(ObjectHolder(*jt)); } bmap[it->first] = ObjectHolder(ohl); } ret["boundaries"] = ObjectHolder(bmap); return ObjectHolder(ret); } bool GeniusRegion::HasBoundary(const std::string &boundary) const { bool ret = false; for (size_t i = 0; i < bocos.size(); ++i) { if (bocos[i]->label == boundary) { ret = true; break; } else if (bocos[i]->name == boundary) { ret = true; break; } } return ret; } GeniusBoundary &GeniusRegion::GetBoundary(const std::string &name) { // boundary not existing is not defined size_t index = size_t(-1); for (size_t i = 0; i < bocos.size(); ++i) { if (bocos[i]->label == name) { index = i; break; } else if (bocos[i]->name == name) { index = i; break; } } return *(bocos[index]); } }
32.083721
148
0.616338
[ "mesh", "vector" ]
12e9945547438e606468f303fd21cb267ac614c9
1,509
cpp
C++
LeetCode/Process Restricted Friend Requests/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
LeetCode/Process Restricted Friend Requests/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
LeetCode/Process Restricted Friend Requests/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
class Solution { vector<int> parent; void init(int n) { parent.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; } } int representative(int u) { while (u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } void merge(int u, int v) { int ru = representative(u); int rv = representative(v); if (ru != rv) { parent[ru] = rv; } } public: vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) { init(n); vector<bool> ans; for (const auto &request : requests) { int u = request[0]; int v = request[1]; int pu = representative(u); int pv = representative(v); bool good = true; if (pu != pv) { for (const auto &restriction : restrictions) { int a = restriction[0]; int b = restriction[1]; int pa = representative(a); int pb = representative(b); if ((pa == pu and pb == pv) or (pa == pv and pb == pu)) { good = false; break; } } } if (good) { merge(u, v); } ans.push_back(good); } return ans; } };
26.946429
106
0.404241
[ "vector" ]
12f50e0f8ce8f293e350d4bd28f81cc28404a481
1,807
cpp
C++
examples/get_rgb_demo.cpp
ManuelMeraz/pixy2_example
1498976a41407c8a3b1eb4ea73f661887712e677
[ "MIT" ]
2
2021-04-13T20:55:53.000Z
2021-12-23T00:35:46.000Z
examples/get_rgb_demo.cpp
ManuelMeraz/pixy2_example
1498976a41407c8a3b1eb4ea73f661887712e677
[ "MIT" ]
null
null
null
examples/get_rgb_demo.cpp
ManuelMeraz/pixy2_example
1498976a41407c8a3b1eb4ea73f661887712e677
[ "MIT" ]
null
null
null
// // begin license header // // This file is part of Pixy CMUcam5 or "Pixy" for short // // All Pixy source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Pixy source code, software and/or // technologies under different licensing terms should contact us at // cmucam@cs.cmu.edu. Such licensing terms are available for // all portions of the Pixy codebase presented here. // // end license header // #include <signal.h> #include "libpixyusb2.h" Pixy2 pixy; static bool run_flag = true; void handle_SIGINT(int unused) { // On CTRL+C - abort! // run_flag = false; } int main() { int Result; uint8_t r, g, b; // Catch CTRL+C (SIGINT) signals, otherwise the Pixy object // won't be cleaned up correctly, leaving Pixy and possibly USB // driver in a defunct state. signal (SIGINT, handle_SIGINT); printf ("=============================================================\n"); printf ("= PIXY2 Get RGB values demo =\n"); printf ("=============================================================\n"); printf ("Connecting to Pixy2..."); // Initialize Pixy2 Connection // { Result = pixy.init(); if (Result < 0) { printf ("Error\n"); printf ("pixy.init() returned %d\n", Result); return Result; } printf ("Success\n"); } // Get Pixy2 Version information // { Result = pixy.getVersion(); if (Result < 0) { printf ("pixy.getVersion() returned %d\n", Result); return Result; } pixy.version->print(); } while(run_flag) { pixy.video.getRGB(158, 104, &r, &g, &b); printf("r:%hhu g:%hhu b:%hhu\n", r, g, b); } printf ("PIXY2 Get RGB Demo Exit\n"); }
21.771084
77
0.570006
[ "object" ]
12fc5954e142a14920d9239389260eb59b41fdf7
16,777
hpp
C++
src/messaging/server.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
61
2015-01-08T08:05:28.000Z
2022-01-07T16:47:47.000Z
src/messaging/server.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
30
2015-04-06T21:41:18.000Z
2021-08-18T13:24:51.000Z
src/messaging/server.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
64
2015-02-23T20:01:11.000Z
2022-03-14T13:31:20.000Z
#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _SRC_SERVER_HPP_ #define _SRC_SERVER_HPP_ #include <boost/thread/recursive_mutex.hpp> #include <boost/noncopyable.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include "boundobject.hpp" #include "authprovider_p.hpp" namespace qi { namespace detail { namespace server { /// Wraps a socket with its server specific information, such as an authentication state and /// automatizes the connection/disconnection of a handler for server messages. class SocketInfo { public: // NonCopyable: SocketInfo(const SocketInfo&) = delete; SocketInfo& operator=(const SocketInfo&) = delete; // SocketInfo: SocketInfo(const MessageSocketPtr& socket, SignalSubscriber onDisconnected, AuthProviderPtr authProvider = {}) noexcept; ~SocketInfo(); MessageSocketPtr socket() const noexcept { return _socket.lock(); } /// @invariant `(x.setAuthenticated(), x.isAuthenticated()) == true` void setAuthenticated() noexcept { _authenticated = true; } bool isAuthenticated() const noexcept{ return _authenticated; } /// @post `extractCapabilities().empty()` CapabilityMap extractCapabilities(); /// @invariant `(x.setAuthProvider(p), x.authProvider()) == p` void setAuthProvider(AuthProviderPtr prov) noexcept { _authProvider = std::move(prov); } AuthProviderPtr authProvider() const noexcept { return _authProvider; } /// Adds a message handler for server specific messages. /// @throws A `std::logic_error` exception if an handler was already set. void setServerMessageHandler(MessageDispatcher::MessageHandler handler); struct Tracker : qi::Trackable<Tracker> { using Trackable::destroy; }; Tracker tracker; private: const MessageSocketWeakPtr _socket; const qi::SignalLink _disconnected = qi::SignalBase::invalidSignalLink; AuthProviderPtr _authProvider; boost::optional<MessageDispatchConnection> _msgDispatchConnection; bool _authenticated = false; bool _capabilitiesTaken = false; }; using SocketInfoPtr = std::unique_ptr<SocketInfo>; /// Helper class that simplifies the creation and destruction of bindings between service bound /// objects and sockets. It automatically binds each object with each socket that it stores. class BoundObjectSocketBinder { using SocketInfoList = std::vector<SocketInfoPtr>; using BoundObjectPtrMap = boost::container::flat_map<unsigned int, BoundObjectPtr>; using BoundObjectSocketBindingList = std::vector<detail::boundObject::SocketBinding>; public: // NonCopyable: BoundObjectSocketBinder(const BoundObjectSocketBinder&) = delete; BoundObjectSocketBinder& operator=(const BoundObjectSocketBinder&) = delete; // BoundObjectSocketBinder: BoundObjectSocketBinder() noexcept; /// A socket must be validated before it is bound to the objects. Usually a validation /// requires an authentication success. /// @throws A `std::logic_error` exception if the socket already exists in this binder. SocketInfo& addSocketPendingValidation(const MessageSocketPtr& socket, SignalSubscriber disconnectionHandlerAnyFunc); /// Removes a socket and unbinds it from the objects. /// @returns True if the socket existed in this binder and was succesfully removed. bool removeSocket(const MessageSocketPtr& socket) noexcept; /// Validates the socket and binds it to the objects. /// @returns The number of bindings that were created. std::size_t validateSocket(const MessageSocketPtr& socket) noexcept; struct ClearSocketsResult { std::size_t socketCount; std::size_t bindingCount; KA_GENERATE_FRIEND_REGULAR_OPS_2(ClearSocketsResult, socketCount, bindingCount) }; /// Removes all sockets and consequently all existing bindings. /// @returns A result containing the number of socket that were removed and disconnected and /// the number of bindings destroyed. /// @post `socketsInfo().empty()` ClearSocketsResult clearSockets() noexcept; const SocketInfoList& socketsInfo() const { return _socketsInfo; } /// Adds a service bound object and binds it to the sockets. /// @returns True if an object did not exist already for this service id and the object was /// successfully added. bool addObject(unsigned int serviceId, BoundObjectPtr object) noexcept; /// Removes a service bound object and unbinds it from the sockets. /// @returns True if an object existed for this service id and it was successfully removed. bool removeObject(unsigned int serviceId) noexcept; const BoundObjectPtrMap& boundObjects() const { return _boundObjects; } private: /// @returns The number of bindings that were created. std::size_t bindObject(const BoundObjectPtr& object) noexcept; /// @returns The number of bindings that were created. std::size_t bindSocket(const MessageSocketPtr& socket) noexcept; /// @returns The number of bindings that were destroyed. std::size_t unbindSocket(const MessageSocketPtr& socket) noexcept; /// @returns The number of bindings that were destroyed. std::size_t unbindObject(const BoundObjectPtr& object) noexcept; BoundObjectPtrMap _boundObjects; SocketInfoList _socketsInfo; BoundObjectSocketBindingList _bindings; }; } } /// Wraps a transport server and ensures the binding between service bound objects and message /// sockets. It handles messages of the protocol destinated to the "Server" of a endpoint, which /// includes the authentication of clients and exchange of protocol capabilities. /// /// The kinematics of server messages processing are as follows: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// ╔═══════════════════════════╗ /// ║ Socket received message { ║ /// ║ service: Server(0) ║ /// ║ object: None(0) ║ /// ║ } ║ /// ╚════════════╤══════════════╝ /// ▼ /// ╔════════════════════╧══════════════════════╗ /// ║ must_auth = Is authentication required ? ║ /// ╟───────────────────────────────────────────╢ /// ║ is_auth = message.type == Call(1) and ║ /// ║ message.action == Authenticate(8) ? ║ /// ╚════════════════╤════════╤═════════════════╝ /// must_auth = yes ┤ ├ must_auth = no /// ╎ ╎ /// ┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌┘ └╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐ /// ╎ ╎ ╎ ╎ /// ├ is_auth ├ is_auth ├ is_auth ├ is_auth /// ╎ = yes ╎ = no ╎ = yes ╎ = no /// ╎ ╎ ╎ ╎ /// ╎ ▼ ╎ ▼ /// ╎ ╔═══════════╧═══════════╗ ╎ ╔═══════════╧═══════════╗ /// ╎ ║ Socket send message { ║ ╎ ║ Socket send message { ║ /// ╎ ║ type: Error(3) ║ ╎ ║ type: Capability(6) ║ /// ╎ ║ service: Server(0) ║ ╎ ║ service: Server(0) ║ /// ╎ ║ object: None(0) ║ ╎ ║ value: { ║ /// ╎ ║ } ║ ╎ ║ <capabilities> ║ /// ╎ ╚═══════════╤═══════════╝ ╎ ║ } ║ /// ▼ └╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐ ╎ ║ } ║ /// ╔════════╧══════════════════════╗ ╎ ╎ ╚═══════════╤═══════════╝ /// ║ Is pair message.auth_user ║ ╎ ╎ ╎ /// ║ message.auth_password valid ? ║ ╎ ╎ ╎ /// ╚════════╤═══════════════╤══════╝ ╎ ╎ ╎ /// yes ┤ no ┤ ╎ ╎ ╎ /// ╎ ▼ ╎ ╎ ╎ /// ╎ ╔════════════╧═════════════╗ ╎ ╎ ╎ /// ╎ ║ Socket send message { ║ ╎ ╎ ╎ /// ╎ ║ type: Error(3) ║ ╎ ╎ ╎ /// ╎ ║ service: Server(0) ║ ╎ ╎ ╎ /// ╎ ║ object: None(0) ║ ╎ ╎ ╎ /// ╎ ║ value: { ║ ╎ ╎ ╎ /// ╎ ║ auth_state: Error(1) ║ ╎ ╎ ╎ /// ╎ ║ } ║ ╎ ╎ ╎ /// ╎ ║ } ║ ╎ ╎ ╎ /// ╎ ╚════════════╤═════════════╝ ╎ ╎ ╎ /// ╎ ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ ╎ ╎ /// ╎ ▼ ╎ ╎ /// ╎ ╔═════════╧═════════╗ ╎ ╎ /// ╎ ║ Disconnect socket ║ ╎ ╎ /// ╎ ╚═══════════════════╝ ╎ ╎ /// └╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ ╎ /// ▼ ╎ /// ╔════════════╧════════════╗ ╎ /// ║ Socket send message { ║ ╎ /// ║ type: Reply(2) ║ ╎ /// ║ service: Server(0) ║ ╎ /// ║ object: None(0) ║ ╎ /// ║ value: { ║ ╎ /// ║ auth_state: Done(3) ║ ╎ /// ║ } ║ ╎ /// ║ } ║ ╎ /// ╚════════════╤════════════╝ ╎ /// └╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ /// ▼ /// ╔═════════════════╧════════════════╗ /// ║ Ignore further socket messages { ║ /// ║ service: Server(0) ║ /// ║ object: None(0) ║ /// ║ } ║ /// ╚══════════════════════════════════╝ /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// class Server : private boost::noncopyable { public: Server(bool enforceAuth = false); ~Server(); /// @see `TransportServer::listen` /// @post The server is not dying. qi::Future<void> listen(const qi::Url& address); /// @see `TransportServer::close` /// @post The server is dying. Future<void> close(); /// Notifies the server that it's up again. /// @post The server is not dying. Future<bool> open(); /// @see `TransportServer::setIdentity` Future<bool> setIdentity(const std::string& key, const std::string& crt); /// @returns True if the object is not null, an object did not exist already for this service id /// and the object was succesfully added. Future<bool> addObject(unsigned int serviceId, qi::AnyObject obj); Future<bool> addObject(unsigned int serviceId, qi::BoundObjectPtr obj); /// @returns True if an object existed for this service id and it was succesfully removed. Future<bool> removeObject(unsigned int idx); /// Adds an outgoing socket (a socket that was connected to a remote server endpoint instead of /// the usual listening server sockets). This allows service bounds objects to process messages /// coming from such sockets. /// @returns True if the socket started accepting messages. /// @throws /// - A `std::invalid_argument` exception if the socket is null. Future<bool> addOutgoingSocket(MessageSocketPtr socket); /// @see `TransportServer::endpoints` Future<UrlVector> endpoints() const; Future<void> setAuthProviderFactory(AuthProviderFactoryPtr factory); private: using SocketInfo = detail::server::SocketInfo; using BoundObjectSocketBinder = detail::server::BoundObjectSocketBinder; void closeImpl(); /// Adds an incoming socket (a socket created from a client connecting to the server), /// optionally requiring authentication. /// @returns True if the socket started accepting messages. /// @pre The function is executed in the context of the strand. /// @throws /// - A `std::invalid_argument` exception if the socket is null. bool addIncomingSocket(MessageSocketPtr socket); /// @pre The function is executed in the context of the strand. /// @returns true if a reply was sent to the client. bool handleServerMessage(const Message& msg, SocketInfo& socketInfo); /// @pre The function is executed in the context of the strand. /// @pre `_enforceAuth == true` /// @returns true if a reply was sent to the client. bool handleServerMessageAuth(const Message& msg, SocketInfo& socketInfo); /// @pre The function is executed in the context of the strand. /// @pre `_enforceAuth == false` /// @returns true if a reply was sent to the client. bool handleServerMessageNoAuth(const Message& msg, SocketInfo& socketInfo); /// @pre The function is executed in the context of the strand. /// @returns true if a reply was sent to the client. bool authenticateSocket(const qi::Message& msg, SocketInfo& socketInfo, Message reply); /// @pre The function is executed in the context of the strand. void finalizeSocketAuthentication(SocketInfo& socketInfo) noexcept; struct SendAuthErrorResult { bool errorSent; Future<void> disconnected; KA_GENERATE_FRIEND_REGULAR_OPS_2(SendAuthErrorResult, errorSent, disconnected) }; static SendAuthErrorResult sendAuthError(std::string error, MessageSocket& socket, Message reply); static bool sendAuthReply(CapabilityMap authResult, SocketInfo& socketInfo, Message reply); static bool sendSuccessfulAuthReply(SocketInfo& socketInfo, Message reply); static bool sendCapabilitiesMessage(SocketInfo& socketInfo); struct RemoveSocketResult { bool removed; Future<void> disconnected; KA_GENERATE_FRIEND_REGULAR_OPS_2(RemoveSocketResult, removed, disconnected) }; /// @see `BoundObjectSocketBinder::removeSocket` /// @pre `socket != nullptr` /// @pre The function is executed in the context of the strand. /// @returns A struct containing a boolean stating if the socket existed in the server and was /// succesfully removed and a future of the socket disconnection result. RemoveSocketResult removeSocket(const MessageSocketPtr& socket); // Mutable state of the object. struct State { AuthProviderFactoryPtr authProviderFactory; BoundObjectSocketBinder binder; }; State _state; boost::shared_ptr<Strand> _strand = boost::make_shared<Strand>(); struct Tracker : qi::Trackable<Tracker> { using Trackable::destroy; }; Tracker _tracker; template<typename R> static Future<R> serverClosedError() { return makeFutureError<R>("The server is closed."); } template< typename Proc1, typename Result = ka::Decay<decltype(std::declval<Proc1>()())>, typename Proc2 = decltype(serverClosedError<Result>)> Future<Result> safeCall(Proc1&& proc, Proc2&& onFail = serverClosedError<Result>) const { if (auto ptr = boost::atomic_load(&_strand)) return ptr->async(std::forward<Proc1>(proc)); else return std::forward<Proc2>(onFail)(); } /// @pre The function is executed in the context of the strand. /// @throws /// - A `std::invalid_argument` exception if the socket is null. SocketInfo& addSocket(MessageSocketPtr socket); protected: const bool _enforceAuth; TransportServer _server; const qi::MetaCallType _defaultCallType; }; } #endif // _SRC_SERVER_HPP_
44.501326
101
0.523336
[ "object", "vector" ]
12fc98fe3babbff3dabb1d9409a6895960cc24f9
13,091
cpp
C++
benchmarks.cpp
stryku/branchless_enum
7f52ad6cc143db23ed50eac1d57812891f578604
[ "MIT" ]
null
null
null
benchmarks.cpp
stryku/branchless_enum
7f52ad6cc143db23ed50eac1d57812891f578604
[ "MIT" ]
null
null
null
benchmarks.cpp
stryku/branchless_enum
7f52ad6cc143db23ed50eac1d57812891f578604
[ "MIT" ]
null
null
null
#include "include/branchless_enum.hpp" #include <chrono> #include <vector> #include <iostream> #include <random> branchless_enum(branchless, name_1, name_2, name_3, name_4, name_5, name_6, name_7, name_8, name_9, name_10, name_11, name_12, name_13, name_14, name_15, name_16, name_17, name_18, name_19); template <typename Clock> struct BenchmarkResult { struct Duration { using tp = std::chrono::time_point<Clock>; tp start; tp finnish; }; Duration create; Duration fill; Duration fromString; Duration toString; Duration function; static auto elapsed(const Duration &d) { return std::chrono::duration_cast<std::chrono::milliseconds>(d.finnish - d.start); } }; #pragma optimize( "", off ) struct BranchlessFunction : public boost::static_visitor<> { public: void operator()(branchless::Types::name_1) const {} void operator()(branchless::Types::name_2) const {} void operator()(branchless::Types::name_3) const {} void operator()(branchless::Types::name_4) const {} void operator()(branchless::Types::name_5) const {} void operator()(branchless::Types::name_6) const {} void operator()(branchless::Types::name_7) const {} void operator()(branchless::Types::name_8) const {} void operator()(branchless::Types::name_9) const {} void operator()(branchless::Types::name_10) const {} void operator()(branchless::Types::name_11) const {} void operator()(branchless::Types::name_12) const {} void operator()(branchless::Types::name_13) const {} void operator()(branchless::Types::name_14) const {} void operator()(branchless::Types::name_15) const {} void operator()(branchless::Types::name_16) const {} void operator()(branchless::Types::name_17) const {} void operator()(branchless::Types::name_18) const {} void operator()(branchless::Types::name_19) const {} }; #pragma optimize( "", on ) namespace branch_namespace { enum class BranchEnum { NAME_1, NAME_2, NAME_3, NAME_4, NAME_5, NAME_6, NAME_7, NAME_8, NAME_9, NAME_10, NAME_11, NAME_12, NAME_13, NAME_14, NAME_15, NAME_16, NAME_17, NAME_18, NAME_19 }; constexpr auto toString(BranchEnum en) { return (en == BranchEnum::NAME_1) ? "NAME_1" : (en == BranchEnum::NAME_2) ? "NAME_2" : (en == BranchEnum::NAME_3) ? "NAME_3" : (en == BranchEnum::NAME_4) ? "NAME_4" : (en == BranchEnum::NAME_5) ? "NAME_5" : (en == BranchEnum::NAME_6) ? "NAME_6" : (en == BranchEnum::NAME_7) ? "NAME_7" : (en == BranchEnum::NAME_8) ? "NAME_8" : (en == BranchEnum::NAME_9) ? "NAME_9" : (en == BranchEnum::NAME_10) ? "NAME_10" : (en == BranchEnum::NAME_11) ? "NAME_11" : (en == BranchEnum::NAME_12) ? "NAME_12" : (en == BranchEnum::NAME_13) ? "NAME_13" : (en == BranchEnum::NAME_14) ? "NAME_14" : (en == BranchEnum::NAME_15) ? "NAME_15" : (en == BranchEnum::NAME_16) ? "NAME_16" : (en == BranchEnum::NAME_17) ? "NAME_17" : (en == BranchEnum::NAME_18) ? "NAME_18" : (en == BranchEnum::NAME_19) ? "NAME_19" : ""; } BranchEnum fromString(const std::string &str) { if (str == "NAME_1") return BranchEnum::NAME_1; if (str == "NAME_2") return BranchEnum::NAME_2; if (str == "NAME_3") return BranchEnum::NAME_3; if (str == "NAME_4") return BranchEnum::NAME_4; if (str == "NAME_5") return BranchEnum::NAME_5; if (str == "NAME_6") return BranchEnum::NAME_6; if (str == "NAME_7") return BranchEnum::NAME_7; if (str == "NAME_8") return BranchEnum::NAME_8; if (str == "NAME_9") return BranchEnum::NAME_9; if (str == "NAME_10") return BranchEnum::NAME_10; if (str == "NAME_11") return BranchEnum::NAME_11; if (str == "NAME_12") return BranchEnum::NAME_12; if (str == "NAME_13") return BranchEnum::NAME_13; if (str == "NAME_14") return BranchEnum::NAME_14; if (str == "NAME_15") return BranchEnum::NAME_15; if (str == "NAME_16") return BranchEnum::NAME_16; if (str == "NAME_17") return BranchEnum::NAME_17; if (str == "NAME_18") return BranchEnum::NAME_18; if (str == "NAME_19") return BranchEnum::NAME_19; } } #pragma optimize( "", off ) void branchFunction(branch_namespace::BranchEnum type) { switch (type) { case branch_namespace::BranchEnum::NAME_1: {} break; case branch_namespace::BranchEnum::NAME_2: {} break; case branch_namespace::BranchEnum::NAME_3: {} break; case branch_namespace::BranchEnum::NAME_4: {} break; case branch_namespace::BranchEnum::NAME_5: {} break; case branch_namespace::BranchEnum::NAME_6: {} break; case branch_namespace::BranchEnum::NAME_7: {} break; case branch_namespace::BranchEnum::NAME_8: {} break; case branch_namespace::BranchEnum::NAME_9: {} break; case branch_namespace::BranchEnum::NAME_10: {} break; case branch_namespace::BranchEnum::NAME_11: {} break; case branch_namespace::BranchEnum::NAME_12: {} break; case branch_namespace::BranchEnum::NAME_13: {} break; case branch_namespace::BranchEnum::NAME_14: {} break; case branch_namespace::BranchEnum::NAME_15: {} break; case branch_namespace::BranchEnum::NAME_16: {} break; case branch_namespace::BranchEnum::NAME_17: {} break; case branch_namespace::BranchEnum::NAME_18: {} break; case branch_namespace::BranchEnum::NAME_19: {} break; } } #pragma optimize( "", on ) void benchmark(const size_t N) { using Clock = std::chrono::steady_clock; BenchmarkResult<Clock> branchless_results; BenchmarkResult<Clock> branch; branch.create.start = Clock::now(); std::vector<branch_namespace::BranchEnum> branchVector(N); branch.create.finnish = Clock::now(); branchless_results.create.start = Clock::now(); std::vector<branchless::Type> branchlessVector(N); branchless_results.create.finnish = Clock::now(); std::vector<std::string> strVector(N); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(1, 19); branch.fill.start = Clock::now(); for (size_t i = 0; i < N; ++i) { switch (uniform_dist(e1)) { case 1: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 2: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 3: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 4: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 5: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 6: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 7: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 8: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 9: branchVector[i] = branch_namespace::BranchEnum::NAME_1; break; case 10: branchVector[i] = branch_namespace::BranchEnum::NAME_10; break; case 11: branchVector[i] = branch_namespace::BranchEnum::NAME_11; break; case 12: branchVector[i] = branch_namespace::BranchEnum::NAME_12; break; case 13: branchVector[i] = branch_namespace::BranchEnum::NAME_13; break; case 14: branchVector[i] = branch_namespace::BranchEnum::NAME_14; break; case 15: branchVector[i] = branch_namespace::BranchEnum::NAME_15; break; case 16: branchVector[i] = branch_namespace::BranchEnum::NAME_16; break; case 17: branchVector[i] = branch_namespace::BranchEnum::NAME_17; break; case 18: branchVector[i] = branch_namespace::BranchEnum::NAME_18; break; case 19: branchVector[i] = branch_namespace::BranchEnum::NAME_19; break; } } branch.fill.finnish = Clock::now(); branchless_results.fill.start = Clock::now(); for (size_t i = 0; i < N; ++i) { switch (uniform_dist(e1)) { case 1: branchlessVector[i] = branchless::Types::name_1{}; break; case 2: branchlessVector[i] = branchless::Types::name_2{}; break; case 3: branchlessVector[i] = branchless::Types::name_3{}; break; case 4: branchlessVector[i] = branchless::Types::name_4{}; break; case 5: branchlessVector[i] = branchless::Types::name_5{}; break; case 6: branchlessVector[i] = branchless::Types::name_6{}; break; case 7: branchlessVector[i] = branchless::Types::name_7{}; break; case 8: branchlessVector[i] = branchless::Types::name_8{}; break; case 9: branchlessVector[i] = branchless::Types::name_9{}; break; case 10: branchlessVector[i] = branchless::Types::name_10{}; break; case 11: branchlessVector[i] = branchless::Types::name_11{}; break; case 12: branchlessVector[i] = branchless::Types::name_12{}; break; case 13: branchlessVector[i] = branchless::Types::name_13{}; break; case 14: branchlessVector[i] = branchless::Types::name_14{}; break; case 15: branchlessVector[i] = branchless::Types::name_15{}; break; case 16: branchlessVector[i] = branchless::Types::name_16{}; break; case 17: branchlessVector[i] = branchless::Types::name_17{}; break; case 18: branchlessVector[i] = branchless::Types::name_18{}; break; case 19: branchlessVector[i] = branchless::Types::name_19{}; break; } } branchless_results.fill.finnish = Clock::now(); branch.toString.start = Clock::now(); std::transform(std::begin(branchVector), std::end(branchVector), std::begin(strVector), [](const auto &el) { return branch_namespace::toString(el); }); branch.toString.finnish = Clock::now(); branch.fromString.start = Clock::now(); std::transform(std::begin(strVector), std::end(strVector), std::begin(branchVector), [](const auto &el) { return branch_namespace::fromString(el); }); branch.fromString.finnish = Clock::now(); branchless_results.toString.start = Clock::now(); std::transform(std::begin(branchlessVector), std::end(branchlessVector), std::begin(strVector), [](const auto &el) { return branchless::toString(el); }); branchless_results.toString.finnish = Clock::now(); branchless_results.fromString.start = Clock::now(); std::transform(std::begin(strVector), std::end(strVector), std::begin(branchlessVector), [](const auto &el) { return branchless::fromString(el); }); branchless_results.fromString.finnish = Clock::now(); branchless_results.function.start = Clock::now(); BranchlessFunction bf; for (const auto &el : branchlessVector) boost::apply_visitor(bf, el); branchless_results.function.finnish = Clock::now(); branch.function.start = Clock::now(); for (const auto &el : branchVector) branchFunction(el); branch.function.finnish = Clock::now(); std::cout << "BRANCH\n"; std::cout << "creation:\t" << BenchmarkResult<Clock>::elapsed(branch.create).count() << "\n"; std::cout << "fill:\t" << BenchmarkResult<Clock>::elapsed(branch.fill).count() << "\n"; std::cout << "fromString:\t" << BenchmarkResult<Clock>::elapsed(branch.fromString).count() << "\n"; std::cout << "toString:\t" << BenchmarkResult<Clock>::elapsed(branch.toString).count() << "\n"; std::cout << "function:\t" << BenchmarkResult<Clock>::elapsed(branch.function).count() << "\n\n"; std::cout << "BRANCHLESS\n"; std::cout << "creation:\t" << BenchmarkResult<Clock>::elapsed(branchless_results.create).count() << "\n"; std::cout << "fill:\t" << BenchmarkResult<Clock>::elapsed(branchless_results.fill).count() << "\n"; std::cout << "fromString:\t" << BenchmarkResult<Clock>::elapsed(branchless_results.fromString).count() << "\n"; std::cout << "toString:\t" << BenchmarkResult<Clock>::elapsed(branchless_results.toString).count() << "\n"; std::cout << "function:\t" << BenchmarkResult<Clock>::elapsed(branchless_results.function).count() << "\n"; } int main() { size_t N; std::cout << "N: "; std::cin >> N; benchmark(N); return 0; }
39.312312
115
0.606371
[ "vector", "transform" ]
12ffc084d7fda3d2361534d9eb42cbc7a9c85b94
17,950
cc
C++
Models/CommonStateSignalAuthorChatCall.pb.cc
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
Models/CommonStateSignalAuthorChatCall.pb.cc
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
Models/CommonStateSignalAuthorChatCall.pb.cc
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CommonStateSignalAuthorChatCall.proto #include "CommonStateSignalAuthorChatCall.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_AuthorChatPlayerInfo_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_AuthorChatPlayerInfo_AuthorChatPlayerInfo_2eproto; namespace AcFunDanmu { class CommonStateSignalAuthorChatCallDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CommonStateSignalAuthorChatCall> _instance; } _CommonStateSignalAuthorChatCall_default_instance_; } // namespace AcFunDanmu static void InitDefaultsscc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::AcFunDanmu::_CommonStateSignalAuthorChatCall_default_instance_; new (ptr) ::AcFunDanmu::CommonStateSignalAuthorChatCall(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto}, { &scc_info_AuthorChatPlayerInfo_AuthorChatPlayerInfo_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_CommonStateSignalAuthorChatCall_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_CommonStateSignalAuthorChatCall_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_CommonStateSignalAuthorChatCall_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_CommonStateSignalAuthorChatCall_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::AcFunDanmu::CommonStateSignalAuthorChatCall, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::AcFunDanmu::CommonStateSignalAuthorChatCall, authorchatid_), PROTOBUF_FIELD_OFFSET(::AcFunDanmu::CommonStateSignalAuthorChatCall, inviteruserinfo_), PROTOBUF_FIELD_OFFSET(::AcFunDanmu::CommonStateSignalAuthorChatCall, calltimestampms_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::AcFunDanmu::CommonStateSignalAuthorChatCall)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::AcFunDanmu::_CommonStateSignalAuthorChatCall_default_instance_), }; const char descriptor_table_protodef_CommonStateSignalAuthorChatCall_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n%CommonStateSignalAuthorChatCall.proto\022" "\nAcFunDanmu\032\032AuthorChatPlayerInfo.proto\"" "\213\001\n\037CommonStateSignalAuthorChatCall\022\024\n\014a" "uthorChatId\030\001 \001(\t\0229\n\017inviterUserInfo\030\002 \001" "(\0132 .AcFunDanmu.AuthorChatPlayerInfo\022\027\n\017" "callTimestampMs\030\003 \001(\003b\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_CommonStateSignalAuthorChatCall_2eproto_deps[1] = { &::descriptor_table_AuthorChatPlayerInfo_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_CommonStateSignalAuthorChatCall_2eproto_sccs[1] = { &scc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_CommonStateSignalAuthorChatCall_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_CommonStateSignalAuthorChatCall_2eproto = { false, false, descriptor_table_protodef_CommonStateSignalAuthorChatCall_2eproto, "CommonStateSignalAuthorChatCall.proto", 229, &descriptor_table_CommonStateSignalAuthorChatCall_2eproto_once, descriptor_table_CommonStateSignalAuthorChatCall_2eproto_sccs, descriptor_table_CommonStateSignalAuthorChatCall_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_CommonStateSignalAuthorChatCall_2eproto::offsets, file_level_metadata_CommonStateSignalAuthorChatCall_2eproto, 1, file_level_enum_descriptors_CommonStateSignalAuthorChatCall_2eproto, file_level_service_descriptors_CommonStateSignalAuthorChatCall_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_CommonStateSignalAuthorChatCall_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_CommonStateSignalAuthorChatCall_2eproto)), true); namespace AcFunDanmu { // =================================================================== class CommonStateSignalAuthorChatCall::_Internal { public: static const ::AcFunDanmu::AuthorChatPlayerInfo& inviteruserinfo(const CommonStateSignalAuthorChatCall* msg); }; const ::AcFunDanmu::AuthorChatPlayerInfo& CommonStateSignalAuthorChatCall::_Internal::inviteruserinfo(const CommonStateSignalAuthorChatCall* msg) { return *msg->inviteruserinfo_; } void CommonStateSignalAuthorChatCall::clear_inviteruserinfo() { if (GetArena() == nullptr && inviteruserinfo_ != nullptr) { delete inviteruserinfo_; } inviteruserinfo_ = nullptr; } CommonStateSignalAuthorChatCall::CommonStateSignalAuthorChatCall(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:AcFunDanmu.CommonStateSignalAuthorChatCall) } CommonStateSignalAuthorChatCall::CommonStateSignalAuthorChatCall(const CommonStateSignalAuthorChatCall& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); authorchatid_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_authorchatid().empty()) { authorchatid_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_authorchatid(), GetArena()); } if (from._internal_has_inviteruserinfo()) { inviteruserinfo_ = new ::AcFunDanmu::AuthorChatPlayerInfo(*from.inviteruserinfo_); } else { inviteruserinfo_ = nullptr; } calltimestampms_ = from.calltimestampms_; // @@protoc_insertion_point(copy_constructor:AcFunDanmu.CommonStateSignalAuthorChatCall) } void CommonStateSignalAuthorChatCall::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto.base); authorchatid_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&inviteruserinfo_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&calltimestampms_) - reinterpret_cast<char*>(&inviteruserinfo_)) + sizeof(calltimestampms_)); } CommonStateSignalAuthorChatCall::~CommonStateSignalAuthorChatCall() { // @@protoc_insertion_point(destructor:AcFunDanmu.CommonStateSignalAuthorChatCall) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void CommonStateSignalAuthorChatCall::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); authorchatid_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete inviteruserinfo_; } void CommonStateSignalAuthorChatCall::ArenaDtor(void* object) { CommonStateSignalAuthorChatCall* _this = reinterpret_cast< CommonStateSignalAuthorChatCall* >(object); (void)_this; } void CommonStateSignalAuthorChatCall::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void CommonStateSignalAuthorChatCall::SetCachedSize(int size) const { _cached_size_.Set(size); } const CommonStateSignalAuthorChatCall& CommonStateSignalAuthorChatCall::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CommonStateSignalAuthorChatCall_CommonStateSignalAuthorChatCall_2eproto.base); return *internal_default_instance(); } void CommonStateSignalAuthorChatCall::Clear() { // @@protoc_insertion_point(message_clear_start:AcFunDanmu.CommonStateSignalAuthorChatCall) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; authorchatid_.ClearToEmpty(); if (GetArena() == nullptr && inviteruserinfo_ != nullptr) { delete inviteruserinfo_; } inviteruserinfo_ = nullptr; calltimestampms_ = PROTOBUF_LONGLONG(0); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* CommonStateSignalAuthorChatCall::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // string authorChatId = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_authorchatid(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId")); CHK_(ptr); } else goto handle_unusual; continue; // .AcFunDanmu.AuthorChatPlayerInfo inviterUserInfo = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_inviteruserinfo(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // int64 callTimestampMs = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { calltimestampms_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* CommonStateSignalAuthorChatCall::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:AcFunDanmu.CommonStateSignalAuthorChatCall) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string authorChatId = 1; if (this->authorchatid().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_authorchatid().data(), static_cast<int>(this->_internal_authorchatid().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId"); target = stream->WriteStringMaybeAliased( 1, this->_internal_authorchatid(), target); } // .AcFunDanmu.AuthorChatPlayerInfo inviterUserInfo = 2; if (this->has_inviteruserinfo()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::inviteruserinfo(this), target, stream); } // int64 callTimestampMs = 3; if (this->calltimestampms() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(3, this->_internal_calltimestampms(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:AcFunDanmu.CommonStateSignalAuthorChatCall) return target; } size_t CommonStateSignalAuthorChatCall::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:AcFunDanmu.CommonStateSignalAuthorChatCall) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string authorChatId = 1; if (this->authorchatid().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_authorchatid()); } // .AcFunDanmu.AuthorChatPlayerInfo inviterUserInfo = 2; if (this->has_inviteruserinfo()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *inviteruserinfo_); } // int64 callTimestampMs = 3; if (this->calltimestampms() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->_internal_calltimestampms()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CommonStateSignalAuthorChatCall::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:AcFunDanmu.CommonStateSignalAuthorChatCall) GOOGLE_DCHECK_NE(&from, this); const CommonStateSignalAuthorChatCall* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CommonStateSignalAuthorChatCall>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:AcFunDanmu.CommonStateSignalAuthorChatCall) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:AcFunDanmu.CommonStateSignalAuthorChatCall) MergeFrom(*source); } } void CommonStateSignalAuthorChatCall::MergeFrom(const CommonStateSignalAuthorChatCall& from) { // @@protoc_insertion_point(class_specific_merge_from_start:AcFunDanmu.CommonStateSignalAuthorChatCall) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.authorchatid().size() > 0) { _internal_set_authorchatid(from._internal_authorchatid()); } if (from.has_inviteruserinfo()) { _internal_mutable_inviteruserinfo()->::AcFunDanmu::AuthorChatPlayerInfo::MergeFrom(from._internal_inviteruserinfo()); } if (from.calltimestampms() != 0) { _internal_set_calltimestampms(from._internal_calltimestampms()); } } void CommonStateSignalAuthorChatCall::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:AcFunDanmu.CommonStateSignalAuthorChatCall) if (&from == this) return; Clear(); MergeFrom(from); } void CommonStateSignalAuthorChatCall::CopyFrom(const CommonStateSignalAuthorChatCall& from) { // @@protoc_insertion_point(class_specific_copy_from_start:AcFunDanmu.CommonStateSignalAuthorChatCall) if (&from == this) return; Clear(); MergeFrom(from); } bool CommonStateSignalAuthorChatCall::IsInitialized() const { return true; } void CommonStateSignalAuthorChatCall::InternalSwap(CommonStateSignalAuthorChatCall* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); authorchatid_.Swap(&other->authorchatid_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(CommonStateSignalAuthorChatCall, calltimestampms_) + sizeof(CommonStateSignalAuthorChatCall::calltimestampms_) - PROTOBUF_FIELD_OFFSET(CommonStateSignalAuthorChatCall, inviteruserinfo_)>( reinterpret_cast<char*>(&inviteruserinfo_), reinterpret_cast<char*>(&other->inviteruserinfo_)); } ::PROTOBUF_NAMESPACE_ID::Metadata CommonStateSignalAuthorChatCall::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace AcFunDanmu PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::AcFunDanmu::CommonStateSignalAuthorChatCall* Arena::CreateMaybeMessage< ::AcFunDanmu::CommonStateSignalAuthorChatCall >(Arena* arena) { return Arena::CreateMessageInternal< ::AcFunDanmu::CommonStateSignalAuthorChatCall >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
46.866841
209
0.78624
[ "object" ]
4202042635a66190ddb398f9ae7206a6f4f03f4e
29,113
cpp
C++
gcg/src/dec_consclass.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
gcg/src/dec_consclass.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
gcg/src/dec_consclass.cpp
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
1
2022-01-19T01:15:11.000Z
2022-01-19T01:15:11.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program */ /* GCG --- Generic Column Generation */ /* a Dantzig-Wolfe decomposition based extension */ /* of the branch-cut-and-price framework */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2010-2019 Operations Research, RWTH Aachen University */ /* Zuse Institute Berlin (ZIB) */ /* */ /* This program is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public License */ /* as published by the Free Software Foundation; either version 3 */ /* 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file dec_consclass.cpp * @ingroup DETECTORS * @brief detector consclass (put your description here) * @author Michael Bastubbe */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #include "dec_consclass.h" #include "cons_decomp.h" #include "class_seeed.h" #include "class_seeedpool.h" #include "class_consclassifier.h" #include "gcg.h" #include "scip/cons_setppc.h" #include "scip/scip.h" #include "scip_misc.h" #include "scip/clock.h" #include <sstream> #include <iostream> #include <algorithm> /* constraint handler properties */ #define DEC_DETECTORNAME "consclass" /**< name of detector */ #define DEC_DESC "detector consclass" /**< description of detector*/ #define DEC_FREQCALLROUND 1 /** frequency the detector gets called in detection loop ,ie it is called in round r if and only if minCallRound <= r <= maxCallRound AND (r - minCallRound) mod freqCallRound == 0 */ #define DEC_MAXCALLROUND 0 /** last round the detector gets called */ #define DEC_MINCALLROUND 0 /** first round the detector gets called */ #define DEC_FREQCALLROUNDORIGINAL 1 /** frequency the detector gets called in detection loop while detecting the original problem */ #define DEC_MAXCALLROUNDORIGINAL INT_MAX /** last round the detector gets called while detecting the original problem */ #define DEC_MINCALLROUNDORIGINAL 0 /** first round the detector gets called while detecting the original problem */ #define DEC_PRIORITY 0 /**< priority of the constraint handler for separation */ #define DEC_DECCHAR 'c' /**< display character of detector */ #define DEC_ENABLED TRUE /**< should the detection be enabled */ #define DEC_ENABLEDORIGINAL FALSE /**< should the detection of the original problem be enabled */ #define DEC_ENABLEDFINISHING FALSE /**< should the detection be enabled */ #define DEC_ENABLEDPOSTPROCESSING FALSE /**< should the finishing be enabled */ #define DEC_SKIP FALSE /**< should detector be skipped if other detectors found decompositions */ #define DEC_USEFULRECALL FALSE /**< is it useful to call this detector on a descendant of the propagated seeed */ #define DEC_LEGACYMODE FALSE /**< should (old) DETECTSTRUCTURE method also be used for detection */ #define DEFAULT_MAXIMUMNCLASSES 5 #define AGGRESSIVE_MAXIMUMNCLASSES 9 #define FAST_MAXIMUMNCLASSES 3 #define SET_MULTIPLEFORSIZETRANSF 12500 /* * Data structures */ /** @todo fill in the necessary detector data */ /** detector handler data */ struct DEC_DetectorData { }; /* * Local methods */ /* put your local methods here, and declare them static */ /* * detector callback methods */ /** destructor of detector to free user data (called when GCG is exiting) */ #define freeConsclass NULL /** destructor of detector to free detector data (called before the solving process begins) */ #if 0 static DEC_DECL_EXITDETECTOR(exitConsclass) { /*lint --e{715}*/ SCIPerrorMessage("Exit function of detector <%s> not implemented!\n", DEC_DETECTORNAME); SCIPABORT(); return SCIP_OKAY; } #else #define exitConsclass NULL #endif /** detection initialization function of detector (called before solving is about to begin) */ #if 0 static DEC_DECL_INITDETECTOR(initConsclass) { /*lint --e{715}*/ SCIPerrorMessage("Init function of detector <%s> not implemented!\n", DEC_DETECTORNAME); SCIPABORT(); return SCIP_OKAY; } #else #define initConsclass NULL #endif /** detection function of detector */ //static DEC_DECL_DETECTSTRUCTURE(detectConsclass) //{ /*lint --e{715}*/ // *result = SCIP_DIDNOTFIND; // // SCIPerrorMessage("Detection function of detector <%s> not implemented!\n", DEC_DETECTORNAME) //; SCIPABORT(); /*lint --e{527}*/ // // return SCIP_OKAY; //} #define detectConsclass NULL #define finishSeeedConsclass NULL static DEC_DECL_PROPAGATESEEED(propagateSeeedConsclass) { *result = SCIP_DIDNOTFIND; char decinfo[SCIP_MAXSTRLEN]; SCIP_CLOCK* temporaryClock; SCIP_CALL_ABORT( SCIPcreateClock(scip, &temporaryClock) ); SCIP_CALL_ABORT( SCIPstartClock(scip, temporaryClock) ); std::vector<gcg::Seeed*> foundseeeds(0); gcg::Seeed* seeedOrig; gcg::Seeed* seeed; int maximumnclasses; if( seeedPropagationData->seeedpool->getNConss() + seeedPropagationData->seeedpool->getNVars() >= 50000 ) SCIPgetIntParam(scip, "detection/maxnclassesperclassifierforlargeprobs", &maximumnclasses); else SCIPgetIntParam(scip, "detection/maxnclassesperclassifier", &maximumnclasses); SCIPverbMessage(scip, SCIP_VERBLEVEL_HIGH, NULL, " in dec_consclass: there are %d different constraint classes \n ", seeedPropagationData->seeedpool->getNConsClassifiers() ); for( int classifierIndex = 0; classifierIndex < seeedPropagationData->seeedpool->getNConsClassifiers(); ++classifierIndex ) { gcg::ConsClassifier* classifier = seeedPropagationData->seeedpool->getConsClassifier( classifierIndex ); std::vector<int> consclassindices_master = std::vector<int>(0); if ( classifier->getNClasses() > maximumnclasses ) { std::cout << " the current consclass distribution includes " << classifier->getNClasses() << " classes but only " << maximumnclasses << " are allowed for propagateSeeed() of cons class detector" << std::endl; continue; } SCIPverbMessage(scip, SCIP_VERBLEVEL_HIGH, NULL, " the current constraint classifier \"%s\" consists of %d different classes \n ", classifier->getName(), classifier->getNClasses() ); seeedOrig = seeedPropagationData->seeedToPropagate; for( int i = 0; i < classifier->getNClasses(); ++ i ) { if ( classifier->getClassDecompInfo( i ) == gcg::ONLY_MASTER ) consclassindices_master.push_back( i ); } std::vector< std::vector<int> > subsetsOfConsclasses = classifier->getAllSubsets( true, false, false ); for( size_t subset = 0; subset < subsetsOfConsclasses.size(); ++subset ) { if( subsetsOfConsclasses[subset].size() == 0 && consclassindices_master.size() == 0 ) continue; seeed = new gcg::Seeed(seeedOrig); /** book open conss that have a) type of the current subset or b) decomp info ONLY_MASTER as master conss */ for( int i = 0; i < seeed->getNOpenconss(); ++i ) { bool foundCons = false; for( size_t consclassId = 0; consclassId < subsetsOfConsclasses[subset].size(); ++consclassId ) { if( classifier->getClassOfCons( seeed->getOpenconss()[i] ) == subsetsOfConsclasses[subset][consclassId] ) { seeed->bookAsMasterCons(seeed->getOpenconss()[i]); foundCons = true; break; } } /** only check consclassindices_master if current cons has not already been found in a subset */ if ( !foundCons ) { for( size_t consclassId = 0; consclassId < consclassindices_master.size(); ++consclassId ) { if( classifier->getClassOfCons( seeed->getOpenconss()[i] ) == consclassindices_master[consclassId] ) { seeed->bookAsMasterCons(seeed->getOpenconss()[i]); break; } } } } /** set decinfo to: consclass_<classfier_name>:<master_class_name#1>-...-<master_class_name#n> */ std::stringstream decdesc; decdesc << "consclass" << "\\_" << classifier->getName() << ": \\\\ "; std::vector<int> curmasterclasses( consclassindices_master ); for ( size_t consclassId = 0; consclassId < subsetsOfConsclasses[subset].size(); ++consclassId ) { if ( consclassId > 0 ) { decdesc << "-"; } decdesc << classifier->getClassName( subsetsOfConsclasses[subset][consclassId] ); if( std::find( consclassindices_master.begin(), consclassindices_master.end(), subsetsOfConsclasses[subset][consclassId] ) == consclassindices_master.end() ) { curmasterclasses.push_back( subsetsOfConsclasses[subset][consclassId] ); } } for ( size_t consclassId = 0; consclassId < consclassindices_master.size(); ++consclassId ) { if ( consclassId > 0 || subsetsOfConsclasses[subset].size() > 0) { decdesc << "-"; } decdesc << classifier->getClassName( consclassindices_master[consclassId] ); } seeed->flushBooked(); (void) SCIPsnprintf(decinfo, SCIP_MAXSTRLEN, decdesc.str().c_str()); seeed->addDetectorChainInfo(decinfo); seeed->setConsClassifierStatistics( seeed->getNDetectors(), classifier, curmasterclasses ); foundseeeds.push_back(seeed); } } SCIP_CALL_ABORT( SCIPstopClock(scip, temporaryClock ) ); SCIP_CALL( SCIPallocMemoryArray(scip, &(seeedPropagationData->newSeeeds), foundseeeds.size() ) ); seeedPropagationData->nNewSeeeds = foundseeeds.size(); SCIPinfoMessage(scip, NULL, "dec_consclass found %d new seeeds \n", seeedPropagationData->nNewSeeeds ); for( int s = 0; s < seeedPropagationData->nNewSeeeds; ++s ) { seeedPropagationData->newSeeeds[s] = foundseeeds[s]; seeedPropagationData->newSeeeds[s]->addClockTime(SCIPgetClockTime( scip, temporaryClock ) ); } SCIP_CALL_ABORT(SCIPfreeClock(scip, &temporaryClock) ); *result = SCIP_SUCCESS; return SCIP_OKAY; } static DEC_DECL_PROPAGATEFROMTOOLBOX(propagateFromToolboxConsclass) { *result = SCIP_DIDNOTFIND; char decinfo[SCIP_MAXSTRLEN]; gcg::ConsClassifier** classifiers; int nclassifiers; SCIP_Bool newclass, newclassifier; gcg::ConsClassifier* selectedclassifier; std::vector<int> selectedclasses; int i, j; char stri[SCIP_MAXSTRLEN]; SCIP_Bool finished; char* command; int commandlen; SCIP_Bool endoffile; if( seeedPropagationData->seeedToPropagate->getNOpenconss() != seeedPropagationData->seeedpool->getNConss() ) { SCIPverbMessage(scip, SCIP_VERBLEVEL_HIGH, NULL, "Aborting dec_consclass because there are %d open vars of %d total vars and %d open conss of %d total conss \n ", seeedPropagationData->seeedToPropagate->getNOpenvars(), seeedPropagationData->seeedpool->getNVars(), seeedPropagationData->seeedToPropagate->getNOpenconss() ,seeedPropagationData->seeedpool->getNConss() ); return SCIP_ERROR; } if( seeedPropagationData->seeedpool->getNConsClassifiers() == 0 ) { SCIPinfoMessage(scip, NULL, "No ConsClassifiers listed for propagation, starting classification.\n"); seeedPropagationData->seeedpool->calcClassifierAndNBlockCandidates(scip); if( seeedPropagationData->seeedpool->getNConsClassifiers() == 0 ) { SCIPinfoMessage(scip, NULL, "No ConsClassifiers found after calculation, aborting!.\n"); return SCIP_ERROR; } } std::vector<gcg::Seeed*> foundseeeds(0); gcg::Seeed* seeedOrig; gcg::Seeed* seeed; int maximumnclasses; if( seeedPropagationData->seeedpool->getNConss() + seeedPropagationData->seeedpool->getNVars() >= 50000 ) SCIPgetIntParam(scip, "detection/maxnclassesperclassifierforlargeprobs", &maximumnclasses); else SCIPgetIntParam(scip, "detection/maxnclassesperclassifier", &maximumnclasses); SCIP_CALL( SCIPallocMemoryArray(scip, &classifiers, seeedPropagationData->seeedpool->getNConsClassifiers()) ); SCIPinfoMessage(scip, NULL, "\n%d consclassifiers available for propagation.\n", seeedPropagationData->seeedpool->getNConsClassifiers() ); nclassifiers = 0; for( int classifierIndex = 0; classifierIndex < seeedPropagationData->seeedpool->getNConsClassifiers(); ++classifierIndex ) { gcg::ConsClassifier* classifier = seeedPropagationData->seeedpool->getConsClassifier( classifierIndex ); if( classifier->getNClasses() > maximumnclasses ) { std::cout << " the current consclass distribution includes " << classifier->getNClasses() << " classes but only " << maximumnclasses << " are allowed for propagateSeeed() of cons class detector" << std::endl; continue; } newclassifier = TRUE; for( i = 0; i < nclassifiers; ++i ) { if( classifiers[i] == classifier ) { newclassifier = FALSE; } } if( newclassifier ) { SCIPverbMessage(scip, SCIP_VERBLEVEL_HIGH, NULL, "The constraint classifier \"%s\" consists of %d different classes.\n", classifier->getName(), classifier->getNClasses() ); classifiers[nclassifiers] = classifier; ++nclassifiers; } } selectedclassifier = classifiers[0]; //default case to omit warnings /* user selects a consclassifier */ finished = FALSE; while( !finished ) { SCIPinfoMessage(scip, NULL, "Available consclassifiers:\n"); for( i = 0; i < nclassifiers; ++i ) { SCIPinfoMessage(scip, NULL, "%d) ", i+1); //+1 as we want the list to start with 1) SCIPinfoMessage(scip, NULL, "%s\n", classifiers[i]->getName() ); } commandlen = 0; while( commandlen == 0 ) { SCIP_CALL( SCIPdialoghdlrGetWord(dialoghdlr, dialog, "Type in the name or number of the consclassifier that you want to use (seperated by spaces) or \"done\", (use \"quit\" to exit detector): \nGCG/toolbox> ", &command, &endoffile) ); commandlen = strlen(command); } if( !strncmp( command, "done", commandlen) == 0 && !strncmp( command, "quit", commandlen) == 0 ) { for( i = 0; i < nclassifiers; ++i ) { sprintf(stri, "%d", i+1); //used for matching numberings in the list, off-by-one since classifiers array starts with index 0 and our list with 1) if( strncmp( command, classifiers[i]->getName(), commandlen) == 0 || strncmp( command, stri, commandlen ) == 0 ) { selectedclassifier = classifiers[i]; finished = TRUE; continue; } } } else if( strncmp( command, "done", commandlen) == 0 ) { finished = TRUE; continue; } else if( strncmp( command, "quit", commandlen) == 0 ) { SCIPfreeMemoryArray(scip, &classifiers); *result = SCIP_DIDNOTFIND; return SCIP_OKAY; } } std::vector<int> consclassindices = std::vector<int>(0); for( i = 0; i < selectedclassifier->getNClasses(); ++i ) { consclassindices.push_back(i); } SCIPinfoMessage(scip, NULL, "You will now be asked to enter a selection of classes iteratively. If you have finished your selection, enter \"done\".\n"); finished = FALSE; while( !finished ) { std::vector<int> nConssOfClasses = selectedclassifier->getNConssOfClasses(); SCIPinfoMessage(scip, NULL, "The following classes are available for the selected consclassifier \"%s\":\n",selectedclassifier->getName()); for( i = 0; i < static_cast<int>(consclassindices.size()); ++i ) { SCIPinfoMessage(scip, NULL, "%d) ", i+1); //+1 as we want the list to start with 1) SCIPinfoMessage(scip, NULL, "%s || NConss: %d || %s\n", selectedclassifier->getClassName(consclassindices[i]),nConssOfClasses[i], selectedclassifier->getClassDescription(consclassindices[i])); } commandlen = 0; while( commandlen == 0 ) { SCIP_CALL( SCIPdialoghdlrGetWord(dialoghdlr, dialog, "Type in the name(s) or number(s) of classes (seperated by spaces) or \"done\", (use \"quit\" to exit detector): \nGCG/toolbox> ", &command, &endoffile) ); commandlen = strlen(command); } if( !strncmp( command, "done", commandlen) == 0 && !strncmp( command, "quit", commandlen) == 0 ) { for( i = 0; i < static_cast<int>(consclassindices.size()); ++i ) { newclass = TRUE; sprintf(stri, "%d", i+1); //used for matching numberings in the list, off-by-one since classifiers array starts with index 0 and our list with 1) if( strncmp( command, selectedclassifier->getClassNameOfCons(consclassindices[i]), commandlen) == 0 || strncmp( command, stri, commandlen ) == 0 ) { /* check that we do not select the same classifier multiple times*/ for( j = 0; j < static_cast<int>(selectedclasses.size()); ++j ) { if( selectedclasses[j] == consclassindices[i] ) { newclass = FALSE; } } if( newclass ) { selectedclasses.push_back(consclassindices[i]); SCIPinfoMessage(scip, NULL, "\nCurrently selected classifiers: "); for( j = 0; j < static_cast<int>(selectedclasses.size()); ++j ) { SCIPinfoMessage(scip, NULL, "\"%s\" ", selectedclassifier->getClassNameOfCons(selectedclasses[j])); } SCIPinfoMessage(scip, NULL, "\n\n"); if( selectedclasses.size() >= consclassindices.size() ) { finished = TRUE; break; } } else { SCIPinfoMessage(scip, NULL, "\n+++Class \"%s\" is already selected!+++\n\n", selectedclassifier->getClassNameOfCons(consclassindices[i])); } } } } else if( strncmp( command, "done", commandlen) == 0 ) { finished = TRUE; continue; } else if( strncmp( command, "quit", commandlen) == 0 ) { SCIPfreeMemoryArray(scip, &classifiers); *result = SCIP_DIDNOTFIND; return SCIP_OKAY; } } std::vector<int> consclassindices_master = std::vector<int>(0); seeedOrig = seeedPropagationData->seeedToPropagate; for( i = 0; i < selectedclassifier->getNClasses(); ++ i ) { if ( selectedclassifier->getClassDecompInfo(i) == gcg::ONLY_MASTER ) consclassindices_master.push_back(i); } if( selectedclasses.size() == 0 && consclassindices_master.size() == 0 ) { *result = SCIP_DIDNOTFIND; SCIPfreeMemoryArray(scip, &classifiers); return SCIP_OKAY; } seeed = new gcg::Seeed(seeedOrig); /** book open conss that have a) type of the current subset or b) decomp info ONLY_MASTER as master conss */ for( i = 0; i < seeed->getNOpenconss(); ++i ) { bool foundCons = false; for( size_t consclassId = 0; consclassId < selectedclasses.size(); ++consclassId ) { if( selectedclassifier->getClassOfCons( seeed->getOpenconss()[i] ) == selectedclasses[consclassId] ) { seeed->bookAsMasterCons(seeed->getOpenconss()[i]); foundCons = true; break; } } /** only check consclassindices_master if current cons has not already been found in a subset */ if( !foundCons ) { for( size_t consclassId = 0; consclassId < consclassindices_master.size(); ++consclassId ) { if( selectedclassifier->getClassOfCons( seeed->getOpenconss()[i] ) == consclassindices_master[consclassId] ) { seeed->bookAsMasterCons(seeed->getOpenconss()[i]); break; } } } } /** set decinfo to: consclass_<classfier_name>:<master_class_name#1>-...-<master_class_name#n> */ std::stringstream decdesc; decdesc << "consclass" << "\\_" << selectedclassifier->getName() << ": \\\\ "; std::vector<int> curmasterclasses( consclassindices_master ); for( size_t consclassId = 0; consclassId < selectedclasses.size(); ++consclassId ) { if( consclassId > 0 ) { decdesc << "-"; } decdesc << selectedclassifier->getClassName( selectedclasses[consclassId] ); if( std::find( consclassindices_master.begin(), consclassindices_master.end(), selectedclasses[consclassId] ) == consclassindices_master.end() ) { curmasterclasses.push_back( selectedclasses[consclassId] ); } } for( size_t consclassId = 0; consclassId < consclassindices_master.size(); ++consclassId ) { if( consclassId > 0 || selectedclasses.size() > 0) { decdesc << "-"; } decdesc << selectedclassifier->getClassName( consclassindices_master[consclassId] ); } seeed->flushBooked(); (void) SCIPsnprintf(decinfo, SCIP_MAXSTRLEN, decdesc.str().c_str()); seeed->addDetectorChainInfo(decinfo); seeed->setDetectorPropagated(detector); seeed->setConsClassifierStatistics( seeed->getNDetectors(), selectedclassifier, curmasterclasses ); foundseeeds.push_back(seeed); //@TODO: This alloc is already done in cons_decomp:SCIPconshdlrDecompToolboxActOnSeeed(..). //This is contrary to the behaviour of other detectors such as hrcg, hrg and hr but not connectedbase SCIP_CALL( SCIPallocMemoryArray(scip, &(seeedPropagationData->newSeeeds), foundseeeds.size() ) ); seeedPropagationData->nNewSeeeds = foundseeeds.size(); for( int s = 0; s < seeedPropagationData->nNewSeeeds; ++s ) { seeedPropagationData->newSeeeds[s] = foundseeeds[s]; } *result = SCIP_SUCCESS; SCIPfreeMemoryArray(scip, &classifiers); return SCIP_OKAY; } #define finishFromToolboxConsclass NULL #define detectorPostprocessSeeedConsclass NULL static DEC_DECL_SETPARAMAGGRESSIVE(setParamAggressiveConsclass) { char setstr[SCIP_MAXSTRLEN]; SCIP_Real modifier; int newval; const char* name = DECdetectorGetName(detector); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/enabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, TRUE) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/origenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, TRUE) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/finishingenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, FALSE ) ); if( SCIPgetStage(scip) < SCIP_STAGE_PROBLEM ) { return SCIP_OKAY; } modifier = ((SCIP_Real)SCIPgetNConss(scip) + (SCIP_Real)SCIPgetNVars(scip) ) / SET_MULTIPLEFORSIZETRANSF; modifier = log(modifier) / log(2.); if (!SCIPisFeasPositive(scip, modifier) ) modifier = -1.; modifier = SCIPfloor(scip, modifier); newval = MAX( 6, AGGRESSIVE_MAXIMUMNCLASSES - modifier ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/maxnclasses", name); SCIP_CALL( SCIPsetIntParam(scip, setstr, newval ) ); SCIPinfoMessage(scip, NULL, "\n%s = %d\n", setstr, newval); return SCIP_OKAY; } static DEC_DECL_SETPARAMDEFAULT(setParamDefaultConsclass) { char setstr[SCIP_MAXSTRLEN]; SCIP_Real modifier; int newval; const char* name = DECdetectorGetName(detector); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/enabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, TRUE) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/origenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, TRUE ) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/finishingenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, FALSE ) ); if( SCIPgetStage(scip) < SCIP_STAGE_PROBLEM ) { return SCIP_OKAY; } modifier = ( (SCIP_Real)SCIPgetNConss(scip) + (SCIP_Real)SCIPgetNVars(scip) ) / SET_MULTIPLEFORSIZETRANSF; modifier = log(modifier) / log(2); if (!SCIPisFeasPositive(scip, modifier) ) modifier = -1.; modifier = SCIPfloor(scip, modifier); newval = MAX( 6, DEFAULT_MAXIMUMNCLASSES - modifier ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/maxnclasses", name); SCIP_CALL( SCIPsetIntParam(scip, setstr, newval ) ); SCIPinfoMessage(scip, NULL, "\n%s = %d\n", setstr, newval); return SCIP_OKAY; } static DEC_DECL_SETPARAMFAST(setParamFastConsclass) { char setstr[SCIP_MAXSTRLEN]; SCIP_Real modifier; int newval; const char* name = DECdetectorGetName(detector); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/enabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, TRUE) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/origenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, FALSE) ); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/finishingenabled", name); SCIP_CALL( SCIPsetBoolParam(scip, setstr, FALSE ) ); if( SCIPgetStage(scip) < SCIP_STAGE_PROBLEM ) { return SCIP_OKAY; } modifier = ( (SCIP_Real)SCIPgetNConss(scip) + (SCIP_Real)SCIPgetNVars(scip) ) / SET_MULTIPLEFORSIZETRANSF; modifier = log(modifier) / log(2); if (!SCIPisFeasPositive(scip, modifier) ) modifier = -1.; modifier = SCIPfloor(scip, modifier); (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/maxnclasses", name); newval = MAX( 6, FAST_MAXIMUMNCLASSES - modifier ); SCIP_CALL( SCIPsetIntParam(scip, setstr, newval ) ); SCIPinfoMessage(scip, NULL, "\n%s = %d\n", setstr, newval); return SCIP_OKAY; } /* * detector specific interface methods */ /** creates the handler for consclass detector and includes it in SCIP */ SCIP_RETCODE SCIPincludeDetectorConsclass(SCIP* scip /**< SCIP data structure */ ) { DEC_DETECTORDATA* detectordata; char setstr[SCIP_MAXSTRLEN]; /**@todo create consclass detector data here*/ detectordata = NULL; SCIP_CALL( DECincludeDetector(scip, DEC_DETECTORNAME, DEC_DECCHAR, DEC_DESC, DEC_FREQCALLROUND, DEC_MAXCALLROUND, DEC_MINCALLROUND, DEC_FREQCALLROUNDORIGINAL, DEC_MAXCALLROUNDORIGINAL, DEC_MINCALLROUNDORIGINAL, DEC_PRIORITY, DEC_ENABLED, DEC_ENABLEDORIGINAL, DEC_ENABLEDFINISHING, DEC_ENABLEDPOSTPROCESSING, DEC_SKIP, DEC_USEFULRECALL, DEC_LEGACYMODE, detectordata, detectConsclass, freeConsclass, initConsclass, exitConsclass, propagateSeeedConsclass, propagateFromToolboxConsclass, finishFromToolboxConsclass, finishSeeedConsclass, detectorPostprocessSeeedConsclass, setParamAggressiveConsclass, setParamDefaultConsclass, setParamFastConsclass)); /**@todo add consclass detector parameters */ const char* name = DEC_DETECTORNAME; (void) SCIPsnprintf(setstr, SCIP_MAXSTRLEN, "detection/detectors/%s/maxnclasses", name); SCIP_CALL( SCIPaddIntParam(scip, setstr, "maximum number of classes ", NULL, FALSE, DEFAULT_MAXIMUMNCLASSES, 1, INT_MAX, NULL, NULL ) ); return SCIP_OKAY; }
39.341892
374
0.636176
[ "vector" ]
4204ba125fe11327769a67dab669422f6830c0cb
1,961
cpp
C++
Volatility.cpp
Come-B/jbc_pde_solver
0d4504fa90223f06ecdeaf503c7d27a336c4b82d
[ "BSD-3-Clause" ]
null
null
null
Volatility.cpp
Come-B/jbc_pde_solver
0d4504fa90223f06ecdeaf503c7d27a336c4b82d
[ "BSD-3-Clause" ]
null
null
null
Volatility.cpp
Come-B/jbc_pde_solver
0d4504fa90223f06ecdeaf503c7d27a336c4b82d
[ "BSD-3-Clause" ]
null
null
null
#include "Volatility.h" Volatility::Volatility(){ } Volatility::~Volatility(){ } ConstantVolatility::ConstantVolatility(double sigma) : m_vol(sigma){ } double ConstantVolatility::getVolAt(int j){ return m_vol; } double ConstantVolatility::getMeanVol(){ return m_vol; } ConstantVolatility* ConstantVolatility::bumped(double bump){ return (new ConstantVolatility(m_vol+bump)); } ConstantVolatility::~ConstantVolatility(){ } GeneralVolatility::GeneralVolatility(double vols[], int points_available, int points_grid) : m_size(points_available), m_points_grid(points_grid){ m_vols = new double[m_size]; for(int i=0;i<m_size;i++) m_vols[i] = vols[i]; } GeneralVolatility::GeneralVolatility(double vols[], int points_available) : m_size(points_available), m_points_grid(points_available){ m_vols = new double[m_size]; for(int i=0;i<m_size;i++) m_vols[i] = vols[i]; } GeneralVolatility::GeneralVolatility(std::vector<double> vols, int points_grid) : m_size(vols.size()), m_points_grid(points_grid){ m_vols = new double[m_size]; for(int i=0;i<m_size;i++) m_vols[i] = vols[i]; } GeneralVolatility::GeneralVolatility(std::vector<double> vols) : m_size(vols.size()), m_points_grid(vols.size()){ m_vols = new double[m_size]; for(int i=0;i<m_size;i++) m_vols[i] = vols[i]; } double GeneralVolatility::getVolAt(int j){ int closest_point = int(double(m_size)*j/m_points_grid+0.499); return m_vols[closest_point]; } double GeneralVolatility::getMeanVol(){ double tot=0.; for(int i=0;i<m_points_grid;i++) tot += getVolAt(i); return tot/m_points_grid; } GeneralVolatility* GeneralVolatility::bumped(double bump){ double *tempvol = new double[m_size]; for(int i=0;i<m_size;i++) tempvol[i] = m_vols[i] + bump; return (new GeneralVolatility(tempvol,m_size,m_points_grid)); } GeneralVolatility::~GeneralVolatility(){ delete[] m_vols; }
25.141026
146
0.702193
[ "vector" ]
4209085fb99ce94fab5ee05dcdecd31798ce9452
16,028
cpp
C++
MathTL/algebra/piecewise.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
MathTL/algebra/piecewise.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
MathTL/algebra/piecewise.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
// implementation of MathTL::Piecewise inline functions #include <algebra/piecewise.h> #include <algebra/polynomial.h> #include <utils/tiny_tools.h> #include <cmath> #include <iostream> //#include <iomanip> namespace MathTL { /*! default constructor */ template <class C> Piecewise<C>::Piecewise() : Function<1,C>() { expansion.clear(); granularity = 0; } /*! copy constructor */ template <class C> Piecewise<C>::Piecewise(const Piecewise<C> &p) { expansion.clear(); granularity = p.get_granularity(); const typename Piecewise<C>::PiecesType* pieces = p.get_expansion(); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=pieces->begin(); iter != pieces->end(); ++iter) expansion.insert(typename Piecewise<C>::PiecesType::value_type(iter->first, iter->second)); } /*! constructor for predefined granularity */ template <class C> Piecewise<C>::Piecewise(const int j) // : Function<1,C>() { granularity = j; } /*! destructor */ template <class C> Piecewise<C>::~Piecewise() { expansion.clear(); } /*! reading access, local expansion on one subinterval */ template <class C> Polynomial<C> Piecewise<C>::get_local_expansion(const int k) const { Polynomial<C> p; if (expansion.find(k)!=expansion.end()) p = expansion.find(k)->second; return p; } /*! reading access, all polynomials */ template <class C> const typename Piecewise<C>::PiecesType *Piecewise<C>::get_expansion() const { return &expansion; } /*! writing access, local expansion */ template <class C> void Piecewise<C>::set_local_expansion(const int k, const Polynomial<C> &p) { expansion[k] = p; } /*! clip */ template <class C> void Piecewise<C>::clip_me(const int k1, const int k2) { typename Piecewise<C>::PiecesType help(expansion); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=help.begin(); iter!=help.end(); ++iter) if ((iter->first<k1)||(iter->first>=k2)) expansion.erase(iter->first); } template <class C> Piecewise<C> Piecewise<C>::clip(const int k1, const int k2) const { Piecewise<C> r(*this); r.clip_me(k1, k2); return r; } /*! shift */ template <class C> void Piecewise<C>::shift_me(const int k) { Polynomial<C> p; p.set_coefficient(0, ldexp((double) -k, -granularity)); p.set_coefficient(1, 1); typename Piecewise<C>::PiecesType help(expansion); expansion.clear(); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=help.begin(); iter!=help.end(); ++iter) expansion.insert(typename Piecewise<C>::PiecesType::value_type(iter->first+k, iter->second.substitute_into(p))); // if (k>0) // { // map<int, Polynomial<C> >::reverse_iterator iter; // for (iter=expansion.rbegin(); iter!=expansion.rend(); ++iter) // { // expansion[iter->first + k] = iter->second; // expansion.erase(iter->first); // } // } // else // if (k<0) // { // map<int, Polynomial<C> >::iterator iter; // for (iter=expansion.begin(); iter!=expansion.end(); ++iter) // { // expansion[iter->first + k] = iter->second; // expansion.erase(iter->first); // } // } // map<int, Polynomial<C> > help; // map<int, Polynomial<C> >::const_iterator iter; // for (iter=expansion.begin(); iter!=expansion.end(); ++iter) // help[iter->first + k] = iter->second; // expansion = help; } template <class C> Piecewise<C> Piecewise<C>::shift(const int k) const { Piecewise r(*this); r.shift_me(k); return r; } /*! dilate */ template <class C> void Piecewise<C>::dilate_me(const int j) { granularity += j; // f(x) -> f(2^j x) typename Piecewise<C>::PiecesType::iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) iter->second.scale((double)(1<<j)); scale( twotothejhalf(j) ); // scale by 2^{j/2} } template <class C> Piecewise<C> Piecewise<C>::dilate(const int j) const { Piecewise r(*this); r.dilate_me(j); return r; } /*! increase granularity */ template <class C> void Piecewise<C>::split_me(const int jnew) { if (jnew<granularity) { std::cout << std::endl << "Piecewise::split_me() error; granularity jnew=" << jnew << " coarser than current granularity j=" << granularity << "!" << std::endl; abort(); } else { if (jnew>granularity) { const int d = 1<<(jnew-granularity); typename Piecewise<C>::PiecesType help; typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) for (int k=d*iter->first; k<d*(iter->first+1); k++) help.insert(typename Piecewise<C>::PiecesType::value_type(k, iter->second)); expansion.clear(); for (iter=help.begin(); iter!=help.end(); ++iter) expansion.insert(typename Piecewise<C>::PiecesType::value_type(iter->first, iter->second)); granularity = jnew; } } } template <class C> Piecewise<C> Piecewise<C>::split(const int jnew) const { Piecewise r(*this); r.split_me(jnew); return r; } /*! symbolic differentiation */ template <class C> Piecewise<C> Piecewise<C>::differentiate() const { Piecewise<C> r(granularity); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) if(iter->second.degree() > 0) r.set_local_expansion(iter->first, iter->second.differentiate()); return r; } /*! integration, entire support */ template <class C> double Piecewise<C>::integrate(const bool quadrature) const { double help = ldexp(1.0, -granularity); double r = 0; typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) r += iter->second.integrate(help*iter->first, help*(iter->first+1), quadrature); return r; } /*! integration, specific support */ template <class C> double Piecewise<C>::integrate(const int k1, const int k2, const bool quadrature) const { double help = ldexp(1.0, -granularity); double r = 0; typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) if ((iter->first>=k1)&&(iter->first<k2)) r += iter->second.integrate(help*iter->first, help*(iter->first+1), quadrature); return r; } /* Piecewise operators ... */ /*! assignment of another piecewise */ template <class C> Piecewise<C>& Piecewise<C>::operator = (const Piecewise<C>& p) { expansion.clear(); granularity = p.get_granularity(); const typename Piecewise<C>::PiecesType* pieces = p.get_expansion(); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=pieces->begin(); iter != pieces->end(); ++iter) expansion.insert(typename Piecewise<C>::PiecesType::value_type(iter->first, iter->second)); return *this; } /*! point evaluation */ template <class C> C Piecewise<C>::value (const C x) const { int k = (int) floor(ldexp(1.0, granularity)*x); typename Piecewise<C>::PiecesType::const_iterator iter = expansion.find(k); if (iter != expansion.end()) return iter->second.value(x); else return C(0); } /*! point evaluation (calls above value(const C)) */ template <class C> inline C Piecewise<C>::value(const Point<1>& p, const unsigned int component) const { return value(p[0]); } template <class C> inline void Piecewise<C>::vector_value(const Point<1>& p, Vector<C>& values) const { values.resize(1, false); values[0] = value(p[0]); } /*! point evaluation operator */ template <class C> C Piecewise<C>::operator () (const C x) const { return value(x); } /*! point evaluation of first derivative */ template <class C> C Piecewise<C>::derivative(const C x) const { int k = (int) floor(ldexp(1.0, granularity)*x); typename Piecewise<C>::PiecesType::const_iterator iter = expansion.find(k); if (iter != expansion.end()) return (iter->second).value(x,1); // evaluate first derivative else return C(0); } /*! point evaluation of second derivative */ template <class C> C Piecewise<C>::secondDerivative(const C x) const { int k = (int) floor(ldexp(1.0, granularity)*x); typename Piecewise<C>::PiecesType::const_iterator iter = expansion.find(k); if (iter != expansion.end()) return (iter->second).value(x,2); // evaluate second derivative else return C(0); } /* sums */ /*! add a polynomial to this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::add (const Polynomial<C> &p) { // note: this operation is independent from current granularity typename Piecewise<C>::PiecesType::iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) iter->second += p; return *this; } /*! add a polynomial to this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::operator += (const Polynomial<C> &p) { return add(p); } /*! add an other piecewise to this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::add (const Piecewise<C> &p) { typename Piecewise<C>::PiecesType::const_iterator iter; if (p.get_granularity()>=granularity) { split_me(p.get_granularity()); for (iter=p.expansion.begin(); iter!=p.expansion.end(); ++iter) if (expansion.find(iter->first)!=expansion.end()) expansion[iter->first] = expansion[iter->first] + iter->second; else expansion[iter->first] = iter->second; } else { Piecewise<C> q(p); q.split_me(granularity); for (iter=q.expansion.begin(); iter!=q.expansion.end(); ++iter) if (expansion.find(iter->first)!=expansion.end()) expansion[iter->first] = expansion[iter->first] + iter->second; else expansion[iter->first] = iter->second; } return *this; } /*! add an other piecewise to this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::operator += (const Piecewise<C> &p) { return add(p); } /* differences */ /*! subtract a polynomial from this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::operator -= (const Polynomial<C> &p) { // note: this operation is independent from current granularity typename Piecewise<C>::PiecesType::iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) iter->second -= p; return *this; } /*! subtract an other piecewise from this piecewise */ template <class C> Piecewise<C>& Piecewise<C>::operator -= (const Piecewise<C> &p) { typename Piecewise<C>::PiecesType::const_iterator iter; if (p.get_granularity()>=granularity) { split_me(p.get_granularity()); for (iter=p.expansion.begin(); iter!=p.expansion.end(); ++iter) if (expansion.find(iter->first)!=expansion.end()) expansion[iter->first] = expansion[iter->first] - iter->second; else expansion[iter->first] = -iter->second; } else { Piecewise<C> q(p); q.split_me(granularity); for (iter=q.expansion.begin(); iter!=q.expansion.end(); ++iter) if (expansion.find(iter->first)!=expansion.end()) expansion[iter->first] = expansion[iter->first] - iter->second; else expansion[iter->first] = -iter->second; } return *this; } /* products */ /*! in-place multiplication with a constant */ template <class C> Piecewise<C>& Piecewise<C>::scale (const C c) { // independent from granularity typename Piecewise<C>::PiecesType::iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) iter->second *= c; return *this; } /*! in-place multiplication with a constant */ template <class C> Piecewise<C>& Piecewise<C>::operator *= (const C c) { return scale(c); } template <class C> Piecewise<C>& Piecewise<C>::operator *= (const Polynomial<C>& p) { // independent from granularity typename Piecewise<C>::PiecesType::iterator iter; for (iter=expansion.begin(); iter!=expansion.end(); ++iter) iter->second *= p; return *this; } template <class C> Piecewise<C>& Piecewise<C>::operator *= (const Piecewise &p) { Piecewise<C> q(p); typename Piecewise<C>::PiecesType::const_iterator iter; if (q.get_granularity()>=granularity) split_me(q.get_granularity()); else q.split_me(granularity); Piecewise<C> r(*this); for (iter = r.expansion.begin(); iter != r.expansion.end(); ++iter) if (q.expansion.find(iter->first) != q.expansion.end()) expansion[iter->first] = q.expansion[iter->first] * iter->second; else expansion.erase(iter->first); return *this; } /*! inner product with another piecewise */ template <class C> C Piecewise<C>::inner_product(const Piecewise<C> &p) const { Piecewise<C> r(*this); // make a copy r *= p; return r.integrate(true); } /*! inner product with a polynomial */ template <class C> C Piecewise<C>::inner_product(const Polynomial<C> &p) const { Piecewise<C> r(*this); // make a copy r *= p; return r.integrate(true); } /*! Error output */ template <class C> void Piecewise<C>::MatError(char* str) const { std::cerr << std::endl << "Piecewise error : " << str << std::endl; abort(); } /* non-class-member operators ... */ /* sums */ template <class C> Piecewise<C> operator + (const Polynomial<C> &p, const Piecewise<C> &q) { Piecewise<C> r(q); r += p; return r; } template <class C> Piecewise<C> operator + (const Piecewise<C> &p, const Polynomial<C> &q) { Piecewise<C> r(p); r += q; return r; } template <class C> Piecewise<C> operator + (const Piecewise<C> &p, const Piecewise<C> &q) { Piecewise<C> r(p); r += q; return r; } /* differences */ template <class C> Piecewise<C> operator - (const Polynomial<C> &p, const Piecewise<C> &q) { Piecewise<C> r(q); r *= -1.0; r += p; return r; } template <class C> Piecewise<C> operator - (const Piecewise<C> &p, const Polynomial<C> &q) { Piecewise<C> r(p); r -= q; return r; } template <class C> Piecewise<C> operator - (const Piecewise<C> &p, const Piecewise<C> &q) { Piecewise<C> r(p); r -= q; return r; } /* products */ template <class C> Piecewise<C> operator * (const C c, const Piecewise<C> &q) { Piecewise<C> r(q); r *= c; return r; } template <class C> Piecewise<C> operator * (const Polynomial<C> &p, const Piecewise<C> &q) { Piecewise<C> r(q); r *= p; return r; } template <class C> Piecewise<C> operator * (const Piecewise<C> &p, const Piecewise<C> &q) { Piecewise<C> r(q); r *= p; return r; } /*! output into a stream */ template <class C> std::ostream& operator << (std::ostream& s, const Piecewise<C>& p) { int oldprecision = s.precision(); std::ios::fmtflags oldflags = s.flags(); s.precision(12); const typename Piecewise<C>::PiecesType *pieces = p.get_expansion(); typename Piecewise<C>::PiecesType::const_iterator iter; for (iter=pieces->begin(); iter!=pieces->end(); ++iter) { s << "[" << ldexp(1.0, -p.get_granularity())* iter->first << "," << ldexp(1.0, -p.get_granularity())* (iter->first+1) << "]: " << iter->second << std::endl; } s.setf(oldflags); s.precision(oldprecision); return s; } }
24.965732
118
0.606875
[ "vector" ]
420b19f8782ddf04a1a1eb9162d49713bfbdc0ba
7,401
cpp
C++
source/common/rendering/vulkan/system/vk_buffers.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
1
2022-03-30T15:53:09.000Z
2022-03-30T15:53:09.000Z
source/common/rendering/vulkan/system/vk_buffers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
source/common/rendering/vulkan/system/vk_buffers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
/* ** Vulkan backend ** Copyright (c) 2016-2020 Magnus Norddahl ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** */ #include "vk_buffers.h" #include "vk_builders.h" #include "vk_framebuffer.h" #include "vulkan/renderer/vk_renderstate.h" #include "vulkan/renderer/vk_renderpass.h" #include "engineerrors.h" VKBuffer *VKBuffer::First = nullptr; VKBuffer::VKBuffer() { Next = First; First = this; if (Next) Next->Prev = this; } VKBuffer::~VKBuffer() { if (Next) Next->Prev = Prev; if (Prev) Prev->Next = Next; else First = Next; if (mBuffer && map) mBuffer->Unmap(); auto fb = GetVulkanFrameBuffer(); if (fb) { if (mBuffer) fb->FrameDeleteList.Buffers.push_back(std::move(mBuffer)); if (mStaging) fb->FrameDeleteList.Buffers.push_back(std::move(mStaging)); } } void VKBuffer::ResetAll() { for (VKBuffer *cur = VKBuffer::First; cur; cur = cur->Next) cur->Reset(); } void VKBuffer::Reset() { if (mBuffer && map) mBuffer->Unmap(); mBuffer.reset(); mStaging.reset(); } void VKBuffer::SetData(size_t size, const void *data, BufferUsageType usage) { auto fb = GetVulkanFrameBuffer(); size_t bufsize = max(size, (size_t)16); // For supporting zero byte buffers // If SetData is called multiple times we have to keep the old buffers alive as there might still be draw commands referencing them if (mBuffer) { fb->FrameDeleteList.Buffers.push_back(std::move(mBuffer)); mBuffer = {}; } if (mStaging) { fb->FrameDeleteList.Buffers.push_back(std::move(mStaging)); mStaging = {}; } if (usage == BufferUsageType::Static || usage == BufferUsageType::Stream) { // Note: we could recycle buffers here for the stream usage type to improve performance mPersistent = false; BufferBuilder builder; builder.setUsage(VK_BUFFER_USAGE_TRANSFER_DST_BIT | mBufferType, VMA_MEMORY_USAGE_GPU_ONLY); builder.setSize(bufsize); mBuffer = builder.create(fb->device); BufferBuilder builder2; builder2.setUsage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_ONLY); builder2.setSize(bufsize); mStaging = builder2.create(fb->device); if (data) { void* dst = mStaging->Map(0, bufsize); memcpy(dst, data, size); mStaging->Unmap(); } fb->GetTransferCommands()->copyBuffer(mStaging.get(), mBuffer.get()); } else if (usage == BufferUsageType::Persistent) { mPersistent = true; BufferBuilder builder; builder.setUsage(mBufferType, VMA_MEMORY_USAGE_UNKNOWN, VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT); builder.setMemoryType( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); builder.setSize(bufsize); mBuffer = builder.create(fb->device); map = mBuffer->Map(0, bufsize); if (data) memcpy(map, data, size); } else if (usage == BufferUsageType::Mappable) { mPersistent = false; BufferBuilder builder; builder.setUsage(mBufferType, VMA_MEMORY_USAGE_UNKNOWN, 0); builder.setMemoryType( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); builder.setSize(bufsize); mBuffer = builder.create(fb->device); if (data) { void* dst = mBuffer->Map(0, bufsize); memcpy(dst, data, size); mBuffer->Unmap(); } } buffersize = size; } void VKBuffer::SetSubData(size_t offset, size_t size, const void *data) { size = max(size, (size_t)16); // For supporting zero byte buffers auto fb = GetVulkanFrameBuffer(); if (mStaging) { void *dst = mStaging->Map(offset, size); memcpy(dst, data, size); mStaging->Unmap(); fb->GetTransferCommands()->copyBuffer(mStaging.get(), mBuffer.get(), offset, offset, size); } else { void *dst = mBuffer->Map(offset, size); memcpy(dst, data, size); mBuffer->Unmap(); } } void VKBuffer::Resize(size_t newsize) { newsize = max(newsize, (size_t)16); // For supporting zero byte buffers auto fb = GetVulkanFrameBuffer(); // Grab old buffer size_t oldsize = buffersize; std::unique_ptr<VulkanBuffer> oldBuffer = std::move(mBuffer); oldBuffer->Unmap(); map = nullptr; // Create new buffer BufferBuilder builder; builder.setUsage(mBufferType, VMA_MEMORY_USAGE_UNKNOWN, VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT); builder.setMemoryType( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); builder.setSize(newsize); mBuffer = builder.create(fb->device); buffersize = newsize; // Transfer data from old to new fb->GetTransferCommands()->copyBuffer(oldBuffer.get(), mBuffer.get(), 0, 0, oldsize); fb->WaitForCommands(false); // Fetch pointer to new buffer map = mBuffer->Map(0, newsize); // Old buffer may be part of the dynamic set fb->GetRenderPassManager()->UpdateDynamicSet(); } void VKBuffer::Map() { if (!mPersistent) map = mBuffer->Map(0, mBuffer->size); } void VKBuffer::Unmap() { if (!mPersistent) { mBuffer->Unmap(); map = nullptr; } } void *VKBuffer::Lock(unsigned int size) { size = max(size, (unsigned int)16); // For supporting zero byte buffers if (!mBuffer) { // The model mesh loaders lock multiple non-persistent buffers at the same time. This is not allowed in vulkan. // VkDeviceMemory can only be mapped once and multiple non-persistent buffers may come from the same device memory object. mStaticUpload.Resize(size); map = mStaticUpload.Data(); } else if (!mPersistent) { map = mBuffer->Map(0, size); } return map; } void VKBuffer::Unlock() { if (!mBuffer) { map = nullptr; SetData(mStaticUpload.Size(), mStaticUpload.Data(), BufferUsageType::Static); mStaticUpload.Clear(); } else if (!mPersistent) { mBuffer->Unmap(); map = nullptr; } } ///////////////////////////////////////////////////////////////////////////// void VKVertexBuffer::SetFormat(int numBindingPoints, int numAttributes, size_t stride, const FVertexBufferAttribute *attrs) { VertexFormat = GetVulkanFrameBuffer()->GetRenderPassManager()->GetVertexFormat(numBindingPoints, numAttributes, stride, attrs); } ///////////////////////////////////////////////////////////////////////////// void VKDataBuffer::BindRange(FRenderState* state, size_t start, size_t length) { static_cast<VkRenderState*>(state)->Bind(bindingpoint, (uint32_t)start); }
27.309963
137
0.71666
[ "mesh", "object", "model" ]
4217ab2ebc246fbe6a2284a31e38271545aefea3
1,352
cpp
C++
src/process.cpp
h-arieff/CppND-System-Monitor
096cc2e7a07cb7dff19bbd3dc7f8c9d8bb80882f
[ "MIT" ]
null
null
null
src/process.cpp
h-arieff/CppND-System-Monitor
096cc2e7a07cb7dff19bbd3dc7f8c9d8bb80882f
[ "MIT" ]
null
null
null
src/process.cpp
h-arieff/CppND-System-Monitor
096cc2e7a07cb7dff19bbd3dc7f8c9d8bb80882f
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include <pwd.h> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; Process::Process(int p){ pid=p; status=LinuxParser::getStatus(*this); } // TODO: Return this process's CPU utilization float Process::CpuUtilization() { return LinuxParser::CpuUtilization(*this);; } // TODO: Return the command that generated this process string Process::Command() { return LinuxParser::Command(*this); } // TODO: Return this process's memory utilization long Process::Ram() { std::stringstream ss{status["VmSize:"]}; long ret; ss>>ret; return ret; } // TODO: Return the user (name) that generated this process string Process::User() { if (user==""){ struct passwd *pswd; std::stringstream ss{status["Uid:"]}; int uid; ss>>uid; pswd=getpwuid(uid); user=pswd->pw_name; } return user; } // TODO: Return the age of this process (in seconds) long int Process::UpTime() { return LinuxParser::UpTime(*this); } // TODO: Overload the "less than" comparison operator for Process objects // REMOVE: [[maybe_unused]] once you define the function bool Process::operator<(Process & a) { return CpuUtilization()<a.CpuUtilization(); }
24.142857
85
0.673077
[ "vector" ]
42244b61a73fc32c6ab46f8bcf8735df6f514fa7
20,958
cpp
C++
src/sound/mididevices/music_fluidsynth_mididevice.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/sound/mididevices/music_fluidsynth_mididevice.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
src/sound/mididevices/music_fluidsynth_mididevice.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
/* ** music_fluidsynth_mididevice.cpp ** Provides access to FluidSynth as a generic MIDI device. ** **--------------------------------------------------------------------------- ** Copyright 2010 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #ifdef HAVE_FLUIDSYNTH // HEADER FILES ------------------------------------------------------------ #include "i_musicinterns.h" #include "i_system.h" #include "templates.h" #include "doomdef.h" #include "m_swap.h" #include "w_wad.h" #include "v_text.h" #include "version.h" #include "cmdlib.h" // MACROS ------------------------------------------------------------------ #ifdef DYN_FLUIDSYNTH #ifdef _WIN32 // do this without including windows.h for this one single prototype extern "C" unsigned __stdcall GetSystemDirectoryA(char *lpBuffer, unsigned uSize); #ifndef _M_X64 #define FLUIDSYNTHLIB1 "fluidsynth.dll" #define FLUIDSYNTHLIB2 "libfluidsynth.dll" #else #define FLUIDSYNTHLIB1 "fluidsynth64.dll" #define FLUIDSYNTHLIB2 "libfluidsynth64.dll" #endif #else #include <dlfcn.h> #ifdef __APPLE__ #define FLUIDSYNTHLIB1 "libfluidsynth.1.dylib" #else // !__APPLE__ #define FLUIDSYNTHLIB1 "libfluidsynth.so.1" #endif // __APPLE__ #endif #define FLUID_REVERB_DEFAULT_ROOMSIZE 0.2f #define FLUID_REVERB_DEFAULT_DAMP 0.0f #define FLUID_REVERB_DEFAULT_WIDTH 0.5f #define FLUID_REVERB_DEFAULT_LEVEL 0.9f #define FLUID_CHORUS_MOD_SINE 0 #define FLUID_CHORUS_MOD_TRIANGLE 1 #define FLUID_CHORUS_DEFAULT_N 3 #define FLUID_CHORUS_DEFAULT_LEVEL 2.0f #define FLUID_CHORUS_DEFAULT_SPEED 0.3f #define FLUID_CHORUS_DEFAULT_DEPTH 8.0f #define FLUID_CHORUS_DEFAULT_TYPE FLUID_CHORUS_MOD_SINE #endif // TYPES ------------------------------------------------------------------- // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- const char *BaseFileSearch(const char *file, const char *ext, bool lookfirstinprogdir = false); // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- // PRIVATE DATA DEFINITIONS ------------------------------------------------ // PUBLIC DATA DEFINITIONS ------------------------------------------------- CVAR(String, fluid_lib, "", CVAR_ARCHIVE|CVAR_GLOBALCONFIG) CUSTOM_CVAR(String, fluid_patchset, "", CVAR_ARCHIVE | CVAR_GLOBALCONFIG) { if (currSong != nullptr && currSong->GetDeviceType() == MDEV_FLUIDSYNTH) { MIDIDeviceChanged(-1, true); } } CUSTOM_CVAR(Float, fluid_gain, 0.5, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 10) self = 10; else if (currSong != NULL) currSong->FluidSettingNum("synth.gain", self); } CUSTOM_CVAR(Bool, fluid_reverb, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (currSong != NULL) currSong->FluidSettingInt("synth.reverb.active", self); } CUSTOM_CVAR(Bool, fluid_chorus, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (currSong != NULL) currSong->FluidSettingInt("synth.chorus.active", self); } CUSTOM_CVAR(Int, fluid_voices, 128, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 16) self = 16; else if (self > 4096) self = 4096; else if (currSong != NULL) currSong->FluidSettingInt("synth.polyphony", self); } CUSTOM_CVAR(Int, fluid_interp, 1, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { // Values are: 0 = FLUID_INTERP_NONE // 1 = FLUID_INTERP_LINEAR // 4 = FLUID_INTERP_4THORDER (the FluidSynth default) // 7 = FLUID_INTERP_7THORDER // (And here I thought it was just a linear list.) // Round undefined values to the nearest valid one. if (self < 0) self = 0; else if (self == 2) self = 1; else if (self == 3 || self == 5) self = 4; else if (self == 6 || self > 7) self = 7; else if (currSong != NULL) currSong->FluidSettingInt("synth.interpolation", self); } CVAR(Int, fluid_samplerate, 0, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) // I don't know if this setting even matters for us, since we aren't letting // FluidSynth drives its own output. CUSTOM_CVAR(Int, fluid_threads, 1, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 1) self = 1; else if (self > 256) self = 256; } CUSTOM_CVAR(Float, fluid_reverb_roomsize, 0.61f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 1.2f) self = 1.2f; else if (currSong != NULL) currSong->FluidSettingInt("z.reverb-changed", 0); } CUSTOM_CVAR(Float, fluid_reverb_damping, 0.23f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 1) self = 1; else if (currSong != NULL) currSong->FluidSettingInt("z.reverb-changed", 0); } CUSTOM_CVAR(Float, fluid_reverb_width, 0.76f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 100) self = 100; else if (currSong != NULL) currSong->FluidSettingInt("z.reverb-changed", 0); } CUSTOM_CVAR(Float, fluid_reverb_level, 0.57f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 1) self = 1; else if (currSong != NULL) currSong->FluidSettingInt("z.reverb-changed", 0); } CUSTOM_CVAR(Int, fluid_chorus_voices, 3, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 99) self = 99; else if (currSong != NULL) currSong->FluidSettingInt("z.chorus-changed", 0); } CUSTOM_CVAR(Float, fluid_chorus_level, 1.2f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 1) self = 1; else if (currSong != NULL) currSong->FluidSettingInt("z.chorus-changed", 0); } CUSTOM_CVAR(Float, fluid_chorus_speed, 0.3f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0.29f) self = 0.29f; else if (self > 5) self = 5; else if (currSong != NULL) currSong->FluidSettingInt("z.chorus-changed", 0); } // depth is in ms and actual maximum depends on the sample rate CUSTOM_CVAR(Float, fluid_chorus_depth, 8, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self < 0) self = 0; else if (self > 21) self = 21; else if (currSong != NULL) currSong->FluidSettingInt("z.chorus-changed", 0); } CUSTOM_CVAR(Int, fluid_chorus_type, FLUID_CHORUS_DEFAULT_TYPE, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { if (self != FLUID_CHORUS_MOD_SINE && self != FLUID_CHORUS_MOD_TRIANGLE) self = FLUID_CHORUS_DEFAULT_TYPE; else if (currSong != NULL) currSong->FluidSettingInt("z.chorus-changed", 0); } // CODE -------------------------------------------------------------------- //========================================================================== // // FluidSynthMIDIDevice Constructor // //========================================================================== FluidSynthMIDIDevice::FluidSynthMIDIDevice(const char *args) { FluidSynth = NULL; FluidSettings = NULL; #ifdef DYN_FLUIDSYNTH if (!LoadFluidSynth()) { return; } #endif FluidSettings = new_fluid_settings(); if (FluidSettings == NULL) { printf("Failed to create FluidSettings.\n"); return; } SampleRate = fluid_samplerate; if (SampleRate < 22050 || SampleRate > 96000) { // Match sample rate to SFX rate SampleRate = clamp((int)GSnd->GetOutputRate(), 22050, 96000); } fluid_settings_setnum(FluidSettings, "synth.sample-rate", SampleRate); fluid_settings_setnum(FluidSettings, "synth.gain", fluid_gain); fluid_settings_setint(FluidSettings, "synth.reverb.active", fluid_reverb); fluid_settings_setint(FluidSettings, "synth.chorus.active", fluid_chorus); fluid_settings_setint(FluidSettings, "synth.polyphony", fluid_voices); fluid_settings_setint(FluidSettings, "synth.cpu-cores", fluid_threads); FluidSynth = new_fluid_synth(FluidSettings); if (FluidSynth == NULL) { Printf("Failed to create FluidSynth.\n"); return; } fluid_synth_set_interp_method(FluidSynth, -1, fluid_interp); fluid_synth_set_reverb(FluidSynth, fluid_reverb_roomsize, fluid_reverb_damping, fluid_reverb_width, fluid_reverb_level); fluid_synth_set_chorus(FluidSynth, fluid_chorus_voices, fluid_chorus_level, fluid_chorus_speed, fluid_chorus_depth, fluid_chorus_type); // try loading a patch set that got specified with $mididevice. int res = 0; if (args != NULL && *args != 0) { if (LoadPatchSets(args)) return; } if (LoadPatchSets(fluid_patchset)) { return; } #ifdef __unix__ // This is the standard location on Ubuntu. if (LoadPatchSets("/usr/share/sounds/sf2/FluidR3_GS.sf2:/usr/share/sounds/sf2/FluidR3_GM.sf2")) { return; } #endif #ifdef _WIN32 // On Windows, look for the 4 megabyte patch set installed by Creative's drivers as a default. char sysdir[MAX_PATH + sizeof("\\CT4MGM.SF2")]; uint32_t filepart; if (0 != (filepart = GetSystemDirectoryA(sysdir, MAX_PATH))) { strcat(sysdir, "\\CT4MGM.SF2"); if (LoadPatchSets(sysdir)) { return; } // Try again with CT2MGM.SF2 sysdir[filepart + 3] = '2'; if (LoadPatchSets(sysdir)) { return; } } #endif // Last try the base sound font which should be provided by the GZDoom binary package. auto wad = BaseFileSearch(BASESF, NULL, true); if (wad != NULL && LoadPatchSets(wad)) { return; } Printf("Failed to load any MIDI patches.\n"); delete_fluid_synth(FluidSynth); FluidSynth = NULL; } //========================================================================== // // FluidSynthMIDIDevice Destructor // //========================================================================== FluidSynthMIDIDevice::~FluidSynthMIDIDevice() { Close(); if (FluidSynth != NULL) { delete_fluid_synth(FluidSynth); } if (FluidSettings != NULL) { delete_fluid_settings(FluidSettings); } #ifdef DYN_FLUIDSYNTH UnloadFluidSynth(); #endif } //========================================================================== // // FluidSynthMIDIDevice :: Open // // Returns 0 on success. // //========================================================================== int FluidSynthMIDIDevice::Open(MidiCallback callback, void *userdata) { if (FluidSynth == NULL) { return 2; } int ret = OpenStream(4, 0, callback, userdata); if (ret == 0) { fluid_synth_system_reset(FluidSynth); } return ret; } //========================================================================== // // FluidSynthMIDIDevice :: HandleEvent // // Translates a MIDI event into FluidSynth calls. // //========================================================================== void FluidSynthMIDIDevice::HandleEvent(int status, int parm1, int parm2) { int command = status & 0xF0; int channel = status & 0x0F; switch (command) { case MIDI_NOTEOFF: fluid_synth_noteoff(FluidSynth, channel, parm1); break; case MIDI_NOTEON: fluid_synth_noteon(FluidSynth, channel, parm1, parm2); break; case MIDI_POLYPRESS: break; case MIDI_CTRLCHANGE: fluid_synth_cc(FluidSynth, channel, parm1, parm2); break; case MIDI_PRGMCHANGE: fluid_synth_program_change(FluidSynth, channel, parm1); break; case MIDI_CHANPRESS: fluid_synth_channel_pressure(FluidSynth, channel, parm1); break; case MIDI_PITCHBEND: fluid_synth_pitch_bend(FluidSynth, channel, (parm1 & 0x7f) | ((parm2 & 0x7f) << 7)); break; } } //========================================================================== // // FluidSynthMIDIDevice :: HandleLongEvent // // Handle SysEx messages. // //========================================================================== void FluidSynthMIDIDevice::HandleLongEvent(const uint8_t *data, int len) { if (len > 1 && (data[0] == 0xF0 || data[0] == 0xF7)) { fluid_synth_sysex(FluidSynth, (const char *)data + 1, len - 1, NULL, NULL, NULL, 0); } } //========================================================================== // // FluidSynthMIDIDevice :: ComputeOutput // //========================================================================== void FluidSynthMIDIDevice::ComputeOutput(float *buffer, int len) { fluid_synth_write_float(FluidSynth, len, buffer, 0, 2, buffer, 1, 2); } //========================================================================== // // FluidSynthMIDIDevice :: LoadPatchSets // // Loads a delimiter-separated list of patch sets. This delimiter matches // that of the PATH environment variable. On Windows, it is ';'. On other // systems, it is ':'. Returns the number of patch sets loaded. // //========================================================================== int FluidSynthMIDIDevice::LoadPatchSets(const char *patches) { int count; char *wpatches = strdup(patches); char *tok; #ifdef _WIN32 const char *const delim = ";"; #else const char *const delim = ":"; #endif if (wpatches == NULL) { return 0; } tok = strtok(wpatches, delim); count = 0; while (tok != NULL) { FString path; #ifdef _WIN32 // If the path does not contain any path separators, automatically // prepend $PROGDIR to the path. if (strcspn(tok, ":/\\") == strlen(tok)) { path << "$PROGDIR/" << tok; path = NicePath(path); } else #endif { path = NicePath(tok); } if (FileExists(path)) { if (FLUID_FAILED != fluid_synth_sfload(FluidSynth, path, count == 0)) { DPrintf(DMSG_NOTIFY, "Loaded patch set %s.\n", tok); count++; } else { DPrintf(DMSG_ERROR, "Failed to load patch set %s.\n", tok); } } else { DPrintf(DMSG_ERROR, "Could not find patch set %s.\n", tok); } tok = strtok(NULL, delim); } free(wpatches); return count; } //========================================================================== // // FluidSynthMIDIDevice :: FluidSettingInt // // Changes an integer setting. // //========================================================================== void FluidSynthMIDIDevice::FluidSettingInt(const char *setting, int value) { if (FluidSynth == NULL || FluidSettings == NULL) { return; } if (strcmp(setting, "synth.interpolation") == 0) { if (FLUID_OK != fluid_synth_set_interp_method(FluidSynth, -1, value)) { Printf("Setting interpolation method %d failed.\n", value); } } else if (strcmp(setting, "synth.polyphony") == 0) { if (FLUID_OK != fluid_synth_set_polyphony(FluidSynth, value)) { Printf("Setting polyphony to %d failed.\n", value); } } else if (strcmp(setting, "z.reverb-changed") == 0) { fluid_synth_set_reverb(FluidSynth, fluid_reverb_roomsize, fluid_reverb_damping, fluid_reverb_width, fluid_reverb_level); } else if (strcmp(setting, "z.chorus-changed") == 0) { fluid_synth_set_chorus(FluidSynth, fluid_chorus_voices, fluid_chorus_level, fluid_chorus_speed, fluid_chorus_depth, fluid_chorus_type); } else if (0 == fluid_settings_setint(FluidSettings, setting, value)) { Printf("Failed to set %s to %d.\n", setting, value); } // fluid_settings_setint succeeded; update these settings in the running synth, too else if (strcmp(setting, "synth.reverb.active") == 0) { fluid_synth_set_reverb_on(FluidSynth, value); } else if (strcmp(setting, "synth.chorus.active") == 0) { fluid_synth_set_chorus_on(FluidSynth, value); } } //========================================================================== // // FluidSynthMIDIDevice :: FluidSettingNum // // Changes a numeric setting. // //========================================================================== void FluidSynthMIDIDevice::FluidSettingNum(const char *setting, double value) { if (FluidSettings != NULL) { if (0 == fluid_settings_setnum(FluidSettings, setting, value)) { Printf("Failed to set %s to %g.\n", setting, value); } } } //========================================================================== // // FluidSynthMIDIDevice :: FluidSettingStr // // Changes a string setting. // //========================================================================== void FluidSynthMIDIDevice::FluidSettingStr(const char *setting, const char *value) { if (FluidSettings != NULL) { if (0 == fluid_settings_setstr(FluidSettings, setting, value)) { Printf("Failed to set %s to %s.\n", setting, value); } } } //========================================================================== // // FluidSynthMIDIDevice :: GetStats // //========================================================================== FString FluidSynthMIDIDevice::GetStats() { if (FluidSynth == NULL || FluidSettings == NULL) { return "FluidSynth is invalid"; } FString out; CritSec.Enter(); int polyphony = fluid_synth_get_polyphony(FluidSynth); int voices = fluid_synth_get_active_voice_count(FluidSynth); double load = fluid_synth_get_cpu_load(FluidSynth); char *chorus, *reverb; int maxpoly; fluid_settings_getstr(FluidSettings, "synth.chorus.active", &chorus); fluid_settings_getstr(FluidSettings, "synth.reverb.active", &reverb); fluid_settings_getint(FluidSettings, "synth.polyphony", &maxpoly); CritSec.Leave(); out.Format("Voices: " TEXTCOLOR_YELLOW "%3d" TEXTCOLOR_NORMAL "/" TEXTCOLOR_ORANGE "%3d" TEXTCOLOR_NORMAL "(" TEXTCOLOR_RED "%3d" TEXTCOLOR_NORMAL ")" TEXTCOLOR_YELLOW "%6.2f" TEXTCOLOR_NORMAL "%% CPU " "Reverb: " TEXTCOLOR_YELLOW "%3s" TEXTCOLOR_NORMAL " Chorus: " TEXTCOLOR_YELLOW "%3s", voices, polyphony, maxpoly, load, reverb, chorus); return out; } #ifdef DYN_FLUIDSYNTH //========================================================================== // // FluidSynthMIDIDevice :: LoadFluidSynth // // Returns true if the FluidSynth library was successfully loaded. // //========================================================================== FModuleMaybe<DYN_FLUIDSYNTH> FluidSynthModule{"FluidSynth"}; #define DYN_FLUID_SYM(x) decltype(FluidSynthMIDIDevice::x) FluidSynthMIDIDevice::x{#x} DYN_FLUID_SYM(new_fluid_settings); DYN_FLUID_SYM(new_fluid_synth); DYN_FLUID_SYM(delete_fluid_synth); DYN_FLUID_SYM(delete_fluid_settings); DYN_FLUID_SYM(fluid_settings_setnum); DYN_FLUID_SYM(fluid_settings_setstr); DYN_FLUID_SYM(fluid_settings_setint); DYN_FLUID_SYM(fluid_settings_getstr); DYN_FLUID_SYM(fluid_settings_getint); DYN_FLUID_SYM(fluid_synth_set_reverb_on); DYN_FLUID_SYM(fluid_synth_set_chorus_on); DYN_FLUID_SYM(fluid_synth_set_interp_method); DYN_FLUID_SYM(fluid_synth_set_polyphony); DYN_FLUID_SYM(fluid_synth_get_polyphony); DYN_FLUID_SYM(fluid_synth_get_active_voice_count); DYN_FLUID_SYM(fluid_synth_get_cpu_load); DYN_FLUID_SYM(fluid_synth_system_reset); DYN_FLUID_SYM(fluid_synth_noteon); DYN_FLUID_SYM(fluid_synth_noteoff); DYN_FLUID_SYM(fluid_synth_cc); DYN_FLUID_SYM(fluid_synth_program_change); DYN_FLUID_SYM(fluid_synth_channel_pressure); DYN_FLUID_SYM(fluid_synth_pitch_bend); DYN_FLUID_SYM(fluid_synth_write_float); DYN_FLUID_SYM(fluid_synth_sfload); DYN_FLUID_SYM(fluid_synth_set_reverb); DYN_FLUID_SYM(fluid_synth_set_chorus); DYN_FLUID_SYM(fluid_synth_sysex); bool FluidSynthMIDIDevice::LoadFluidSynth() { if (strlen(fluid_lib) > 0) { if(!FluidSynthModule.Load({fluid_lib})) { const char* libname = fluid_lib; Printf(TEXTCOLOR_RED "Could not load %s\n", libname); } else return true; } #ifdef FLUIDSYNTHLIB2 if(!FluidSynthModule.Load({FLUIDSYNTHLIB1, FLUIDSYNTHLIB2})) { Printf(TEXTCOLOR_RED "Could not load " FLUIDSYNTHLIB1 " or " FLUIDSYNTHLIB2 "\n"); return false; } #else if(!FluidSynthModule.Load({fluid_lib, FLUIDSYNTHLIB1})) { Printf(TEXTCOLOR_RED "Could not load " FLUIDSYNTHLIB1 ": %s\n", dlerror()); return false; } #endif return true; } //========================================================================== // // FluidSynthMIDIDevice :: UnloadFluidSynth // //========================================================================== void FluidSynthMIDIDevice::UnloadFluidSynth() { FluidSynthModule.Unload(); } #endif #endif
27.503937
151
0.635461
[ "3d" ]
4235267c4f48b7c8d19d514d3afcc11fbe853317
66,570
cpp
C++
src/BPFFile.cpp
USArmyResearchLab/Fusion3D
98b79ccfcbfd444a924f65c321482b540382758d
[ "Apache-2.0" ]
4
2021-09-08T02:07:22.000Z
2022-03-30T02:48:56.000Z
src/BPFFile.cpp
USArmyResearchLab/Fusion3D
98b79ccfcbfd444a924f65c321482b540382758d
[ "Apache-2.0" ]
null
null
null
src/BPFFile.cpp
USArmyResearchLab/Fusion3D
98b79ccfcbfd444a924f65c321482b540382758d
[ "Apache-2.0" ]
1
2021-10-11T02:53:53.000Z
2021-10-11T02:53:53.000Z
//written by M. Brandon Cox - Booz Allen Hamilton - cox_michael@bah.com #include "internals.h" BPFFile::BPFFile() : STATIC_HEADER_SIZE_IN_BYTES(100), dirtyMinsAndMaxs(false), dirtyFieldMinsAndMaxs(false), pointSpacing(0.0), xMin(0.0), xMax(0.0), yMin(0.0), yMax(0.0), zMin(0.0), zMax(0.0), decompressedBytesBuffer(NULL), decompressedBytesBufferPos(0), decompressedBytesBufferSize(0), numberOfExtraFields(0), numberOfPoints(0), xOffset(0.0), yOffset(0.0), zOffset(0.0), headerDataOnly(false), isCompressed(2), interleaved(0) { extraFields.clear(); transformMatrix[0][0] = 1.0; transformMatrix[0][1] = 0.0; transformMatrix[0][2] = 0.0; transformMatrix[0][3] = 0.0; transformMatrix[1][0] = 0.0; transformMatrix[1][1] = 1.0; transformMatrix[1][2] = 0.0; transformMatrix[1][3] = 0.0; transformMatrix[2][0] = 0.0; transformMatrix[2][1] = 0.0; transformMatrix[2][2] = 1.0; transformMatrix[2][3] = 0.0; transformMatrix[3][0] = 0.0; transformMatrix[3][1] = 0.0; transformMatrix[3][2] = 0.0; transformMatrix[3][3] = 1.0; updateHeaderLength(); nStride = 1; suppressExtraFieldFlags = NULL; } const int BPFFile::FIELD_LABEL_LENGTH = 32; const int BPFFile::HEADER_SIZE_V1 = 100; const int BPFFile::HEADER_SIZE_V2 = 100; const int BPFFile::HEADER_SIZE_V3 = 176; const int BPFFile::HEADER_LENGTH_POS_V3 = 8; const int BPFFile::NUMBER_OF_DIMS_POS_V3 = 12; const int BPFFile::POINT_COUNT_POS_V3 = 16; const char* BPFFile::ASCII_MAGIC_NUMBER_STRING = "BPF!"; const unsigned BPFFile::INTERLEAVED_POINTS_PER_COMPRESSED_BLOCK = 100000; BPFFile::~BPFFile() { for(unsigned int i = 0; i < extraFields.size(); i++) delete extraFields[i]; delete [] decompressedBytesBuffer; if (suppressExtraFieldFlags == NULL) delete[] suppressExtraFieldFlags ; } int BPFFile::setNStride(int n) { nStride = n; return(1); } int BPFFile::suppressExtraField(int ifield) { if (ifield < 0 || ifield >= numberOfExtraFields) { return(0); } else { suppressExtraFieldFlags[ifield] = 1; return(1); } } int BPFFile::getHeaderLength() { updateHeaderLength(); return headerLength; } int BPFFile::getNumberOfPoints() { updateNumberOfPoints(); return numberOfPoints; } int BPFFile::getNumberOfExtraFields() { //only update if this object doesn't represent only header data //otherwise, the number of extra field data will get zeroed in the update if(!this->headerDataOnly) updateNumberOfExtraFields(); return numberOfExtraFields; } double BPFFile::getXMin() { updateXYZMinsAndMaxs(); return xMin; } double BPFFile::getXMax() { updateXYZMinsAndMaxs(); return xMax; } double BPFFile::getYMin() { updateXYZMinsAndMaxs(); return yMin; } double BPFFile::getYMax() { updateXYZMinsAndMaxs(); return yMax; } double BPFFile::getZMin() { updateXYZMinsAndMaxs(); return zMin; } double BPFFile::getZMax() { updateXYZMinsAndMaxs(); return zMax; } bool BPFFile::mergeWithBPFFile(BPFFile& newData) { //prerequisites for merge //same number of extra fields //same coordinate system //same zone if(this->zone != newData.getZone() || this->coordinateSystem != newData.getCoordinateSystem() || this->numberOfExtraFields != newData.getNumberOfExtraFields()) return false; else { int numNewPoints = newData.getNumberOfPoints(); //copy x's for(int i = 0; i < numNewPoints; i++) this->xValues.push_back((float)(newData.getXValue(i) - this->xOffset)); //copy y's for(int i = 0; i < numNewPoints; i++) this->yValues.push_back((float)(newData.getYValue(i) - this->yOffset)); //copy z's for(int i = 0; i < numNewPoints; i++) this->zValues.push_back((float)(newData.getZValue(i) - this->zOffset)); //copy extra fields for(int i = 0; i < this->numberOfExtraFields; i++) { for(int n = 0; n < numNewPoints; n++) { this->extraFields[i]->push_back(newData.getExtraFieldValueByNumber(i, n) - this->fieldOffsets[i]); } } //recalculate all of the min and max values this->updateNumberOfPoints(); this->xMin = (this->xMin < newData.getXMin() ? this->xMin : newData.getXMin()); this->yMin = (this->yMin < newData.getYMin() ? this->yMin : newData.getYMin()); this->zMin = (this->zMin < newData.getZMin() ? this->zMin : newData.getZMin()); this->xMax = (this->xMax > newData.getXMax() ? this->xMax : newData.getXMax()); this->yMax = (this->yMax > newData.getYMax() ? this->yMax : newData.getYMax()); this->zMax = (this->zMax > newData.getZMax() ? this->zMax : newData.getZMax()); for(int i = 0; i < this->numberOfExtraFields; i++) { this->minFieldValues[i] = (this->minFieldValues[i] < newData.getFieldMin(i) ? this->minFieldValues[i] : newData.getFieldMin(i)); this->maxFieldValues[i] = (this->maxFieldValues[i] < newData.getFieldMax(i) ? this->maxFieldValues[i] : newData.getFieldMax(i)); } return true; } } double BPFFile::getFieldMin(int n) { updateFieldMinsAndMaxs(); return this->minFieldValues[n]; } double BPFFile::getFieldMax(int n) { updateFieldMinsAndMaxs(); return this->maxFieldValues[n]; } void BPFFile::setXYZCoordinates(const vector<float>& X, const vector<float>& Y, const vector<float>& Z) { if(X.size() != Y.size() || Y.size() != Z.size()) throw BPFFile::InvalidBPFData("In BPFFile::setXYZCoordinates: X, Y, and Z vectors not equal size"); for(unsigned int i = 0; i < X.size(); i++) { xValues.push_back(X[i]); yValues.push_back(Y[i]); zValues.push_back(Z[i]); } updateNumberOfPoints(); dirtyMinsAndMaxs = true; updateXYZMinsAndMaxs(); } void BPFFile::addExtraFieldData(const string& label, vector<float>& extraField, const double& offset) { if(extraField.size() != this->numberOfPoints) throw BPFFile::InvalidBPFData("In BPFFile::addExtraFieldData: extraField length does not match number of points"); if(label.length() > FIELD_LABEL_LENGTH-1) throw BPFFile::InvalidBPFData("In BPFFile::addExtraFieldData: extra field label length is greater than allowed"); fieldLabels.push_back(label); fieldOffsets.push_back(offset); extraFields.push_back(new vector<float>); float tempFloat; //mins and maxs should be reported as the unoffset values tempFloat = *min_element(extraField.begin(), extraField.end()); minFieldValues.push_back(tempFloat+offset); tempFloat = *max_element(extraField.begin(), extraField.end()); maxFieldValues.push_back(tempFloat+offset); for(int i = 0; i < this->numberOfPoints; i++) { extraFields.back()->push_back(extraField[i]); } updateNumberOfExtraFields(); updateHeaderLength(); } void BPFFile::removeExtraField(const string& label) { //first determine if the specified extra field exists unsigned int labelEFI = this->getExtraFieldNumberByName(label); //erase all data associated with this extra field. this->fieldOffsets.erase(this->fieldOffsets.begin()+labelEFI); this->minFieldValues.erase(this->minFieldValues.begin()+labelEFI); this->maxFieldValues.erase(this->maxFieldValues.begin()+labelEFI); this->fieldLabels.erase(this->fieldLabels.begin()+labelEFI); delete this->extraFields[labelEFI]; this->extraFields.erase(this->extraFields.begin()+labelEFI); this->numberOfExtraFields--; } int BPFFile::calculateHeaderLength() { return STATIC_HEADER_SIZE_IN_BYTES + fieldOffsets.size() * sizeof(double) + minFieldValues.size() * sizeof(double) + maxFieldValues.size() * sizeof(double) + fieldLabels.size() * FIELD_LABEL_LENGTH; } void BPFFile::updateHeaderLength() { this->headerLength = calculateHeaderLength(); } void BPFFile::updateXYZMinsAndMaxs() { if(dirtyMinsAndMaxs == true) { xMin = *min_element(xValues.begin(), xValues.end()) + this->xOffset; xMax = *max_element(xValues.begin(), xValues.end()) + this->xOffset; yMin = *min_element(yValues.begin(), yValues.end()) + this->yOffset; yMax = *max_element(yValues.begin(), yValues.end()) + this->yOffset; zMin = *min_element(zValues.begin(), zValues.end()) + this->zOffset; zMax = *max_element(zValues.begin(), zValues.end()) + this->zOffset; dirtyMinsAndMaxs = false; } } void BPFFile::updateFieldMinsAndMaxs() { if(dirtyFieldMinsAndMaxs == true) { for(unsigned int i = 0; i < extraFields.size(); i++) { minFieldValues[i] = *min_element(extraFields[i]->begin(), extraFields[i]->end()) + this->fieldOffsets[i]; maxFieldValues[i] = *max_element(extraFields[i]->begin(), extraFields[i]->end()) + this->fieldOffsets[i]; } dirtyFieldMinsAndMaxs = false; } } void BPFFile::updateNumberOfPoints() { //doesn't make sense to update if only header data has been read if(this->headerDataOnly) return; else this->numberOfPoints = xValues.size(); return; } void BPFFile::updateNumberOfExtraFields() { //don't update if only header data has been loaded if(!this->headerDataOnly) this->numberOfExtraFields = extraFields.size(); } bool BPFFile::writeBPFFileV3(const string& filename) { ofstream fout; fout.open(filename.c_str(), ios_base::binary); if(!fout.is_open()) return false; writeBPFFileV3(fout); fout.close(); return true; } void BPFFile::writeBPFFileV3(ofstream& fout) { try { updateNumberOfPoints(); updateNumberOfExtraFields(); //POS 0: Write ASCII Magic Number Identifier ("BPF!") fout.write(ASCII_MAGIC_NUMBER_STRING, 4); //POS 4: write version const char* ASCII_FORMAT_VERSION = "0003"; fout.write(ASCII_FORMAT_VERSION, 4); //POS 8: write header length int v3HeaderSize = HEADER_SIZE_V3 + 56*(this->numberOfExtraFields+3); fout.write((char*)&v3HeaderSize, 4); //POS 12: number of dimensions (uchar) //3 added because this class stores x, y, and z seperately from the extra fields unsigned char numberOfDims = this->numberOfExtraFields + 3; fout.write((char*)&numberOfDims, 1); unsigned char tempChar = 0; //POS 13: interleaved (uchar) fout.write((char*)&tempChar, 1); //POS 14: compressed file (uchar) fout.write((char*)&this->isCompressed, 1); //POS 15: unused (char) char unusedChar = 'X'; fout.write((char*)&unusedChar, 1); //POS 16: point count (int 32) updateNumberOfPoints(); //must be called in case points have been added fout.write((char*)&this->numberOfPoints, 4); //POS 20: coordinate space type (int 32) fout.write((char*)&this->coordinateSystem, 4); //POS 24: coordinate space ID (utm zone) (int 32) fout.write((char*)&this->zone, 4); //POS 28: point spacing fout.write((char*)&this->pointSpacing, 4); //POS 32: transformation matrix (16 x float64) fout.write((char*)this->transformMatrix, 128); //POS 160: start time (float64) fout.write((char*)&this->startTime, 8); //POS 168: end time (float 64) fout.write((char*)&this->endTime, 8); //Metadata subheader //write xOffset fout.write((char*)&this->xOffset, sizeof(double)); //write yOffset fout.write((char*)&this->yOffset, sizeof(double)); //write zOffset fout.write((char*)&this->zOffset, sizeof(double)); //write offsets for other fields for(unsigned int i = 0; i < fieldOffsets.size(); i++) fout.write((char*)&fieldOffsets[i], sizeof(double)); //minimums updateXYZMinsAndMaxs(); fout.write((char*)&this->xMin, sizeof(double)); fout.write((char*)&this->yMin, sizeof(double)); fout.write((char*)&this->zMin, sizeof(double)); updateFieldMinsAndMaxs(); for(unsigned int i = 0; i< minFieldValues.size(); i++) fout.write((char*)&minFieldValues[i], sizeof(double)); //maximums fout.write((char*)&this->xMax, sizeof(double)); fout.write((char*)&this->yMax, sizeof(double)); fout.write((char*)&this->zMax, sizeof(double)); for(unsigned int i = 0; i < maxFieldValues.size(); i++) fout.write((char*)&maxFieldValues[i], sizeof(double)); //field labels char tempStr[FIELD_LABEL_LENGTH]; //zero tempStr for(int j=0; j<FIELD_LABEL_LENGTH; j++) tempStr[j] = (char)0; strcpy(tempStr, "X"); fout.write(tempStr, FIELD_LABEL_LENGTH); strcpy(tempStr, "Y"); fout.write(tempStr, FIELD_LABEL_LENGTH); strcpy(tempStr, "Z"); fout.write(tempStr, FIELD_LABEL_LENGTH); for(unsigned int i = 0; i < fieldLabels.size(); i++) { //zero tempStr for(int j=0; j<FIELD_LABEL_LENGTH; j++) tempStr[j] = (char)0; strcpy(tempStr, fieldLabels[i].c_str()); //write fout.write(tempStr, FIELD_LABEL_LENGTH); } if(true) { //write data compressed float* writeBuf = new float[this->numberOfPoints]; //write X values for(unsigned int i = 0; i < this->numberOfPoints; i++) writeBuf[i] = xValues[i]; writeBytesToFile(fout, (char*)writeBuf, sizeof(float) * this->numberOfPoints); //write Y values for(unsigned int i = 0; i < this->numberOfPoints; i++) writeBuf[i] = yValues[i]; writeBytesToFile(fout, (char*)writeBuf, sizeof(float) * this->numberOfPoints); //write Z values for(unsigned int i = 0; i < this->numberOfPoints; i++) writeBuf[i] = zValues[i]; writeBytesToFile(fout, (char*)writeBuf, sizeof(float) * this->numberOfPoints); //write extra fields values for(unsigned int i = 0; i < extraFields.size(); i++) { for(int j = 0; j < this->numberOfPoints; j++) writeBuf[j] = (*extraFields[i])[j]; writeBytesToFile(fout, (char*)writeBuf, sizeof(float) * this->numberOfPoints); } delete [] writeBuf; } else { //fill output buffer with number of points equal to //INTERLEAVED_POINTS_PER_COMPRESSED_BLOCK unsigned long int pointRecordSize = (3 + extraFields.size()); unsigned long int writeBufSize = pointRecordSize * INTERLEAVED_POINTS_PER_COMPRESSED_BLOCK; float* writeBuf = new float[writeBufSize]; unsigned int ptsWritten = 0; while(ptsWritten < this->numberOfPoints) { //fill the buffer or fill with as many points as possible unsigned int ptsInBuf = 0; unsigned int bufferPos = 0; while(ptsInBuf < INTERLEAVED_POINTS_PER_COMPRESSED_BLOCK && ptsWritten < this->numberOfPoints) { writeBuf[bufferPos++] = xValues[ptsWritten]; writeBuf[bufferPos++] = yValues[ptsWritten]; writeBuf[bufferPos++] = zValues[ptsWritten]; for(unsigned int i = 0; i < extraFields.size(); i++) { writeBuf[bufferPos++] = (*extraFields[i])[ptsWritten]; } ptsInBuf++; ptsWritten++; } writeBytesToFile(fout, (char*)writeBuf, sizeof(float) * pointRecordSize * ptsInBuf); } delete [] writeBuf; } } catch(ios_base::failure&) { cerr << "Error writing to file in BPFFile::writeBPFFileV3" << endl; return; } } void BPFFile::writeBPFFile(ofstream& fout) { try { //write static header section //update header length updateHeaderLength(); //write header length fout.write((char*)&this->headerLength, sizeof(int)); //write version int outVersion = 1; fout.write((char*)&outVersion, sizeof(int)); //write number of Points updateNumberOfPoints(); fout.write((char*)&this->numberOfPoints, sizeof(int)); //write number of extra fields updateNumberOfExtraFields(); fout.write((char*)&this->numberOfExtraFields, sizeof(int)); //write coordinate system fout.write((char*)&this->coordinateSystem, sizeof(int)); //write zone fout.write((char*)&this->zone, sizeof(int)); //write pointSpacing fout.write((char*)&this->pointSpacing, sizeof(float)); //write xOffset fout.write((char*)&this->xOffset, sizeof(double)); //write yOffset fout.write((char*)&this->yOffset, sizeof(double)); //write zOffset fout.write((char*)&this->zOffset, sizeof(double)); //update the minimum values and maximum values updateXYZMinsAndMaxs(); fout.write((char*)&this->xMin, sizeof(double)); fout.write((char*)&this->xMax, sizeof(double)); fout.write((char*)&this->yMin, sizeof(double)); fout.write((char*)&this->yMax, sizeof(double)); fout.write((char*)&this->zMin, sizeof(double)); fout.write((char*)&this->zMax, sizeof(double)); //write variable length header section //write field offsets for(unsigned int i = 0; i < fieldOffsets.size(); i++) fout.write((char*)&fieldOffsets[i], sizeof(double)); //write field minimum values updateFieldMinsAndMaxs(); for(unsigned int i = 0; i< minFieldValues.size(); i++) fout.write((char*)&minFieldValues[i], sizeof(double)); for(unsigned int i = 0; i < maxFieldValues.size(); i++) fout.write((char*)&maxFieldValues[i], sizeof(double)); //write field labels char tempStr[FIELD_LABEL_LENGTH]; for(unsigned int i = 0; i < fieldLabels.size(); i++) { //zero tempStr for(int j=0; j<FIELD_LABEL_LENGTH; j++) tempStr[j] = (char)0; strcpy(tempStr, fieldLabels[i].c_str()); //write fout.write(tempStr, FIELD_LABEL_LENGTH); } //write X, Y, and Z values for(unsigned int i = 0; i < xValues.size(); i++) { fout.write((char*)&xValues[i], sizeof(float)); } for(unsigned int i = 0; i < yValues.size(); i++) { fout.write((char*)&yValues[i], sizeof(float)); } for(unsigned int i = 0; i < zValues.size(); i++) { fout.write((char*)&zValues[i], sizeof(float)); } //write extra field values for(unsigned int i = 0; i < extraFields.size(); i++) { for(unsigned int j = 0; j < extraFields[i]->size(); j++) { fout.write((char*)&(*extraFields[i])[j], sizeof(float)); } } } catch(ios_base::failure&) { cerr << "Error writing to file in BPFFile::writeToBPFFile" << endl; return; } } bool BPFFile::getExtraFieldValueByName(const int n, const string& name, double& valueOut) { //find field with name "name" for(int i = 0; i < fieldLabels.size(); i++) { if(fieldLabels[i] == name) { if(n >= extraFields[i]->size()) return false; valueOut = fieldOffsets[i] + (*extraFields[i])[n]; return true; } } return false; } string BPFFile::getExtraFieldName(const int fieldNum) const { if(fieldNum >= 0 && fieldNum < fieldLabels.size()) return fieldLabels[fieldNum]; else return ""; } double BPFFile::getExtraFieldValueByNumber(const int fieldNum, const int pointNum) const { if(fieldNum < this->numberOfExtraFields) { return fieldOffsets[fieldNum] + (*extraFields[fieldNum])[pointNum]; } return 0.0; } float BPFFile::getExtraFieldValueByNumberNoOffset(const int fieldNum, const int pointNum) const { if(fieldNum < this->numberOfExtraFields) { return (*extraFields[fieldNum])[pointNum]; } return 0.0; } unsigned int BPFFile::getExtraFieldNumberByName(const string& fieldName) const { for(int i = 0; i < fieldLabels.size(); i++) { if(fieldLabels[i] == fieldName) { return i; } } throw ParameterOutOfRange("Field name <" + fieldName + "> does not exist"); return 0; } bool BPFFile::readBPFFile(const string& filename, bool readHeaderOnly) { ifstream fin; fin.open(filename.c_str(), ios_base::binary); if(!fin.is_open()) return false; else { readBPFFile(fin, readHeaderOnly); fin.close(); return true; } } void BPFFile::readBPFFile(ifstream& fin, bool readHeaderOnly) { this->version = this->determineFileVersion(fin); this->headerDataOnly = readHeaderOnly; if(this->version == 1) this->readBPFV1File(fin); else if(this->version == 2) cerr << "Can't read BPF2 just yet" << endl; else if(this->version == 3) this->readBPFV3File(fin); else cerr << "Invalid BPF file" << endl; return; } void BPFFile::readBPFHeader(ifstream& fin) { this->version = this->determineFileVersion(fin); if(this->version == 1) this->readBPFV1Header(fin); else if(this->version == 2) cerr << "Can't read BPF2 just yet" << endl; else if(this->version == 3) this->readBPFV3Header(fin); else cerr << "Invalid BPF file" << endl; return; } void BPFFile::readBPFV3Header(ifstream& fin) { if(fin.is_open()) { unsigned int calculatedFileSize; unsigned int actualFileSize; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); fin.seekg(0, ios::beg); this->headerDataOnly = true; try { //read header length fin.seekg(this->HEADER_LENGTH_POS_V3, ios::beg); fin.read((char*)&this->headerLength, sizeof(int)); //read number of dimensions unsigned char numberOfDims; fin.read((char*)&numberOfDims, sizeof(unsigned char)); //BPF3 includes x, y, and z in this number, store in BPF1/2 format this->numberOfExtraFields = numberOfDims - 3; //read interleaved flag fin.read((char*)&this->interleaved, sizeof(unsigned char)); //read compressed flag fin.read((char*)&this->isCompressed, sizeof(unsigned char)); //read point count fin.seekg(this->POINT_COUNT_POS_V3, ios::beg); fin.read((char*)&this->numberOfPoints, sizeof(int)); //read coordinate system fin.read((char*)&this->coordinateSystem, sizeof(int)); //read utm zone fin.read((char*)&this->zone, sizeof(int)); //read point spacing fin.read((char*)&this->pointSpacing, sizeof(float)); //read transform matrix for(int row = 0; row < 4; row++) for(int col = 0; col < 4; col++) fin.read((char*)&this->transformMatrix[row][col], sizeof(double)); //read start time fin.read((char*)&this->startTime, sizeof(double)); //read end time fin.read((char*)&this->endTime, sizeof(double)); //READ METADATA SUBHEADER fin.seekg(this->HEADER_SIZE_V3, ios::beg); //read x offset int sizeOfDouble = sizeof(double); fin.read((char*)&this->xOffset, sizeof(double)); //read y offset fin.read((char*)&this->yOffset, sizeof(double)); //read z offset fin.read((char*)&this->zOffset, sizeof(double)); //read additional field offsets double* tempDoubleArray = new double[this->numberOfExtraFields]; fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) fieldOffsets.push_back(tempDoubleArray[i]); //read x min fin.read((char*)&this->xMin, sizeof(double)); //read y min fin.read((char*)&this->yMin, sizeof(double)); //read z min fin.read((char*)&this->zMin, sizeof(double)); //read additional field minimums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) minFieldValues.push_back(tempDoubleArray[i]); //read x max fin.read((char*)&this->xMax, sizeof(double)); //read y max fin.read((char*)&this->yMax, sizeof(double)); //read z max fin.read((char*)&this->zMax, sizeof(double)); //read additional field maximums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) maxFieldValues.push_back(tempDoubleArray[i]); delete [] tempDoubleArray; //skip reading x, y, and z field labels fin.clear(); unsigned int fieldLabelPos = this->HEADER_SIZE_V3 + 24*numberOfDims + 32*3; fin.seekg(fieldLabelPos); //read field labels char* tempCharArray = new char[FIELD_LABEL_LENGTH]; for(int i = 0; i < numberOfExtraFields; i++) { fin.read(tempCharArray, FIELD_LABEL_LENGTH); fieldLabels.push_back(string(tempCharArray)); } delete [] tempCharArray; } catch(std::exception& e) { throw BPFFile::IOFailure("Attempt to read BPF failed when calling ifstream.read"); } } } void BPFFile::readBPFV3File(ifstream& fin) { if(fin.is_open()) { unsigned int calculatedFileSize; unsigned int actualFileSize; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); fin.seekg(0, ios::beg); try { //read header length fin.seekg(this->HEADER_LENGTH_POS_V3, ios::beg); fin.read((char*)&this->headerLength, sizeof(int)); //read number of dimensions unsigned char numberOfDims; fin.read((char*)&numberOfDims, sizeof(unsigned char)); //BPF3 includes x, y, and z in this number, store in BPF1/2 format this->numberOfExtraFields = numberOfDims - 3; //read interleaved flag fin.read((char*)&this->interleaved, sizeof(unsigned char)); //read compressed flag fin.read((char*)&this->isCompressed, sizeof(unsigned char)); //read point count fin.seekg(this->POINT_COUNT_POS_V3, ios::beg); fin.read((char*)&this->numberOfPoints, sizeof(int)); //read coordinate system fin.read((char*)&this->coordinateSystem, sizeof(int)); //read utm zone fin.read((char*)&this->zone, sizeof(int)); //read point spacing fin.read((char*)&this->pointSpacing, sizeof(float)); //read transform matrix for(int row = 0; row < 4; row++) for(int col = 0; col < 4; col++) fin.read((char*)&this->transformMatrix[row][col], sizeof(double)); //read start time fin.read((char*)&this->startTime, sizeof(double)); //read end time fin.read((char*)&this->endTime, sizeof(double)); //READ METADATA SUBHEADER fin.seekg(this->HEADER_SIZE_V3, ios::beg); //read x offset int sizeOfDouble = sizeof(double); fin.read((char*)&this->xOffset, sizeof(double)); //read y offset fin.read((char*)&this->yOffset, sizeof(double)); //read z offset fin.read((char*)&this->zOffset, sizeof(double)); //read additional field offsets double* tempDoubleArray = new double[this->numberOfExtraFields]; fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) fieldOffsets.push_back(tempDoubleArray[i]); //read x min fin.read((char*)&this->xMin, sizeof(double)); //read y min fin.read((char*)&this->yMin, sizeof(double)); //read z min fin.read((char*)&this->zMin, sizeof(double)); //read additional field minimums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) minFieldValues.push_back(tempDoubleArray[i]); //read x max fin.read((char*)&this->xMax, sizeof(double)); //read y max fin.read((char*)&this->yMax, sizeof(double)); //read z max fin.read((char*)&this->zMax, sizeof(double)); //read additional field maximums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) maxFieldValues.push_back(tempDoubleArray[i]); delete [] tempDoubleArray; //skip reading x, y, and z field labels fin.clear(); unsigned int fieldLabelPos = this->HEADER_SIZE_V3 + 24*numberOfDims + 32*3; fin.seekg(fieldLabelPos); //read field labels char* tempCharArray = new char[FIELD_LABEL_LENGTH]; for(int i = 0; i < numberOfExtraFields; i++) { fin.read(tempCharArray, FIELD_LABEL_LENGTH); fieldLabels.push_back(string(tempCharArray)); } delete [] tempCharArray; // JFD added if (suppressExtraFieldFlags == NULL) { suppressExtraFieldFlags = new int[numberOfExtraFields]; memset(suppressExtraFieldFlags, 0, numberOfExtraFields * sizeof(int)); } if(this->headerDataOnly) return; if(this->interleaved == 0) { //seek to beginning of points fin.seekg(this->headerLength, ios::beg); //read point data non-interleaved float* tempFloatArray = new float[this->numberOfPoints]; //read x this->readBytesFromFile(fin, (char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) xValues.push_back(tempFloatArray[i]); //read y this->readBytesFromFile(fin, (char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) yValues.push_back(tempFloatArray[i]); //read z this->readBytesFromFile(fin, (char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) zValues.push_back(tempFloatArray[i]); //read extra field values for(int i = 0; i < this->numberOfExtraFields; i++) { extraFields.push_back(new vector<float>); this->readBytesFromFile(fin, (char*)tempFloatArray, sizeof(float) * this->numberOfPoints); if (suppressExtraFieldFlags[i]) continue; for(int j = 0; j < this->numberOfPoints; j=j+nStride) extraFields[i]->push_back(tempFloatArray[j]); } delete [] tempFloatArray; } else //is interleaved { //seek to beginning of points fin.seekg(this->headerLength, ios::beg); float* floatTemp = new float[numberOfDims]; for(int i = 0; i < this->numberOfExtraFields; i++) this->extraFields.push_back(new vector<float>); for(int point = 0; point < this->numberOfPoints; point++) { this->readBytesFromFile(fin, (char*)floatTemp, 4 * numberOfDims); // Transfer only every nStride'th point if (point % nStride == 0) { this->xValues.push_back(floatTemp[0]); this->yValues.push_back(floatTemp[1]); this->zValues.push_back(floatTemp[2]); for(int extraDimNum = 3; extraDimNum < numberOfDims; extraDimNum++) { if (!suppressExtraFieldFlags[extraDimNum-3]) this->extraFields[extraDimNum-3]->push_back(floatTemp[extraDimNum]); } } } delete [] floatTemp; } } catch(std::exception& e) { throw BPFFile::IOFailure("Attempt to read BPF failed when calling ifstream.read"); } } else { throw BPFFile::IOFailure("Attempt to read failed because file not open."); } } void BPFFile::readBPFV1Header(ifstream& fin) { if(fin.is_open()) { unsigned int calculatedFileSize; unsigned int actualFileSize; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); fin.seekg(0, ios::beg); this->headerDataOnly = true; try { //all of these values are considered suspect until the //actual values are calculated from the data and compared //read header size fin.read((char*)&this->headerLength, sizeof(int)); //read version fin.read((char*)&this->version, sizeof(int)); //read number of points fin.read((char*)&this->numberOfPoints, sizeof(int)); //read numberOfExtraFields fin.read((char*)&this->numberOfExtraFields, sizeof(int)); //read coordinate system fin.read((char*)&this->coordinateSystem, sizeof(int)); //read utm zone fin.read((char*)&this->zone, sizeof(int)); //read point spacing fin.read((char*)&this->pointSpacing, sizeof(float)); //read x offset fin.read((char*)&this->xOffset, sizeof(double)); //read y offset fin.read((char*)&this->yOffset, sizeof(double)); //read z offset fin.read((char*)&this->zOffset, sizeof(double)); //read x min fin.read((char*)&this->xMin, sizeof(double)); //read x max fin.read((char*)&this->xMax, sizeof(double)); //read y min fin.read((char*)&this->yMin, sizeof(double)); //read y max fin.read((char*)&this->yMax, sizeof(double)); //read z min fin.read((char*)&this->zMin, sizeof(double)); //read z max fin.read((char*)&this->zMax, sizeof(double)); //before going any further, let's validate the claimed number of points and number of extra fields calculatedFileSize = this->headerLength + 12*this->numberOfPoints + 4*this->numberOfExtraFields*this->numberOfPoints; char msg[150]; if(calculatedFileSize != actualFileSize) { sprintf(msg, "Actual filesize = %d, calculated file size = %d", actualFileSize, calculatedFileSize); fin.close(); throw BPFFile::InvalidBPFData(msg); } //if we're here, then we know "numberOfPoints" and "numberOfExtraFields" are valid //read field offsets double* tempDoubleArray = new double[this->numberOfExtraFields]; //read field offsets fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) fieldOffsets.push_back(tempDoubleArray[i]); //read field minimums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) minFieldValues.push_back(tempDoubleArray[i]); //read field maximums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) maxFieldValues.push_back(tempDoubleArray[i]); delete [] tempDoubleArray; //read field labels char* tempCharArray = new char[FIELD_LABEL_LENGTH]; for(int i = 0; i < numberOfExtraFields; i++) { fin.read(tempCharArray, FIELD_LABEL_LENGTH); fieldLabels.push_back(string(tempCharArray)); } delete [] tempCharArray; fin.close(); } catch(std::exception& e) { throw BPFFile::IOFailure("Attempt to read BPF failed when calling ifstream.read"); } } else { throw BPFFile::IOFailure("Attempt to read failed because file not open."); } } void BPFFile::readBPFV1File(ifstream& fin) { if(fin.is_open()) { unsigned int calculatedFileSize; unsigned int actualFileSize; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); fin.seekg(0, ios::beg); this->isCompressed = 0; //can't be since its V1 this->interleaved = 0; //again, can't be in V1 try { //all of these values are considered suspect until the //actual values are calculated from the data and compared //read header size fin.read((char*)&this->headerLength, sizeof(int)); //read version fin.read((char*)&this->version, sizeof(int)); //read number of points fin.read((char*)&this->numberOfPoints, sizeof(int)); //read numberOfExtraFields fin.read((char*)&this->numberOfExtraFields, sizeof(int)); //read coordinate system fin.read((char*)&this->coordinateSystem, sizeof(int)); //read utm zone fin.read((char*)&this->zone, sizeof(int)); //read point spacing fin.read((char*)&this->pointSpacing, sizeof(float)); //read x offset fin.read((char*)&this->xOffset, sizeof(double)); //read y offset fin.read((char*)&this->yOffset, sizeof(double)); //read z offset fin.read((char*)&this->zOffset, sizeof(double)); //read x min fin.read((char*)&this->xMin, sizeof(double)); //read x max fin.read((char*)&this->xMax, sizeof(double)); //read y min fin.read((char*)&this->yMin, sizeof(double)); //read y max fin.read((char*)&this->yMax, sizeof(double)); //read z min fin.read((char*)&this->zMin, sizeof(double)); //read z max fin.read((char*)&this->zMax, sizeof(double)); //before going any further, let's validate the claimed number of points and number of extra fields calculatedFileSize = this->headerLength + 12*this->numberOfPoints + 4*this->numberOfExtraFields*this->numberOfPoints; char msg[150]; if(calculatedFileSize != actualFileSize) { sprintf(msg, "Actual filesize = %d, calculated file size = %d", actualFileSize, calculatedFileSize); fin.close(); throw BPFFile::InvalidBPFData(msg); } //if we're here, then we know "numberOfPoints" and "numberOfExtraFields" are valid //read field offsets double* tempDoubleArray = new double[this->numberOfExtraFields]; //read field offsets fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) fieldOffsets.push_back(tempDoubleArray[i]); //read field minimums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) minFieldValues.push_back(tempDoubleArray[i]); //read field maximums fin.read((char*)tempDoubleArray, sizeof(double) * numberOfExtraFields); for(int i = 0; i < numberOfExtraFields; i++) maxFieldValues.push_back(tempDoubleArray[i]); delete [] tempDoubleArray; //read field labels char* tempCharArray = new char[FIELD_LABEL_LENGTH]; for(int i = 0; i < numberOfExtraFields; i++) { fin.read(tempCharArray, FIELD_LABEL_LENGTH); fieldLabels.push_back(string(tempCharArray)); } delete [] tempCharArray; // JFD added if (suppressExtraFieldFlags == NULL) { suppressExtraFieldFlags = new int[numberOfExtraFields]; memset(suppressExtraFieldFlags, 0, numberOfExtraFields * sizeof(int)); } if(this->headerDataOnly) return; //have to put this here because some groups jam non-standard stuff in the header fin.seekg(this->headerLength, ios::beg); //read point data float* tempFloatArray = new float[this->numberOfPoints]; //read x fin.read((char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) xValues.push_back(tempFloatArray[i]); //read y fin.read((char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) yValues.push_back(tempFloatArray[i]); //read z fin.read((char*)tempFloatArray, sizeof(float) * this->numberOfPoints); for(int i = 0; i < this->numberOfPoints; i=i+nStride) zValues.push_back(tempFloatArray[i]); //read extra field values for(int i = 0; i < this->numberOfExtraFields; i++) { extraFields.push_back(new vector<float>); fin.read((char*)tempFloatArray, sizeof(float) * this->numberOfPoints); if (suppressExtraFieldFlags[i]) continue; for(int j = 0; j < this->numberOfPoints; j=j+nStride) extraFields[i]->push_back(tempFloatArray[j]); } delete [] tempFloatArray; fin.close(); } catch(std::exception& e) { throw BPFFile::IOFailure("Attempt to read BPF failed when calling ifstream.read"); } } else { throw BPFFile::IOFailure("Attempt to read failed because file not open."); } } bool BPFFile::xyzMinMaxMinusAircraftTrack(double& xMin, double& xMax, double& yMin, double& yMax, double& zMin, double& zMax) const { xMin = yMin = zMin = DBL_MAX; xMax = yMax = zMax = DBL_MIN; unsigned int pixelFieldNum; try { pixelFieldNum = this->getExtraFieldNumberByName("Pixel Number"); } catch(ParameterOutOfRange e) { return false; } for(unsigned int pt = 0; pt < this->numberOfPoints; pt++) { if((*extraFields[pixelFieldNum])[pt] != -5.0) { xMin = min(xMin, (double)xValues[pt]); xMax = max(xMax, (double)xValues[pt]); yMin = min(yMin, (double)yValues[pt]); yMax = max(yMax, (double)yValues[pt]); zMin = min(zMin, (double)zValues[pt]); zMax = max(zMax, (double)zValues[pt]); } } xMin += xOffset; xMax += xOffset; yMin += yOffset; yMax += yOffset; zMin += zOffset; zMax += zOffset; return true; } #define C1WIDTH 30 #define C2WIDTH 15 #define C3WIDTH 15 #define C4WIDTH 15 ostream& operator<<(ostream& out, BPFFile& bpf) { double minMaxNoAT[3][2]; bool isAnAT = bpf.xyzMinMaxMinusAircraftTrack(minMaxNoAT[0][0], minMaxNoAT[0][1], minMaxNoAT[1][0], minMaxNoAT[1][1], minMaxNoAT[2][0], minMaxNoAT[2][1]); bpf.updateXYZMinsAndMaxs(); bpf.updateFieldMinsAndMaxs(); out << "--------------------------------------------------------------------------" << endl; out << "Header Length : " << bpf.headerLength << endl; out << "Version : " << bpf.version << endl; out << "Number of Points : " << bpf.numberOfPoints << endl; out << "Number of Extra Fields : " << bpf.numberOfExtraFields << endl; out << "Interleaved : " << (unsigned int)bpf.interleaved << endl; out << "Compressed : " << (bpf.isCompressed == 0 ? "No" : "Yes") << endl; out << "Coordinate System : " << bpf.coordinateSystem << endl; out << "Zone : " << bpf.zone << endl; out << "Point Spacing : " << bpf.pointSpacing << endl; out << "X Offset : " << bpf.xOffset << endl; out << "Y Offset : " << bpf.yOffset << endl; out << "Z Offset : " << bpf.zOffset << endl; out.precision(20); out << "X Min : " << (isAnAT ? minMaxNoAT[0][0] : bpf.xMin) << endl; out << "X Max : " << (isAnAT ? minMaxNoAT[0][1] : bpf.xMax) << endl; out << "Y Min : " << (isAnAT ? minMaxNoAT[1][0] : bpf.yMin) << endl; out << "Y Max : " << (isAnAT ? minMaxNoAT[1][1] : bpf.yMax) << endl; out << "Z Min : " << (isAnAT ? minMaxNoAT[2][0] : bpf.zMin) << endl; out << "Z Max : " << (isAnAT ? minMaxNoAT[2][1] : bpf.zMax) << endl; out << "Aircraft Track in BPF? : " << (isAnAT ? "Yes" : "No") << endl; out << "--------------------------------------------------------------------------" << endl; out.width(C1WIDTH); out.precision(3); out.setf(ios::left, ios::adjustfield); out << "Field Label"; out.width(C2WIDTH); out.setf(ios::left, ios::adjustfield); out << "Min"; out.width(C3WIDTH); out.setf(ios::left, ios::adjustfield); out << "Max"; out.width(C4WIDTH); out.setf(ios::left, ios::adjustfield); out << "Offset" << endl; for(int i = 0; i < bpf.numberOfExtraFields; i++) { out.width(C1WIDTH); out.precision(3); out.setf(ios::left, ios::adjustfield); out << bpf.fieldLabels[i]; out.width(C2WIDTH); out.setf(ios::left, ios::adjustfield); out << bpf.minFieldValues[i]; out.width(C3WIDTH); out.setf(ios::left, ios::adjustfield); out << bpf.maxFieldValues[i]; out.width(C4WIDTH); out.setf(ios::left, ios::adjustfield); out << bpf.fieldOffsets[i] << endl; } return out; } bool BPFFile::isValidBPFV3File(ifstream& fin) { unsigned long long actualFileSize; unsigned long long calculatedFileSize; int headerLength; int pointCount; unsigned char metaDataDims; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); if(actualFileSize < HEADER_SIZE_V3) return false; fin.seekg(BPFFile::HEADER_LENGTH_POS_V3, ios::beg); fin.read((char*)&headerLength, sizeof(int)); fin.seekg(BPFFile::NUMBER_OF_DIMS_POS_V3, ios::beg); fin.read((char*)&metaDataDims, sizeof(unsigned char)); fin.seekg(BPFFile::POINT_COUNT_POS_V3, ios::beg); fin.read((char*)&pointCount, 4); calculatedFileSize = (unsigned long long)headerLength + (unsigned long long)metaDataDims*(unsigned long long)pointCount*4; if(actualFileSize == calculatedFileSize) return true; else return false; } bool BPFFile::isValidBPFV1File(ifstream& fin) { return this->isValidBPFV2File(fin); } bool BPFFile::isValidBPFV2File(ifstream& fin) { unsigned long long actualFileSize; unsigned long long calculatedFileSize; int headerLength; int pointCount; int metaDataDims; fin.seekg(0, ios::end); actualFileSize = fin.tellg(); if(actualFileSize < HEADER_SIZE_V2) return false; fin.seekg(0, ios::beg); //read header length fin.read((char*)&headerLength, sizeof(int)); //read point count fin.seekg(8, ios::beg); fin.read((char*)&pointCount, sizeof(int)); //read number metadata dims fin.seekg(12, ios::beg); fin.read((char*)&metaDataDims, sizeof(int)); //calculate file size calculatedFileSize = (unsigned long long)headerLength + ((unsigned long long)pointCount)*12 + ((unsigned long long)metaDataDims*pointCount)*4; if(actualFileSize == calculatedFileSize) return true; else return false; } void BPFFile::renameExtraField(const string& curName, const string& newName) { unsigned int fieldNum = this->getExtraFieldNumberByName(curName); fieldLabels[fieldNum] = newName; return; } int BPFFile::determineFileVersion(ifstream& fin) { int versionNum = 0; char magicNumber[5]; char versionStr[5]; //reset file pointer fin.seekg(0, ios::beg); //read first 4 bytes fin.read((char*)magicNumber, sizeof(int)); magicNumber[4] = '\0'; //if version 3 //read second 4 bytes fin.read((char*)&versionNum, sizeof(int)); //if version 1 or 2 memcpy((void*)versionStr, (void*)&versionNum, 4); versionStr[4] = '\0'; //if version 3 if(versionNum == 1) { //validate as v1 file if(this->isValidBPFV1File(fin)) return 1; else return 0; } else if (versionNum == 2) { //validate as v2 file if(this->isValidBPFV2File(fin)) return 2; else return 0; } if(strncmp(magicNumber, "BPF!",4)==0 && strncmp(versionStr, "0003",4)==0) { return 3; //validate as v3 file if(this->isValidBPFV3File(fin)) return 3; else return 0; } else return 0; } void BPFFile::printPoint(unsigned int n) const { cout << "X : " << this->getXValue(n) << endl; cout << "Y : " << this->getYValue(n) << endl; cout << "Z : " << this->getZValue(n) << endl; //print extra fields for(int i = 0; i < extraFields.size(); i++) { cout << this->getExtraFieldName(i) << " : " << this->getExtraFieldValueByNumber(i, n) << endl; } return; } void BPFFile::writeBytesToFile(ofstream& fout, const char* buf, unsigned int bytesToWrite) { //check if file is open if(!fout.is_open()) return; if(this->isCompressed == 0) //no compression { fout.write(buf, bytesToWrite); } else if(this->isCompressed == 1) //quick lz { cerr << "QuickLZ writing not implemented" << endl; exit(1); } else if(this->isCompressed == 2) //fast lz { #if defined(LIBS_FASTLZ) unsigned int uncompressedSize = bytesToWrite; unsigned int compressedSize = bytesToWrite; //write the uncompressed size to the file fout.write((char*)&uncompressedSize, sizeof(unsigned int)); //create compressed buffer char* compressedBuffer; int compressedBufferSize = max((int)ceil(uncompressedSize*1.05), 66); //see fast lz documentation compressedBuffer = new char[compressedBufferSize]; unsigned int actualCompressedSize = 0; //compress the data if it is larger than 16 bytes (see fastlz docs) if(uncompressedSize > 16) { actualCompressedSize = fastlz_compress_level(2, (const void*)buf, uncompressedSize, (void*)compressedBuffer); } else actualCompressedSize = uncompressedSize; if(actualCompressedSize < uncompressedSize) { //write compressed size to file fout.write((char*)&actualCompressedSize, sizeof(unsigned int)); //write compressed buffer to file fout.write(compressedBuffer, actualCompressedSize); } else //just write the original bytes to the file { //write compressed size to file (which in this case is the original size fout.write((char*)&uncompressedSize, sizeof(unsigned int)); //write uncompressed buffer fout.write(buf, uncompressedSize); } delete [] compressedBuffer; #else #endif } return; } void BPFFile::readBytesFromFile(ifstream& fin, char* buf, unsigned int bytesToRead) { //check if file is open if(!fin.is_open()) return; //if not compressed, read as normal if(!this->isCompressed) { fin.read(buf, bytesToRead); } else if(this->isCompressed == 1) //is compressed, read with quicklz { #if defined(MFC_QUICKLZ) unsigned int decompressedBytesRead = 0; //read compressed bytes until decompressed bytes read >= bytes to Read while(decompressedBytesRead < bytesToRead) { //if buffer has unread decompressed bytes left in it read those first if(decompressedBytesBufferPos < decompressedBytesBufferSize) { //read the lesser of the bytes in the buffer or the bytes left to read unsigned int numBytesLeftInBuffer = decompressedBytesBufferSize - decompressedBytesBufferPos; unsigned int curReadBytes = min(bytesToRead - decompressedBytesRead, numBytesLeftInBuffer); memcpy(buf + decompressedBytesRead, this->decompressedBytesBuffer + this->decompressedBytesBufferPos, curReadBytes); decompressedBytesBufferPos += curReadBytes; decompressedBytesRead += curReadBytes; } else //decompressed bytes buffer is empty, refill { qlz_state_decompress state; char* compressedBuffer = NULL; unsigned int compressedBufferSize = 0; //delete old buffer delete [] decompressedBytesBuffer; //read next byte from file, which has the size of the subsequent compressed chunk fin.read((char*)&compressedBufferSize, sizeof(unsigned int)); //cout << "Compressed buffer size = " << compressedBufferSize << endl; //create new compressed buffer compressedBuffer = new char[compressedBufferSize]; //read in compressed bytes from file fin.read(compressedBuffer, compressedBufferSize); //decompress the compressed chunk and copy it into the decompressed buffer //get the decompressed size, create new decompressed buffer decompressedBytesBufferPos = 0; decompressedBytesBufferSize = qlz_size_decompressed(compressedBuffer); decompressedBytesBuffer = new char[decompressedBytesBufferSize]; //decompress qlz_decompress(compressedBuffer, (void*)decompressedBytesBuffer, &state); //delete compressed buffer delete [] compressedBuffer; } } #else #endif } else if(this->isCompressed == 2) { #if defined(LIBS_FASTLZ) unsigned int decompressedBytesRead = 0; //read compressed bytes until decompressed bytes read >= bytes to Read while(decompressedBytesRead < bytesToRead) { //if buffer has unread decompressed bytes left in it read those first if(decompressedBytesBufferPos < decompressedBytesBufferSize) { //read the lesser of the bytes in the buffer or the bytes left to read unsigned int numBytesLeftInBuffer = decompressedBytesBufferSize - decompressedBytesBufferPos; unsigned int curReadBytes = min(bytesToRead - decompressedBytesRead, numBytesLeftInBuffer); memcpy(buf + decompressedBytesRead, this->decompressedBytesBuffer + this->decompressedBytesBufferPos, curReadBytes); decompressedBytesBufferPos += curReadBytes; decompressedBytesRead += curReadBytes; } else //decompressed bytes buffer is empty, refill { char* compressedBuffer = NULL; unsigned int compressedBufferSize = 0; unsigned int uncompressedBufferSize = 0; //delete old buffer delete [] decompressedBytesBuffer; //read next 4 bytes, is the uncompressed size of the subsequent compressed chunk fin.read((char*)&uncompressedBufferSize,sizeof(unsigned int)); decompressedBytesBufferSize = uncompressedBufferSize; //read next 4 bytes from file, which has the size of the subsequent compressed chunk fin.read((char*)&compressedBufferSize, sizeof(unsigned int)); //cout << "Uncompressed buffer size = " << uncompressedBufferSize << endl; //cout << "Compressed buffer size = " << compressedBufferSize << endl; //create new decompressed bytes buffer decompressedBytesBufferPos = 0; decompressedBytesBuffer = new char[uncompressedBufferSize]; if(uncompressedBufferSize > compressedBufferSize) //data is indeed compressed { //create new compressed buffer compressedBuffer = new char[compressedBufferSize]; //read in compressed bytes from file fin.read(compressedBuffer, compressedBufferSize); fastlz_decompress(compressedBuffer, compressedBufferSize, decompressedBytesBuffer, uncompressedBufferSize); //delete compressed buffer delete [] compressedBuffer; compressedBuffer = NULL; } else if(uncompressedBufferSize == compressedBufferSize) //data is not compressed { //just copy bytes directly from file into decompressed buffer fin.read(decompressedBytesBuffer, uncompressedBufferSize); } else { //error, compressed size should have never been larger than uncompressed size cerr << "ERROR: decompresesd size less than compressed size" << endl; exit(1); } } } #else #endif } } void BPFFile::setXYZOffset(const double& xoff, const double& yoff, const double& zoff) { this->xOffset = xoff; this->yOffset = yoff; this->zOffset = zoff; this->dirtyMinsAndMaxs = true; return; } void BPFFile::setCompression(const unsigned char val) { this->isCompressed = val; } void BPFFile::setExtraFieldValue(unsigned int fieldIndex, unsigned int pointIndex, const double& val) { (*this->extraFields[fieldIndex])[pointIndex] = val - fieldOffsets[fieldIndex]; dirtyFieldMinsAndMaxs = true; return; } //changes the offset value and changes the point values to compensate //the result is that the actual point values do not change at all void BPFFile::changeOffsetX(const double& off) { double offsetDiff = off - this->xOffset; //add the offset diff to each coordinate vector<float>::iterator itr = xValues.begin(); vector<float>::iterator endItr = xValues.end(); while(itr != endItr) { (*itr) = (float)((double)(*itr) - offsetDiff); itr++; } this->xOffset = off; return; } void BPFFile::changeOffsetY(const double& off) { double offsetDiff = off - this->yOffset; //add the offset diff to each coordinate vector<float>::iterator itr = yValues.begin(); vector<float>::iterator endItr = yValues.end(); while(itr != endItr) { (*itr) = (float)((double)(*itr) - offsetDiff); itr++; } this->yOffset = off; return; } void BPFFile::changeOffsetZ(const double& off) { double offsetDiff = off - this->zOffset; //add the offset diff to each coordinate vector<float>::iterator itr = zValues.begin(); vector<float>::iterator endItr = zValues.end(); while(itr != endItr) { (*itr) = (float)((double)(*itr) - offsetDiff); itr++; } this->zOffset = off; return; } void BPFFile::changeOffsetEF(const double& off, const string& fieldName) { unsigned int efi = this->getExtraFieldNumberByName(fieldName); double offsetDiff = off - fieldOffsets[efi]; //add the offset diff to each coordinate vector<float>::iterator itr = (*extraFields[efi]).begin(); vector<float>::iterator endItr = (*extraFields[efi]).end(); while(itr != endItr) { (*itr) = (float)((double)(*itr) - offsetDiff); itr++; } fieldOffsets[efi] = off; return; } bool BPFFile::extractPointsFilterByExtraField(const unsigned int fieldNumber, const double& lowerBound, const double& upperBound, vector<double>& x, vector<double>& y, vector<double>& z) const { if(upperBound < lowerBound) { throw(ParameterOutOfRange("upper bound less than lower bound")); } for(unsigned int pt = 0; pt < this->numberOfPoints; pt++) { double efv = this->getExtraFieldValueByNumber(fieldNumber, pt); if(efv >= lowerBound && efv <= upperBound) { x.push_back(this->getXValue(pt)); y.push_back(this->getYValue(pt)); z.push_back(this->getZValue(pt)); } } return true; } bool BPFFile::extractPointsFilterByExtraField(const unsigned int fieldNumber, const double& lowerBound, const double& upperBound, set<unsigned int>& indices) const { if(upperBound < lowerBound) { throw(ParameterOutOfRange("upper bound less than lower bound")); } for(unsigned int pt = 0; pt < this->numberOfPoints; pt++) { double efv = this->getExtraFieldValueByNumber(fieldNumber, pt); if(efv >= lowerBound && efv <= upperBound) { indices.insert(pt); } } return true; } bool BPFFile::extractExtraFieldFilterByExtraField(const unsigned int keyFieldNumber, const double& lowerBound, const double& upperBound, vector<double>& ef, const unsigned int valueFieldNumber) const { if(upperBound < lowerBound) { throw(ParameterOutOfRange("upper bound less than lower bound")); } for(unsigned int pt = 0; pt < this->numberOfPoints; pt++) { double efv = this->getExtraFieldValueByNumber(keyFieldNumber, pt); if(efv >= lowerBound && efv <= upperBound) { ef.push_back(this->getExtraFieldValueByNumber(valueFieldNumber, pt)); } } return true; } bool BPFFile::extractUniqueValuesFromExtraField(list<double>& vals, unsigned int fieldNumber) const { if(fieldNumber >= extraFields.size()) throw(ParameterOutOfRange("Field number not valid")); //copy extra field values to list double fieldOffsetVal = fieldOffsets[fieldNumber]; vector<float>::const_iterator itr = (*extraFields[fieldNumber]).begin(); while(itr != (*extraFields[fieldNumber]).end()) { vals.push_back(*itr + fieldOffsetVal); itr++; } //run unique on the list (running it first shortens the list some so the sort doesn't take so long) vals.unique(); //sort the list vals.sort(); //run unique again vals.unique(); return true; } void BPFFile::rotatePoints(const double& theta, const double& axisX, const double& axisY, const double& axisZ) { #if defined(LIBS_BOOST) //the axis of rotation Quat r(0, axisX, axisY, axisZ); //normalize r Quat rnorm = r / boost::math::abs(r); //create rotation quaternion // [cos(theta/2) Rx*sin(theta/2) Ry*sin(theta/2) Rz*sin(theta/2)] Quat Qr = Quat(cos(theta/2.0), 0, 0, 0) + (rnorm * sin(theta/2.0)); //Qrconj Quat QrConj = boost::math::conj(Qr); //rotate each point for(unsigned int pt = 0; pt < this->numberOfPoints; pt++) { Quat point(0, (double)xValues[pt], (double)yValues[pt], (double)zValues[pt]); Quat pointRotated = Qr * point * QrConj; //overwrite original point value with new rotated value xValues[pt] = pointRotated.R_component_2(); yValues[pt] = pointRotated.R_component_3(); zValues[pt] = pointRotated.R_component_4(); } //rotate offset values Quat point(0, xOffset, yOffset, zOffset); Quat pointRotated = Qr * point * QrConj; //overwrite original point value with new rotated value xOffset = pointRotated.R_component_2(); yOffset = pointRotated.R_component_3(); zOffset = pointRotated.R_component_4(); dirtyMinsAndMaxs = true; #else #endif return; } void BPFFile::clipPoints(set<unsigned int>& keepers) { //clip all of the storage arrays vector<float> temp; set<unsigned int>::const_iterator itr, endItr = keepers.end(); for(itr = keepers.begin(); itr != endItr; itr++) { temp.push_back(xValues[*itr]); } xValues.clear(); xValues = temp; temp.clear(); for(itr = keepers.begin(); itr != endItr; itr++) { temp.push_back(yValues[*itr]); } yValues.clear(); yValues = temp; temp.clear(); for(itr = keepers.begin(); itr != endItr; itr++) { temp.push_back(zValues[*itr]); } zValues.clear(); zValues = temp; temp.clear(); for(unsigned int field = 0; field < extraFields.size(); field++) { for(itr = keepers.begin(); itr != endItr; itr++) { temp.push_back((*extraFields[field])[*itr]); } (*extraFields[field]).clear(); (*extraFields[field]) = temp; temp.clear(); } updateNumberOfPoints(); updateXYZMinsAndMaxs(); updateFieldMinsAndMaxs(); return; } void BPFFile::clipPoints(const double& xMinClip, const double& xMaxClip, const double& yMinClip, const double& yMaxClip, const double& zMinClip, const double& zMaxClip) { vector<unsigned int> keepers; //indices of points to keep //offset the clipping values float xMinClipOff = xMinClip - xOffset; float xMaxClipOff = xMaxClip - xOffset; float yMinClipOff = yMinClip - yOffset; float yMaxClipOff = yMaxClip - yOffset; float zMinClipOff = zMinClip - zOffset; float zMaxClipOff = zMaxClip - zOffset; //lets find those points to keep unsigned int numPoints = xValues.size(); for(unsigned int i = 0; i < numPoints; i++) { if(xValues[i] >= xMinClipOff && xValues[i] <= xMaxClipOff && yValues[i] >= yMinClipOff && yValues[i] <= yMaxClipOff && zValues[i] >= zMinClipOff && zValues[i] <= zMaxClipOff) keepers.push_back(i); } //clip all of the storage arrays vector<float> temp; for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(xValues[keepers[i]]); } xValues.clear(); xValues = temp; temp.clear(); for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(yValues[keepers[i]]); } yValues.clear(); yValues = temp; temp.clear(); for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(zValues[keepers[i]]); } zValues.clear(); zValues = temp; temp.clear(); for(unsigned int field = 0; field < extraFields.size(); field++) { for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back((*extraFields[field])[keepers[i]]); } (*extraFields[field]).clear(); (*extraFields[field]) = temp; temp.clear(); } updateNumberOfPoints(); updateXYZMinsAndMaxs(); updateFieldMinsAndMaxs(); return; } void BPFFile::getPointsInRange(double& xMin, double& xMax, double& yMin, double& yMax, double& zMin, double& zMax, set<unsigned int>& indices) const { //offset the clipping values float xMinClipOff = xMin - xOffset; float xMaxClipOff = xMax - xOffset; float yMinClipOff = yMin - yOffset; float yMaxClipOff = yMax - yOffset; float zMinClipOff = zMin - zOffset; float zMaxClipOff = zMax - zOffset; //lets find those points to keep unsigned int numPoints = xValues.size(); for(unsigned int i = 0; i < numPoints; i++) { if(xValues[i] >= xMinClipOff && xValues[i] <= xMaxClipOff && yValues[i] >= yMinClipOff && yValues[i] <= yMaxClipOff && zValues[i] >= zMinClipOff && zValues[i] <= zMaxClipOff) indices.insert(i); } } void BPFFile::clipPointsInRangeByExtraFieldValue(const string& extraFieldName, const double& lowerBound, const double& upperBound) { this->clipPointsInRangeByExtraFieldValue(this->getExtraFieldNumberByName(extraFieldName), lowerBound, upperBound); } void BPFFile::clipPointsInRangeByExtraFieldValue(const unsigned int& extraFieldNum, const double& lowerBound, const double& upperBound) { vector<unsigned int> keepers; //indices of points to keep //offset the clipping values float lb = lowerBound - fieldOffsets[extraFieldNum]; float ub = upperBound - fieldOffsets[extraFieldNum]; //lets find those points to keep unsigned int numPoints = xValues.size(); for(unsigned int i = 0; i < numPoints; i++) { float value = (*extraFields[extraFieldNum])[i]; if( value < lb || value > ub) keepers.push_back(i); } //clip all of the storage arrays vector<float> temp; for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(xValues[keepers[i]]); } xValues.clear(); xValues = temp; temp.clear(); for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(yValues[keepers[i]]); } yValues.clear(); yValues = temp; temp.clear(); for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back(zValues[keepers[i]]); } zValues.clear(); zValues = temp; temp.clear(); for(unsigned int field = 0; field < extraFields.size(); field++) { for(unsigned int i = 0; i < keepers.size(); i++) { temp.push_back((*extraFields[field])[keepers[i]]); } (*extraFields[field]).clear(); (*extraFields[field]) = temp; temp.clear(); } updateNumberOfPoints(); dirtyMinsAndMaxs = true; updateXYZMinsAndMaxs(); dirtyFieldMinsAndMaxs = true; updateFieldMinsAndMaxs(); return; } double BPFFile::getExtraFieldMean(const string& name) const { int efi = this->getExtraFieldNumberByName(name); return this->getExtraFieldMean(efi); } double BPFFile::getExtraFieldMean(const int fieldNum) const { //find mean of extra field fieldNum vector<float>* ef = extraFields[fieldNum]; vector<float>::const_iterator itr = ef->begin(), end = ef->end(); double sum = 0.0; while(itr != end) { sum += (double)(*itr); itr++; } double average = sum / ef->size(); return average + fieldOffsets[fieldNum]; } double BPFFile::getXMean() const { double sum = 0.0; for(vector<float>::const_iterator itr = xValues.begin(); itr != xValues.end(); itr++) { sum += (double)*itr; } return (sum / xValues.size()) + xOffset; } double BPFFile::getYMean() const { double sum = 0.0; for(vector<float>::const_iterator itr = yValues.begin(); itr != yValues.end(); itr++) { sum += (double)*itr; } return (sum / yValues.size()) + yOffset; } double BPFFile::getZMean() const { double sum = 0.0; for(vector<float>::const_iterator itr = zValues.begin(); itr != zValues.end(); itr++) { sum += (double)*itr; } return (sum / zValues.size()) + zOffset; } multimap<float, unsigned int>* BPFFile::partitionPointsByExtraFieldOffset(const string& fieldName) const { return partitionPointsByExtraFieldOffset(this->getExtraFieldNumberByName(fieldName)); } multimap<float, unsigned int>* BPFFile::partitionPointsByExtraFieldOffset(const unsigned int fieldIndex) const { multimap<float, unsigned int>* pMap = new multimap<float, unsigned int>; multimap<float, unsigned int>::iterator prev = pMap->begin(); for(unsigned int i = 0; i < this->numberOfPoints; i++) { prev = pMap->insert(prev, pair<float,unsigned int>((*extraFields[fieldIndex])[i], i)); } return pMap; } multimap<double, unsigned int>* BPFFile::partitionPointsByExtraField(const string& fieldName) const { return partitionPointsByExtraField(this->getExtraFieldNumberByName(fieldName)); } multimap<double, unsigned int>* BPFFile::partitionPointsByExtraField(const unsigned int fieldIndex) const { multimap<double, unsigned int>* pMap = new multimap<double, unsigned int>; double offset = fieldOffsets[fieldIndex]; multimap<double, unsigned int>::iterator prev = pMap->begin(); for(unsigned int i = 0; i < this->numberOfPoints; i++) { prev = pMap->insert(prev, pair<double,unsigned int>((*extraFields[fieldIndex])[i] + offset, i)); } return pMap; }
30.550711
164
0.656842
[ "object", "vector", "transform" ]
4236c0de3d2361f046aca9a276ff11fdb7758ec5
394
cpp
C++
51-60/53. Maximum Subarray.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
51-60/53. Maximum Subarray.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
51-60/53. Maximum Subarray.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
//简单dp class Solution { public: int maxSubArray(vector<int>& nums) { int ans = nums[0]; int dp = 0; for(int i = 0; i < nums.size(); i++) { if(dp + nums[i] < 0) dp = max(nums[i], 0); else dp += nums[i]; if(dp) ans = max(ans, dp); else ans = max(ans, nums[i]); } return ans; } };
23.176471
54
0.403553
[ "vector" ]
423b9cb8f520216a06418ed4fbccde07bafd67ff
11,156
cpp
C++
test/src/msa.cpp
nathanweeks/root_digger
906869952c01291beec4cb7b99077f741aaddd0f
[ "MIT" ]
13
2020-01-13T09:54:06.000Z
2022-03-20T15:21:09.000Z
test/src/msa.cpp
nathanweeks/root_digger
906869952c01291beec4cb7b99077f741aaddd0f
[ "MIT" ]
5
2020-02-24T02:45:57.000Z
2022-03-21T22:24:39.000Z
test/src/msa.cpp
nathanweeks/root_digger
906869952c01291beec4cb7b99077f741aaddd0f
[ "MIT" ]
7
2020-02-15T19:50:29.000Z
2021-08-19T11:10:34.000Z
extern "C" { #include <libpll/pll.h> } #include "data.hpp" #include <catch2/catch.hpp> #include <msa.hpp> TEST_CASE("msa_t parse msa", "[msa_t]") { for (auto &kv : data_files_dna) { auto &ds = kv.second; msa_t msa{ds.first}; REQUIRE(msa.states() == 4); REQUIRE(msa.map() == pll_map_nt); } } TEST_CASE("msa_t parse partition line", "[msa_t]") { SECTION("no errors") { std::string line{"DNA, PART_0 = 123-4123"}; auto pi = parse_partition_info(line); CHECK("DNA" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); } SECTION("no spaces") { std::string line{"DNA,PART_0=123-4123"}; auto pi = parse_partition_info(line); CHECK("DNA" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); } SECTION("multiple ranges") { std::string line{"DNA,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); } SECTION("Model strings") { SECTION("Frequency only") { SECTION("emperical") { std::string line{"DNA+F,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+F" == pi.model_name); CHECK("DNA" == pi.model.subst_str); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.freq_opts.type == param_type::emperical); } SECTION("estimate") { std::string line{"DNA+FO,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+FO" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.freq_opts.type == param_type::estimate); } SECTION("equal") { std::string line{"DNA+FE,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+FE" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.freq_opts.type == param_type::equal); } SECTION("user") { SECTION("cli") { std::string line{ "DNA+FU{0.25/0.25/0.25/0.25},PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+FU{0.25/0.25/0.25/0.25}" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.freq_opts.type == param_type::user); } } } SECTION("Invar Only"){ SECTION("estimate"){ std::string line{"DNA+I,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+I" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.invar_opts.type == param_type::estimate); } SECTION("emperical"){ std::string line{"DNA+IC,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+IC" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.invar_opts.type == param_type::emperical); } SECTION("user"){ std::string line{"DNA+IU{0.25},PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+IU{0.25}" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.invar_opts.type == param_type::user); CHECK(pi.model.invar_opts.user_prop == 0.25); } } SECTION("RateHet Only"){ SECTION("emperical"){ std::string line{"DNA+G,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+G" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::estimate); CHECK(pi.model.ratehet_opts.rate_cats == 4); } SECTION("emperical, with n"){ std::string line{"DNA+G2,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+G2" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::estimate); CHECK(pi.model.ratehet_opts.rate_cats == 2); } SECTION("user"){ std::string line{"DNA+G2{0.25},PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+G2{0.25}" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::user); CHECK(pi.model.ratehet_opts.rate_cats == 2); CHECK(pi.model.ratehet_opts.alpha == 0.25); } SECTION("median"){ std::string line{"DNA+GA,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+GA" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::estimate); CHECK(pi.model.ratehet_opts.rate_cats == 4); } SECTION("free, ml specified"){ std::string line{"DNA+R4,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+R4" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::estimate); CHECK(pi.model.ratehet_opts.rate_cats == 4); CHECK(pi.model.ratehet_opts.rate_category_type == rate_category::FREE); } SECTION("free, rates specified"){ std::string line{"DNA+R2{0.2/0.2}{0.1/0.1},PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+R2{0.2/0.2}{0.1/0.1}" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::estimate); CHECK(pi.model.ratehet_opts.rate_cats == 2); CHECK(pi.model.ratehet_opts.rate_category_type == rate_category::FREE); } } SECTION("All together"){ std::string line{"DNA+G2{0.25}+F+I,PART_0=123-4123, 5122-12411"}; auto pi = parse_partition_info(line); CHECK("DNA+G2{0.25}+F+I" == pi.model_name); CHECK("PART_0" == pi.partition_name); CHECK(123 == pi.parts[0].first); CHECK(4123 == pi.parts[0].second); CHECK(5122 == pi.parts[1].first); CHECK(12411 == pi.parts[1].second); CHECK(pi.model.ratehet_opts.type == param_type::user); CHECK(pi.model.ratehet_opts.rate_cats == 2); CHECK(pi.model.ratehet_opts.alpha == 0.25); CHECK(pi.model.invar_opts.type == param_type::estimate); CHECK(pi.model.freq_opts.type == param_type::emperical); } } SECTION("error: missing comma") { std::string line{"DNA PART_0 = 123-4123"}; CHECK_THROWS(parse_partition_info(line)); } SECTION("error: missing =") { std::string line{"DNA, PART_0 123-4123"}; CHECK_THROWS(parse_partition_info(line)); } SECTION("error: missing -") { std::string line{"DNA, PART_0 = 1234123"}; CHECK_THROWS(parse_partition_info(line)); } SECTION("error: missing -") { std::string line{"DNA, PART_0 = 123=4123"}; CHECK_THROWS(parse_partition_info(line)); } SECTION("error: missing model name") { std::string line{", PART_0 = 123-4123"}; CHECK_THROWS(parse_partition_info(line)); } } TEST_CASE("msa_t partition datafile", "[msa_t]") { auto ds = data_files_dna["101.phy"]; SECTION("single partition, one range") { msa_t msa{ds.first}; msa_partitions_t parts{parse_partition_info("DNA, PART_0 = 1-100")}; auto parted_msa = msa.partition(parts); CHECK(parted_msa.size() == parts.size()); CHECK(parted_msa[0].length() == 100); } SECTION("single partition, two ranges") { msa_t msa{ds.first}; msa_partitions_t parts{ parse_partition_info("DNA, PART_0 = 1-100, 200-300")}; auto parted_msa = msa.partition(parts); CHECK(parted_msa.size() == parts.size()); CHECK(parted_msa[0].length() == 201); } SECTION("multiple partitions, one range") { msa_t msa{ds.first}; msa_partitions_t parts{parse_partition_info("DNA, PART_0 = 1-100"), parse_partition_info("DNA, PART_1 = 200-300")}; auto parted_msa = msa.partition(parts); CHECK(parted_msa.size() == parts.size()); CHECK(parted_msa[0].length() == 100); CHECK(parted_msa[1].length() == 101); } SECTION("multiple partitions, multiple ranges") { msa_t msa{ds.first}; msa_partitions_t parts{ parse_partition_info("DNA, PART_0 = 1-100, 500-520"), parse_partition_info("DNA, PART_1 = 200-300, 400-500")}; auto parted_msa = msa.partition(parts); CHECK(parted_msa.size() == parts.size()); CHECK(parted_msa[0].length() == 121); CHECK(parted_msa[1].length() == 202); } }
39.420495
81
0.593582
[ "model" ]
424253eb2f37d9da88db34d4170f65982bc7f638
878
cpp
C++
examples/serialize-xml.cpp
genisysram/libzeep
cb3e7f0e03c5337e106e23de478ccb53bad62d97
[ "BSL-1.0" ]
7
2017-01-04T19:27:03.000Z
2020-07-06T11:19:33.000Z
examples/serialize-xml.cpp
genisysram/libzeep
cb3e7f0e03c5337e106e23de478ccb53bad62d97
[ "BSL-1.0" ]
11
2016-01-14T14:08:46.000Z
2022-02-26T08:08:15.000Z
examples/serialize-xml.cpp
genisysram/libzeep
cb3e7f0e03c5337e106e23de478ccb53bad62d97
[ "BSL-1.0" ]
3
2018-10-11T22:39:28.000Z
2020-11-12T02:44:41.000Z
//[ synopsis_xml_serialize #include <fstream> #include <zeep/xml/document.hpp> struct Person { std::string firstname; std::string lastname; /*<< A struct we want to serialize needs a `serialize` method >>*/ template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & zeep::make_nvp("firstname", firstname) & zeep::make_nvp("lastname", lastname); } }; int main() { /*<< Read in a text document containing XML and parse it into a document object >>*/ std::ifstream file("test.xml"); zeep::xml::document doc(file); std::vector<Person> persons; /*<< Deserialize all persons into an array >>*/ doc.deserialize("persons", persons); doc.clear(); /*<< Serialize all persons back into an XML document again >>*/ doc.serialize("persons", persons); return 0; } //]
24.388889
88
0.635535
[ "object", "vector" ]
424e77052478eec20ba4bde5ad7dd056c4770068
1,758
hh
C++
tools/click-fastclassifier/click-fastclassifier.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
tools/click-fastclassifier/click-fastclassifier.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
tools/click-fastclassifier/click-fastclassifier.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
#ifndef CLICK_FASTCLASSIFIER_HH #define CLICK_FASTCLASSIFIER_HH #include <click/vector.hh> #include <click/string.hh> class ElementClassT; struct Classifier_Insn { int offset; bool short_output; int j[2]; union { unsigned char c[4]; uint32_t u; } mask; union { unsigned char c[4]; uint32_t u; } value; int required_length() const { if (!mask.u) return 0; else if (mask.c[3]) return offset + 4; else if (mask.c[2]) return offset + 3; else if (mask.c[1]) return offset + 2; else return offset + 1; } static void write_branch(int branch, const String &label_prefix, StringAccum &sa); void write_state(int state, bool check_length, bool take_short, const String &data, const String &label_prefix, StringAccum &sa) const; }; struct Classifier_Program { int safe_length; int unsafe_length_output_everything; int output_everything; int align_offset; int noutputs; Vector<Classifier_Insn> program; int type; ElementClassT *eclass; Vector<String> handler_names; Vector<String> handler_values; const String &handler_value(const String &name) const; }; bool operator==(const Classifier_Insn &, const Classifier_Insn &); bool operator!=(const Classifier_Insn &, const Classifier_Insn &); bool operator==(const Classifier_Program &, const Classifier_Program &); bool operator!=(const Classifier_Program &, const Classifier_Program &); int add_classifier_type(const String &name, void (*match_body)(const Classifier_Program &, StringAccum &sa), void (*more)(const Classifier_Program &, const String &type_name, StringAccum &header_sa, StringAccum &source_sa)); void add_interesting_handler(const String &name); #endif
26.636364
116
0.710466
[ "vector" ]
42509b912e98b0e12f67a3248d8f68d51e1fc4fe
9,015
hpp
C++
src/fluxes.hpp
pecos/tps
13b15a673848d5b448443bb8333ab1e66709a73a
[ "BSD-3-Clause" ]
3
2021-12-21T15:54:06.000Z
2022-02-10T21:13:40.000Z
src/fluxes.hpp
pecos/tps
13b15a673848d5b448443bb8333ab1e66709a73a
[ "BSD-3-Clause" ]
24
2021-10-20T01:50:43.000Z
2022-03-15T15:58:25.000Z
src/fluxes.hpp
pecos/tps
13b15a673848d5b448443bb8333ab1e66709a73a
[ "BSD-3-Clause" ]
null
null
null
// -----------------------------------------------------------------------------------bl- // BSD 3-Clause License // // Copyright (c) 2020-2022, The PECOS Development Team, University of Texas at Austin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -----------------------------------------------------------------------------------el- #ifndef FLUXES_HPP_ #define FLUXES_HPP_ /* * Class that deals with flux operations */ #include <tps_config.h> #include <mfem.hpp> #include <mfem/general/forall.hpp> #include "dataStructures.hpp" #include "equation_of_state.hpp" #include "transport_properties.hpp" using namespace mfem; // TODO(kevin): In order to avoid repeated primitive variable evaluation, // Fluxes and RiemannSolver should take Vector Up (on the evaulation point) as input argument, // and FaceIntegrator should have a pointer to ParGridFunction *Up. // Also should be able to have Up more than number of equations, // while gradUp is evaluated only for the first num_equation variables. // Need to discuss further. class Fluxes { private: GasMixture *mixture; TransportProperties *transport; Equations &eqSystem; const int &dim; int nvel; const bool axisymmetric_; const int &num_equation; double Rg; Vector gradT; Vector vel; Vector vtmp; DenseMatrix stress; public: Fluxes(GasMixture *_mixture, Equations &_eqSystem, TransportProperties *_transport, const int &_num_equation, const int &_dim, bool axisym); Equations GetEquationSystem() { return eqSystem; } void ComputeTotalFlux(const Vector &state, const DenseMatrix &gradUp, DenseMatrix &flux); void ComputeConvectiveFluxes(const Vector &state, DenseMatrix &flux); void ComputeViscousFluxes(const Vector &state, const DenseMatrix &gradUp, double radius, DenseMatrix &flux); // Compute viscous flux with prescribed boundary flux. void ComputeBdrViscousFluxes(const Vector &state, const DenseMatrix &gradUp, double radius, const BoundaryViscousFluxData &bcFlux, Vector &normalFlux); // Compute the split fersion of the flux for SBP operations // Output matrices a_mat, c_mat need not have the right size void ComputeSplitFlux(const Vector &state, DenseMatrix &a_mat, DenseMatrix &c_mat); // GPU functions static void convectiveFluxes_gpu(const Vector &x, DenseTensor &flux, const Equations &eqSystem, GasMixture *mixture, const int &dof, const int &dim, const int &num_equation); static void viscousFluxes_gpu(const Vector &x, ParGridFunction *gradUp, DenseTensor &flux, const Equations &eqSystem, GasMixture *mixture, const ParGridFunction *spaceVaryViscMult, const linearlyVaryingVisc &linViscData, const int &dof, const int &dim, const int &num_equation); #ifdef _GPU_ static MFEM_HOST_DEVICE void viscousFlux_gpu(double *vFlux, const double *Un, const double *gradUpn, const Equations &eqSystem, const double &gamma, const double &Rg, const double &viscMult, const double &bulkViscMult, const double &Pr, const double &Sc, const int &thrd, const int &maxThreads, const int &dim, const int &num_equation) { MFEM_SHARED double KE[3], vel[3], divV; MFEM_SHARED double stress[3][3]; MFEM_SHARED double gradT[3]; if (thrd < 3) KE[thrd] = 0.; if (thrd < dim) KE[thrd] = 0.5 * Un[1 + thrd] * Un[1 + thrd] / Un[0]; // if(thrd<num_equation) for(int d=0;d<dim;d++) vFlux[thrd+d*num_equation] = 0.; for (int eq = thrd; eq < num_equation; eq += maxThreads) { for (int d = 0; d < dim; d++) vFlux[eq + d * num_equation] = 0.; } MFEM_SYNC_THREAD; const double p = DryAir::pressure(&Un[0], &KE[0], gamma, dim, num_equation); const double temp = p / Un[0] / Rg; double visc = DryAir::GetViscosity_gpu(temp); visc *= viscMult; const double k = DryAir::GetThermalConductivity_gpu(visc, gamma, Rg, Pr); for (int i = thrd; i < dim; i += maxThreads) { for (int j = 0; j < dim; j++) { stress[i][j] = gradUpn[1 + j + i * num_equation] + gradUpn[1 + i + j * num_equation]; } // temperature gradient // gradT[i] = temp * (gradUpn[1 + dim + i * num_equation] / p - gradUpn[0 + i * num_equation] / Un[0]); gradT[i] = gradUpn[1 + dim + i * num_equation]; vel[i] = Un[1 + i] / Un[0]; } if (thrd == maxThreads - 1) { divV = 0.; for (int i = 0; i < dim; i++) divV += gradUpn[1 + i + i * num_equation]; } MFEM_SYNC_THREAD; for (int i = thrd; i < dim; i += maxThreads) stress[i][i] += (bulkViscMult - 2. / 3.) * divV; MFEM_SYNC_THREAD; for (int i = thrd; i < dim; i += maxThreads) { for (int j = 0; j < dim; j++) { vFlux[1 + i + j * num_equation] = visc * stress[i][j]; // energy equation vFlux[1 + dim + i * num_equation] += visc * vel[j] * stress[i][j]; } } MFEM_SYNC_THREAD; for (int i = thrd; i < dim; i += maxThreads) { vFlux[1 + dim + i * num_equation] += k * gradT[i]; } MFEM_SYNC_THREAD; if (eqSystem == NS_PASSIVE) { for (int d = thrd; d < dim; d += maxThreads) vFlux[num_equation - 1 + d * num_equation] += visc / Sc * gradUpn[num_equation - 1 + d * num_equation]; } } static MFEM_HOST_DEVICE void viscousFlux_serial_gpu(double *vFlux, const double *Un, const double *gradUpn, const double &gamma, const double &Rg, const double &viscMult, const double &bulkViscMult, const double &Pr, const int &dim, const int &num_equation) { double KE[3], vel[3], divV; double stress[3][3]; double gradT[3]; for (int d = 0; d < dim; d++) KE[d] = 0.; for (int d = 0; d < dim; d++) KE[d] = 0.5 * Un[1 + d] * Un[1 + d] / Un[0]; for (int eq = 0; eq < num_equation; eq++) { for (int d = 0; d < dim; d++) vFlux[eq + d * num_equation] = 0.; } const double p = DryAir::pressure(&Un[0], &KE[0], gamma, dim, num_equation); const double temp = p / Un[0] / Rg; double visc = DryAir::GetViscosity_gpu(temp); visc *= viscMult; const double k = DryAir::GetThermalConductivity_gpu(visc, gamma, Rg, Pr); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { stress[i][j] = gradUpn[1 + j + i * num_equation] + gradUpn[1 + i + j * num_equation]; } // temperature gradient // gradT[i] = temp * (gradUpn[1 + dim + i * num_equation] / p - gradUpn[0 + i * num_equation] / Un[0]); gradT[i] = gradUpn[1 + dim + i * num_equation]; vel[i] = Un[1 + i] / Un[0]; } divV = 0.; for (int i = 0; i < dim; i++) divV += gradUpn[1 + i + i * num_equation]; for (int i = 0; i < dim; i++) stress[i][i] += (bulkViscMult - 2. / 3.) * divV; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { vFlux[1 + i + j * num_equation] = visc * stress[i][j]; // energy equation vFlux[num_equation - 1 + i * num_equation] += visc * vel[j] * stress[i][j]; } } for (int i = 0; i < dim; i++) { vFlux[num_equation - 1 + i * num_equation] += k * gradT[i]; } } #endif }; #endif // FLUXES_HPP_
41.353211
120
0.609872
[ "vector" ]
42531adebb97fbc091519f18c70a8ee55e8a2c52
11,504
cc
C++
rowsize.cc
avineshwar/drammer
2e262d6e10f943209c5476f876075fe1082e7977
[ "Apache-2.0" ]
null
null
null
rowsize.cc
avineshwar/drammer
2e262d6e10f943209c5476f876075fe1082e7977
[ "Apache-2.0" ]
null
null
null
rowsize.cc
avineshwar/drammer
2e262d6e10f943209c5476f876075fe1082e7977
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016, Victor van der Veen * * 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. */ #include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <memory> #include <numeric> #include <string> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #include "helper.h" #include "ion.h" #include "rowsize.h" #define ROWSIZE_READCOUNT 2500000 // 2.5 million reads #define ROWSIZE_PAGES 64 #define DEFAULT_ROWSIZE K(64) std::vector<struct model> models = { // model ro.product.name board platform ion row // generic name // Snapdragon 820 // {"SM-G935T", "hero2qltetmo", "msm8996", "msm8996", 21, 0, // "Samsung Galaxy S7 Edge"}, // {"SAMSUNG-SM-G930A", "heroqlteuc","MSM8996", "msm8996", 21, 0, // "Samsung Galaxy S7"}, // Snapdragon 810 // {"Nexus 6P", "angler", "angler", "msm8994", 21, 0, // "Huawei Nexus 6P"}, {"E6853", "E6853", "msm8994", "msm8994", 21, K(64), "Sony Xperia Z5"}, // Snapdragon 808 {"Nexus 5X", "bullhead", "bullhead", "msm8992", 21, K(64), "LG Nexus 5X"}, {"LG-H960", "pplus_global_com", "msm8992", "msm8992", 21, K(64), "LG V10"}, {"LG-H815", "p1_global_com", "msm8992", "msm8992", 21, K(64), "LG G4"}, {"C1905", "cm_nicki", "qcom", "msm8960", 22, K(32), "Sony Xperia M"}, // Snapdragon 805 {"SM-G901F", "kccat6xx", "APQ8084", "apq8084", 21, K(128), "Samsung Galaxy S5 Plus"}, // {"SM-N910V", "trltevzw", "APQ8084", "apq8084", 21, 0, // "Samsung Galaxy Note 4"}, // Snapdragon 800 {"Nexus 5", "hammerhead", "hammerhead", "msm8974", 21, K(64), "LG Nexus 5"}, {"A0001", "bacon", "MSM8974", "msm8974", 21, K(128), "OnePlus One"}, {"SM-G870F", "klteactivexx", "MSM8974", "msm8974", 21, K(64), "Samsung Galaxy S5 Active"}, // {"SM-G900T", "kltetmo", "MSM8974", "msm8974", 21, 0, // "Samsung Galaxy S5"}, // Snapdragon 410: // {"SM-A500FU", "a5ultexx", "MSM8916", "msm8916", 21, 0, // "Samsung Galaxy A5"}, // {"MotoG3", "osprey_retus", "msm8916", "msm8916", 21, 0, // "Motorola Moto G 3rd Gen"}, {"GT-I9195I", "serranoveltexx", "MSM8916", "msm8916", 21, K(32), "Samsung Galaxy S4 Mini"}, {"KIW-L21", "KIW-L21", "KIW-L21", "msm8916", 21, K(32), "Huawei Honor 5X"}, {"MotoE2(4G-LTE)", "surnia_reteu", "msm8916", "msm8916", 21, K(32), "Motorola Moto E 2nd Gen"}, {"MotoG3", "osprey_reteu", "msm8916", "msm8916", 21, K(32), "Motorola Moto G 3rd Gen"}, {"HUAWEI RIO-L01", "RIO-L01", "RIO-L01", "msm8916", 21, K(64), "Huawei GX8/G8"}, {"HTC One M8s", "m8qlul_htc_europe", "msm8939", "msm8916", 21, K(64), "HTC One M8s"}, // Snapdragon 400: {"XT1064", "titan_retuaws", "MSM8226", "msm8226", 21, K(32), "Motorola Moto G 2nd Gen"}, {"XT1068", "titan_retaildsds", "MSM8226", "msm8226", 21, K(32), "Motorola Moto G 2nd Gen"}, // {"LG-V410", "e7lte_att_us", "MSM8226", "msm8226", 21, 0, "LG // G Pad 7.0"}, {"SM-J320FN", "j3xnltexx", "SC9830I", "sc8830", 2, K(32), "Samsung Galaxy J3 2016"}, {"SM-A310F", "a3xeltexx", "universal7580", "exynos5", 4, K(64), "Samsung Galaxy A3 2016"}, // not sure about the rowsize... {"SM-A700F", "a7altexx", "universal5430", "exynos5", 4, K(128), "Samsung Galaxy A7"}, {"SM-G920F", "zerofltexx", "universal7420", "exynos5", 4, K(128), "Samsung Galaxy S6"}, {"SM-G935F", "hero2ltexx", "universal8890", "exynos5", 4, K(256), "Samsung Galaxy S7 Edge"}, {"SM-G930F", "heroltexx", "universal8890", "exynos5", 4, K(256), "Samsung Galaxy S7"}, // {"SM-T710", "gts28wifixx", "universal5433", "exynos5", 4, 0, // "Samsung Galaxy Tab S2 8.0"}, {"SM-G935F", "hero2ltexx", "universal8890", "exynos5", 4, K(256), "Samsung Galaxy S7 Edge"}, {"SM-G930F", "heroltexx", "universal8890", "exynos5", 4, K(256), "Samsung Galaxy S7"}, // {"SM-T710", "gts28wifixx", "universal5433", "exynos5", 4, 0, // "Samsung Galaxy Tab S2 8.0"}, // {"SM-T810", "gts210wifixx", "universal5433", "exynos5", 4, 0, // "Samsung Galaxy Tab S2 9.7"}, {"SM-N910C", "treltexx", "universal5433", "exynos5", 4, K(64), "Samsung Galaxy Note 4"}, // Snapdragon S4 // {"AOSP on Mako", "full_mako", "MAKO", "msm8960", 21, 0, // ""}, {"ALE-L21", "ALE-L21", "BalongV8R1SFT", "hi6210sft", 1, K(32), "Huawei P8 Lite"}, {"EVA-L09", "EVA-L09", "EVA-L09", "hi3650", 1, K(64), "Huawei P9"}, {"HUAWEI VNS-L31", "VNS-L31", "VNS-L31", "hi6250", 1, K(32), "Huawei P9 Lite"}, {"NEO6_LTE", "NEO6_LTE", "", "mt6735", 1, K(32), "Odys Neo 6"}, {"HTC Desire 830 dual sim", "a51cml_dtul_00401", "", "mt6753", 1, K(64), "HTC Desire 830"}, {"E5603", "E5603", "", "mt6795", 1, K(64), "Sony Xperia M5"} // MT6572 // {"Goophone i5C", "mbk72_wet_jb3", "mbk72_wet_jb3", "", 21, 0, // "Goophone i5C"}, // MT8735 }; int rowsize; uint64_t compute_mad(std::vector<uint64_t> &v) { uint64_t median = compute_median(v); std::vector<uint64_t> absolute_deviations; for (auto it : v) { if (it < median) absolute_deviations.push_back(median - it); else absolute_deviations.push_back(it - median); } sort(absolute_deviations.begin(), absolute_deviations.end()); return compute_median(absolute_deviations); } uint64_t compute_iqr(std::vector<uint64_t> &v, uint64_t *q1, uint64_t *q2, uint64_t *q3) { std::vector<uint64_t> tmp = v; sort(tmp.begin(), tmp.end()); auto const i1 = tmp.size() / 4; auto const i2 = tmp.size() / 2; auto const i3 = i1 + i2; std::nth_element(tmp.begin(), tmp.begin() + i1, tmp.end()); std::nth_element(tmp.begin() + i1 + 1, tmp.begin() + i2, tmp.end()); std::nth_element(tmp.begin() + i2 + 1, tmp.begin() + i3, tmp.end()); *q1 = tmp[i1]; *q2 = tmp[i2]; *q3 = tmp[i3]; return (tmp[i3] - tmp[i1]); } std::string getprop(std::string property) { std::string cmd = "/system/bin/getprop "; cmd += property; char buffer[128]; std::string value = ""; std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose); if (!pipe) { perror("popen failed"); return value; } while (!feof(pipe.get())) { if (fgets(buffer, 128, pipe.get()) != NULL) value += buffer; } value.erase(std::remove(value.begin(), value.end(), '\n'), value.end()); return value; } #define KNOWN_MODEL 2 #define FAMILIAR_MODEL 1 #define UNKNOWN_MODEL 0 struct model *get_model(int *familiarity) { std::string model = getprop("ro.product.model"); print("[RS] ro.product.model: %s\n", model.c_str()); std::string name = getprop("ro.product.name"); print("[RS] ro.product.name: %s\n", name.c_str()); std::string board = getprop("ro.product.board"); print("[RS] ro.product.board: %s\n", board.c_str()); std::string platform = getprop("ro.board.platform"); print("[RS] ro.board.platform: %s\n", platform.c_str()); for (std::vector<struct model>::iterator it = models.begin(); it != models.end(); ++it) { struct model *m = &(*it); if (m->model == model || m->name == name) { print("[RS] known model: %s\n", m->generic_name.c_str()); *familiarity = KNOWN_MODEL; return m; } } for (std::vector<struct model>::iterator it = models.begin(); it != models.end(); ++it) { struct model *m = &(*it); if (m->board == board || m->platform == platform) { printf("[RS] familiar model: %s\n", m->generic_name.c_str()); *familiarity = FAMILIAR_MODEL; return m; } } *familiarity = UNKNOWN_MODEL; return NULL; } /* auto detect row size */ int RS_autodetect(void) { print("[RS] Trying getprop\n"); int familiarity; struct model *m = get_model(&familiarity); if (familiarity == KNOWN_MODEL) { rowsize = m->rowsize; return rowsize; } print("[RS] Allocating 256 ion chunk\n"); struct ion_data data; data.handle = ION_alloc(K(256)); if (data.handle == 0) { perror("Could not allocate 256K chunk for row size detection"); exit(EXIT_FAILURE); } data.len = K(256); ION_mmap(&data); print("[RS] Reading from page 0 and page x (x = 0..%d)\n", ROWSIZE_PAGES); std::vector<uint64_t> deltas; int page1 = 0; volatile uintptr_t *virt1 = (volatile uintptr_t *)((uint64_t)data.mapping + (page1 * PAGESIZE)); for (int page2 = 0; page2 < ROWSIZE_PAGES; page2++) { volatile uintptr_t *virt2 = (volatile uintptr_t *)((uint64_t)data.mapping + (page2 * PAGESIZE)); uint64_t t1 = get_ns(); for (int i = 0; i < ROWSIZE_READCOUNT; i++) { *virt1; *virt2; } uint64_t t2 = get_ns(); deltas.push_back((t2 - t1) / ROWSIZE_READCOUNT); print("%llu ", deltas.back()); } print("\n"); if (munmap(data.mapping, data.len)) { perror("Could not munmap"); exit(EXIT_FAILURE); } if (close(data.fd)) { perror("Could not close"); exit(EXIT_FAILURE); } if (ION_free(data.handle)) { perror("Could not free"); exit(EXIT_FAILURE); } uint64_t q1, q2, q3; uint64_t iqr = compute_iqr(deltas, &q1, &q2, &q3); uint64_t median = compute_median(deltas); uint64_t mad = compute_mad(deltas); print("[RS] Median: %llu\n", median); print("[RS] MAD: %llu\n", mad); print("[RS] IQR: %llu\n", iqr); // MAD, IQR and standard deviation all need some form of correction... :( iqr += 5; print("[RS] Corrected IQR: %llu\n", iqr); /* try simple algorithm first */ int count = 0; for (auto it : deltas) { if (it < 2 * median) { count++; } else { break; } } printf("count: %d\n", count); rowsize = count * 4096; /* do more advanced stuff if the rowsize is absurd */ if (rowsize >= K(128)) { print("[RS] Sequences: "); std::vector<uint64_t> seq_normal; std::vector<uint64_t> seq_outlier; int sn = 0; int so = 0; for (auto it : deltas) { if (it < q1 - 1.5 * iqr || it > q3 + 1.5 * iqr) { if (so != 0) { seq_normal.push_back(so); print("%d ", so); so = 0; } sn++; } else { if (sn != 0) { seq_outlier.push_back(sn); print("%d ", sn); sn = 0; } so++; } } printf("\n"); rowsize = (compute_median(seq_normal) + compute_median(seq_outlier)) * 4096; } print("[RS] Detected row size: %d\n", rowsize); if (!VALID_ROWSIZES.count(rowsize)) { if (familiarity == FAMILIAR_MODEL) { print("[RS] WARNING! Weird row size detected, assuming familiar model's " "rowsize %d\n", m->rowsize); rowsize = m->rowsize; } else { print("[RS] WARNING! Weird row size detected, assuming %d\n", DEFAULT_ROWSIZE); rowsize = DEFAULT_ROWSIZE; } } return rowsize; }
31.431694
80
0.579016
[ "vector", "model" ]
4262b4b95dc546b4a7b5663c01e0c47436e06654
9,394
hpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/common/add_endpoint.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/common/add_endpoint.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/common/add_endpoint.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @brief Definition of AddEndpoint class. * * @copyright Copyright (c) 2017-2019 Intel Corporation * * 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. * * @file add_endpoint.hpp */ #pragma once #include "agent-framework/module/constants/common.hpp" #include "agent-framework/module/constants/command.hpp" #include "agent-framework/module/model/attributes/array.hpp" #include "agent-framework/module/model/attributes/oem.hpp" #include "agent-framework/module/model/attributes/ip_transport_detail.hpp" #include "agent-framework/module/model/attributes/identifier.hpp" #include "agent-framework/module/model/attributes/connected_entity.hpp" #include "agent-framework/module/utils/optional_field.hpp" #include "agent-framework/validators/procedure_validator.hpp" #include "agent-framework/module/constants/regular_expressions.hpp" #include <string> namespace agent_framework { namespace model { namespace requests { /*! AddEndpoint request */ class AddEndpoint { public: using IpTransportDetails = agent_framework::model::attribute::Array<agent_framework::model::attribute::IpTransportDetail>; using Identifiers = agent_framework::model::attribute::Array<agent_framework::model::attribute::Identifier>; using ConnectedEntities = agent_framework::model::attribute::Array<agent_framework::model::attribute::ConnectedEntity>; using Ports = agent_framework::model::attribute::Array<Uuid>; explicit AddEndpoint(const Uuid& fabric, const IpTransportDetails& transports, const Identifiers& identifiers, const ConnectedEntities& connected_entities, const OptionalField<std::string>& username, const OptionalField<std::string>& password, const Ports& ports, const attribute::Oem& oem); static std::string get_command() { return literals::Command::ADD_ENDPOINT; } /*! * @brief Get IP transport details. * * @return IP transport details */ const IpTransportDetails& get_ip_transport_details() const { return m_ip_transport_details; } /*! * @brief Get identifiers. * * @return identifiers */ const Identifiers& get_identifiers() const { return m_identifiers; } /*! * @brief Get fabric Uuid * * @return fabric Uuid */ const Uuid& get_fabric() const { return m_fabric; } /*! * @brief Get ports Uuids * * @return Array of ports Uuids */ const Ports& get_ports() const { return m_ports; } /*! * @brief Get connected entities. * * @return connected entities. */ const ConnectedEntities& get_connected_entities() const { return m_connected_entities; } /*! * @brief Get username. * * @return username */ const OptionalField<std::string>& get_username() const { return m_username; } /*! * @brief Get password. * * @return password */ const OptionalField<std::string>& get_password() const { return m_password; } /*! * @brief Get oem from request * * @return oem */ const attribute::Oem& get_oem() const { return m_oem; } /*! * @brief Transform request to Json * @return created Json value */ json::Json to_json() const; /*! * @brief create AddEndpoint from Json * @param[in] json the input argument * @return new AddEndpoint */ static AddEndpoint from_json(const json::Json& json); /*! * @brief Returns procedure scheme * @return ProcedureValidator scheme */ static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::Endpoint::FABRIC, VALID_UUID, literals::Endpoint::IP_TRANSPORT_DETAILS, VALID_ARRAY_OF(VALID_ATTRIBUTE(IpTransportDetailSchema)), literals::Endpoint::IDENTIFIERS, VALID_ARRAY_OF(VALID_ATTRIBUTE(IdentifierSchema)), literals::Endpoint::CONNECTED_ENTITIES, VALID_ARRAY_OF(VALID_ATTRIBUTE(ConnectedEntitySchema)), literals::Endpoint::USERNAME, VALID_NULLABLE(VALID_JSON_STRING), literals::Endpoint::PASSWORD, VALID_NULLABLE(VALID_JSON_STRING), literals::Endpoint::PORTS, VALID_OPTIONAL(VALID_NULLABLE(VALID_ARRAY_OF(VALID_UUID))), literals::Endpoint::OEM, VALID_OPTIONAL(jsonrpc::JSON_OBJECT), nullptr }; return procedure; } private: class IpTransportDetailSchema { public: static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::IpTransportDetail::PROTOCOL, VALID_NULLABLE(VALID_ENUM(enums::TransportProtocol)), literals::IpTransportDetail::IPV4_ADDRESS, VALID_NULLABLE(VALID_ATTRIBUTE(IPv4AddressSchema)), literals::IpTransportDetail::IPV6_ADDRESS, VALID_NULLABLE(VALID_ATTRIBUTE(IPv6AddressSchema)), literals::IpTransportDetail::PORT, VALID_NULLABLE(VALID_NUMERIC_TYPED(UINT32)), literals::IpTransportDetail::INTERFACE, VALID_NULLABLE(VALID_UUID), nullptr }; return procedure; } }; class IPv4AddressSchema { public: static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::Ipv4Address::ADDRESS, VALID_REGEX(literals::regex::IPAddresses::ADDRESS), literals::Ipv4Address::SUBNET_MASK, VALID_NULLABLE(VALID_REGEX(literals::regex::IPAddresses::ADDRESS)), literals::Ipv4Address::ADDRESS_ORIGIN, VALID_NULLABLE(VALID_ENUM(enums::Ipv4AddressOrigin)), literals::Ipv4Address::GATEWAY, VALID_NULLABLE(VALID_REGEX(literals::regex::IPAddresses::ADDRESS)), nullptr }; return procedure; } }; class IPv6AddressSchema { public: static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::Ipv6Address::ADDRESS, VALID_NULLABLE(VALID_REGEX(literals::regex::IPv6Addresses::ADDRESS)), literals::Ipv6Address::PREFIX_LENGTH, VALID_NULLABLE(VALID_NUMERIC_TYPED(UINT32)), literals::Ipv6Address::ADDRESS_ORIGIN, VALID_NULLABLE(VALID_ENUM(enums::Ipv6AddressOrigin)), literals::Ipv6Address::ADDRESS_STATE, VALID_NULLABLE(VALID_ENUM(enums::Ipv6AddressState)), nullptr }; return procedure; } }; class IdentifierSchema { public: static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::Identifier::DURABLE_NAME, VALID_REGEX(literals::regex::Common::EMPTY_OR_NO_WHITESPACE_STRING), literals::Identifier::DURABLE_NAME_FORMAT, VALID_ENUM(enums::IdentifierType), nullptr }; return procedure; } }; class ConnectedEntitySchema { public: static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::ConnectedEntity::ROLE, VALID_ENUM(enums::EntityRole), literals::ConnectedEntity::ENTITY, VALID_NULLABLE(VALID_UUID), literals::ConnectedEntity::IDENTIFIERS, VALID_ARRAY_OF(VALID_ATTRIBUTE(IdentifierSchema)), literals::ConnectedEntity::LUN, VALID_NULLABLE(VALID_NUMERIC_TYPED(INT64)), nullptr }; return procedure; } }; Uuid m_fabric{}; Ports m_ports{}; IpTransportDetails m_ip_transport_details{}; Identifiers m_identifiers{}; ConnectedEntities m_connected_entities{}; OptionalField<std::string> m_username{}; OptionalField<std::string> m_password{}; attribute::Oem m_oem{}; }; } } }
33.194346
126
0.64456
[ "model", "transform" ]
42667dd470231233f528bbbdf67e279e3ddfd275
6,962
cpp
C++
src/main.cpp
szledan/arg-.parse
94dbd2f51ee6fc33f2649792d58dc29794fb7008
[ "BSD-2-Clause" ]
null
null
null
src/main.cpp
szledan/arg-.parse
94dbd2f51ee6fc33f2649792d58dc29794fb7008
[ "BSD-2-Clause" ]
null
null
null
src/main.cpp
szledan/arg-.parse
94dbd2f51ee6fc33f2649792d58dc29794fb7008
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2018, Szilard Ledan <szledan@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ int option_main(int argc, char* argv[]); #include "arg-parser.h" int main(int argc, char* argv[]) { // 1. Simple usage in 'main' /* Parse help. */ bool a_help = PARSE_HELP("-h, --help, --usage", "show this help.", "Arg-parser Demo *** Simple version *** (C) 2018. Szilard Ledan\nUsage: %p [options] name number [number...]\n\nOptions:", argc, argv); /* Parse flags. */ uint a_size = PARSE_FLAG("--size SIZE[=%d]", 300, "set size of window."); float a_lineWidth = PARSE_FLAG("-w, --line-width LW", 3.14f, "set width of line. Default is '%d'."); std::string a_path = PARSE_FLAG("-p, --path PATH", std::string("./build"), "set working dir. Default is '%d'."); const char a_dot = CHECK_FLAG("-d", argc, argv) ? PARSE_FLAG("-d DOT", '.', "set separate char. Default is '%d'.") : '\0'; bool a_enable = PARSE_FLAG("-e, --enable", false, "enable something."); bool a_none = PARSE_FLAG("-none", true, "disable something."); ADD_MSG("\nFrequencies:"); int a_frequency = PARSE_FLAG("-f, --frequency FREQ", 60, "set rendering frequency.\n Default is '%d', but '%d' is not the best."); int a_Frequency = PARSE_FLAG("+f, ++frequency FREQ", 25, "set refreshing frequency. Default is '%d'."); ADD_MSG("\nExamples:\n %p -f 90 nothing 1 1 2 3 5 8\n %p -s 2000 -e something 123 124 125"); /* Parse arguments. */ std::string a_from = PARSE_ARG(std::string("ABC")); std::vector<int> a_to(1, PARSE_ARG(3)); while (!a_help && UNPARSED_COUNT()) { a_to.push_back(PARSE_ARG(0)); } /* Check help. */ if (!a_help) { std::cout << "a_help: " << a_help << ";" << std::endl; std::cout << "a_frequency: " << a_frequency << ";" << std::endl; std::cout << "a_Frequency: " << a_Frequency << ";" << std::endl; std::cout << "a_size: " << a_size << ";" << std::endl; std::cout << "a_lineWidth: " << a_lineWidth << ";" << std::endl; std::cout << "a_path: " << a_path << ";" << std::endl; std::cout << "a_dot: " << a_dot << ";" << std::endl; std::cout << "a_enable: " << a_enable << ";" << std::endl; std::cout << "a_none: " << a_none << ";" << std::endl; std::cout << "a_from: " << a_from << ";" << std::endl; std::cout << "a_to: "; for (size_t i = 0; i < a_to.size(); ++i) std::cout << a_to[i] << " "; std::cout << ";" << std::endl; } return option_main(argc, argv); // 2. Call the Singleton solution. } /* 2. Singleton class variant */ #ifdef AP_STDOUT #undef AP_STDOUT #endif #define AP_STDOUT Options::getOptions().m_optionStream class Options { public: static Options& getOptions() { static Options instance; return instance; } Options(Options const&) = delete; void operator=(Options const&) = delete; Options& parseOptions(int argc, char* argv[]) { /* Parse help. */ ap::s_alignment = 30; std::string usage("Arg-parser Demo *** Singleton version *** (C) 2018. Szilard Ledan\nUsage: %p [options] name number [number...]\n\nOptions:"); m_help = PARSE_HELP("-h, --help, --usage", "show this help.", usage, argc, argv); /* Parse flags. */ m_frequency = PARSE_FLAG("-f, --frequency FREQ", 60, "set rendering frequency.\n Default is '%d', but '%d' is not the best."); m_Frequency = PARSE_FLAG("+f, ++frequency FREQ", 25, "set refreshing frequency. Default is '%d'."); m_size = PARSE_FLAG("--size SIZE", 300, "set size of window. Default is '%d'."); m_lineWidth = PARSE_FLAG("-w, --line-width LW", 3.14f, "set width of line. Default is '%d'."); m_path = PARSE_FLAG("-p, --path PATH", std::string("./build"), "set working dir. Default is '%d'."); m_dot = PARSE_FLAG("-d DOT", '.', "set separate char. Default is '%d'."); m_enable = PARSE_FLAG("-e, --enable", false, "enable something."); /* Parse arguments. */ m_from = PARSE_ARG(m_from); m_to.push_back(PARSE_ARG(3)); while (!m_help && UNPARSED_COUNT()) { m_to.push_back(PARSE_ARG(0)); } return *this; } bool m_help = false; int m_frequency = 60; int m_Frequency = 25; uint m_size = 300; float m_lineWidth = 3.14; std::string m_path = "./build"; char m_dot = '.'; bool m_enable = false; std::string m_from = "ABC"; std::vector<int> m_to; std::stringstream m_optionStream; private: Options() {} }; int option_main(int argc, char* argv[]) { Options& options = Options::getOptions().parseOptions(argc, argv); if (options.m_help) { std::cout << options.m_optionStream.str(); return 0; } std::cout << "m_help: " << options.m_help << std::endl; std::cout << "m_frequency: " << options.m_frequency << std::endl; std::cout << "m_Frequency: " << options.m_Frequency << std::endl; std::cout << "m_size: " << options.m_size << std::endl; std::cout << "m_lineWidth: " << options.m_lineWidth << std::endl; std::cout << "m_path: " << options.m_path << std::endl; std::cout << "m_dot: " << options.m_dot << std::endl; std::cout << "m_enable: " << options.m_enable << std::endl; std::cout << "m_from: " << options.m_from << std::endl; std::cout << "m_to: "; for (size_t i = 0; i < options.m_to.size(); ++i) std::cout << options.m_to[i] << " "; std::cout << std::endl; return 0; }
46.10596
216
0.598104
[ "vector" ]
426d284ce406664b176d4f7e2fbe82b52954e7e8
1,603
cpp
C++
d25/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
d25/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
d25/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #include "../helpers/string_helpers.cpp" typedef long long int ll; int W,H; vector<string> input; void prepare() { string s; while(getline(cin, s)){ W = s.size(); input.push_back(s); } H = input.size(); } void print_cuc(vector<string> a) { cout << endl; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ cout << a[i][j]; } cout << endl; } } vector<string> step(vector<string> a) { vector<string> ret(H, string(W, '.')); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(a[i][j] == '>'){ int jj = (j+1)%W; if(a[i][jj] == '.'){ ret[i][jj] = a[i][j]; } else { ret[i][j] = a[i][j]; } } if(a[i][j] == 'v'){ ret[i][j] = a[i][j]; } } } a = ret; ret = vector<string>(H,string(W, '.')); for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(a[i][j] == 'v'){ int ii = (i+1)%H; if(a[ii][j] == '.'){ ret[ii][j] = a[i][j]; } else { ret[i][j] = a[i][j]; } } if(a[i][j] == '>'){ ret[i][j] = a[i][j]; } } } return ret; } bool isEq(vector<string> a, vector<string> b){ for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(a[i][j] != b[i][j]) return false; } } return true; } ll first() { int st = 0; auto a = input; while(true){ st++; auto b = step(a); if(isEq(a,b)){ // print_cuc(b); // for printing final state return st; } a = b; } return -1; } ll second() { cout << "That's all folks ;)" << endl; return 0; } int main() { prepare(); cout << "First: " << first() << endl; cout << "Second: " << second() << endl; return 0; }
15.413462
47
0.475359
[ "vector" ]
f121002d654152e7b2c8e739a7c45e761c22a721
4,209
cpp
C++
src/vi/la/opencl/opencl_builder.cpp
ville-k/vinn
288d64c5d525ca2d887d829097567f3e0104ab34
[ "MIT" ]
39
2015-05-08T15:58:07.000Z
2021-08-20T22:49:38.000Z
src/vi/la/opencl/opencl_builder.cpp
ville-k/vinn
288d64c5d525ca2d887d829097567f3e0104ab34
[ "MIT" ]
null
null
null
src/vi/la/opencl/opencl_builder.cpp
ville-k/vinn
288d64c5d525ca2d887d829097567f3e0104ab34
[ "MIT" ]
10
2015-09-17T23:58:04.000Z
2020-05-09T10:09:10.000Z
#include "vi/la/opencl/opencl_builder.h" #include "vi/la/opencl/opencl_ostream.h" #include <algorithm> #include <CL/cl.hpp> #include <iterator> #include <sstream> #include <stdexcept> namespace vi { namespace la { namespace opencl { builder::builder(source_loader& loader) : _loader(loader) {} void builder::add_extension_requirements(const std::vector<std::string>& required) { _required_extensions.insert(required.begin(), required.end()); } void builder::add_source_paths(const std::vector<std::string>& paths) { for (const std::string& relative_path : paths) { if (!_loader.can_load(relative_path)) { throw std::invalid_argument("invalid source path: " + relative_path); } _source_paths.insert(relative_path); } } void builder::add_build_options(const std::vector<std::string>& options) { _build_options.insert(options.begin(), options.end()); } bool builder::can_build(cl::Context& context) const { if (!compiler_available(context)) { return false; } if (!supports_all_required_extensions(context)) { return false; } return true; } build_result builder::build(cl::Context& context) { build_result result; result.set_success(false); if (!can_build(context)) { result.set_log("build context does not support all required features"); return result; } // list owns and frees the source memory std::list<source> loaded_sources = load_sources(); cl::Program::Sources sources; for (const auto& source : loaded_sources) { // source lenght should not include null termination sources.push_back({source.data(), source.length() - 1U}); } cl::Program program(context, sources); std::vector<cl::Device> context_devices = context.getInfo<CL_CONTEXT_DEVICES>(); std::ostringstream log_stream; try { program.build(context_devices, combine_build_options().c_str()); result.set_program(program); result.set_success(true); log_stream << "Build succeeded" << std::endl; } catch (cl::Error& error) { result.set_success(false); log_stream << "Build failed" << std::endl; log_stream << "Error: " << error.what() << std::endl; log_stream << "Error code: " << error.err() << std::endl; } for (size_t device_index = 0; device_index < context_devices.size(); ++device_index) { cl::Device& device = context_devices[device_index]; log_stream << device; log_stream << "Build log: " << std::endl; log_stream << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl; } result.set_log(log_stream.str()); return result; } std::list<source> builder::load_sources() const { std::list<source> sources; for (const auto& path : _source_paths) { sources.push_back(_loader.load(path)); } return sources; } std::string builder::combine_build_options() const { std::string options; for (const std::string& option : _build_options) { options += option + " "; } return options; } bool builder::compiler_available(cl::Context& context) const { std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); for (cl::Device& device : devices) { cl_bool available = device.getInfo<CL_DEVICE_COMPILER_AVAILABLE>(); if (!available) { return false; } } return true; } bool builder::supports_all_required_extensions(cl::Context& context) const { std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); for (cl::Device& device : devices) { std::string extensions_string = device.getInfo<CL_DEVICE_EXTENSIONS>(); std::istringstream iss(extensions_string); std::set<std::string> available_extensions; std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::inserter(available_extensions, available_extensions.begin())); std::set<std::string> matching_extensions; std::set_intersection(available_extensions.begin(), available_extensions.end(), _required_extensions.begin(), _required_extensions.end(), std::inserter(matching_extensions, matching_extensions.begin())); if (matching_extensions != _required_extensions) { return false; } } return true; } } } }
30.948529
92
0.694939
[ "vector" ]
f12610c6e6178eb8915acaf0987470ef791a1bb4
11,872
cpp
C++
src/cli.cpp
brex-it/3dconv
8efa4da731ce453ddb200fb192f17e277560821e
[ "BSD-3-Clause" ]
null
null
null
src/cli.cpp
brex-it/3dconv
8efa4da731ce453ddb200fb192f17e277560821e
[ "BSD-3-Clause" ]
null
null
null
src/cli.cpp
brex-it/3dconv
8efa4da731ce453ddb200fb192f17e277560821e
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <cstdlib> #include <filesystem> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include <CLI11/CLI11.hpp> #include <3dconv/cli.hpp> #include <3dconv/io.hpp> #include <3dconv/linalg.hpp> #include <3dconv/model.hpp> const char *FACE_TRANSFORMS_HELP_MSG = R"MSG( Supported face transformations: -------------------------------- Transformation | Command ------------------+----------- Convexification | c Triangulation | t Any combination of these will be accepted. Multiple transformations can be given as a comma separated list of the above commands. E.g.: c,t,t,c,t These operations are idempotent, so they can be applied multiple times, like in the example above, with no further effect after the first application. )MSG"; const char *MODEL_TRANSFORMS_HELP_MSG = R"MSG( Supported model transformations: -------------------------------- Transformation | Command ------------------+----------------------------------------------- Rotation | ro:<axis-x>:<axis-y>:<axis-z>:<angle-in-rad> Scaling | sc:<factor> Skew | sk:<domain-letter><range-letter>:<angle> Translation | tr:<direction-x>:<direction-y>:<direction-z> Any combination of these will be accepted. Multiple transformations can be given as a comma separated list of the above commands. E.g.: sc:3.7,ro:1:1:0:1.57,sc:2.4,tr:-4.2:-.3:3.6,sk:zy:1.57 In the skew command the domain and range letters can either be 'x', 'y' or 'z' meaning that in which direction should we move (domain) from the origin to achieve skewing in an another direction (range). )MSG"; const char *PROPERTIES_HELP_MSG = R"MSG( Supported properties and their flags: ------------------------------------- Property name | Flag ------------------+-------- connectivity | c convexity | x surface area | s triangularity | t volume | v water tightness | w Or simply write 'a' to print all of the listed properties. Any combination of these letter can be contained in the string given as an argument for --print-properties but unsupported letters will result in an error. If 'a' is present, other flags will be omitted. )MSG"; using namespace std; using namespace linalg; namespace fs = std::filesystem; string print_file_formats_help() { ostringstream out; out << endl; out << "Supported file formats:" << endl; out << "---------------------" << endl; out << " INPUT:" << endl; for (const auto &p : IOMap<Parser>::instance().map()) { out << " * " << p.first << endl; } out << endl; out << " OUTPUT:" << endl; for (const auto &w : IOMap<Writer>::instance().map()) { out << " * " << w.first << endl; } out << endl; return out.str(); } CLIContext::CLIContext(int argc, char *argv[]) { CLI::App cli_app; /* Order-insensitive options */ string ioformats; cli_app.add_option("-i,--input", ifile_, "Input file")->required() ->check(CLI::ExistingFile); cli_app.add_option("-o,--output", ofile_, "Output file"); cli_app.add_option("-f,--file-formats", ioformats, "Input and output file formats in the form [in-format]:[out-format] " "(If not specified the input and output file extensions will " "be used to determine the file formats.)"); cli_app.add_option("-v,--verbosity", verbosity_, "Sets the verbosity level (0 causes silent run)")->default_val(1); /* Order-sensitive options (so called "actions") */ vector<string> props, ftransforms, mtransforms; auto prop_opt = cli_app.add_option("-p,--print-properties", props, "Print model properties"); auto ftrans_opt = cli_app.add_option("-F,--face-transformation", ftransforms, "Face transformation string"); auto mtrans_opt = cli_app.add_option("-T,--transformation," "--model-transformation", mtransforms, "Model transformation string"); /* Callback for creating a detailed help message * TODO: Move this into a source-independent man page */ cli_app.footer([](){ ostringstream txt; txt << print_file_formats_help(); txt << PROPERTIES_HELP_MSG; txt << FACE_TRANSFORMS_HELP_MSG; txt << MODEL_TRANSFORMS_HELP_MSG; return txt.str(); }); /* Rethrow CLI11 exceptions and handle --help flag */ try { cli_app.parse(argc, argv); } catch (const CLI::CallForHelp &h) { exit(cli_app.exit(h)); } catch (const exception &e) { throw CLIError(e.what()); } /* Set the final value of iformat_ and oformat_ */ parse_ioformats(ifile_, ofile_, ioformats, iformat_, oformat_); /* Pack order-sensitive arguments into actions_ in the original order */ reverse(props.begin(), props.end()); reverse(ftransforms.begin(), ftransforms.end()); reverse(mtransforms.begin(), mtransforms.end()); using AT = Action::ActionType; for (const auto &o : cli_app.parse_order()) { if (o == prop_opt) { actions_.emplace_back(AT::PrintProperties, props.back()); props.pop_back(); } else if (o == ftrans_opt) { actions_.emplace_back(AT::FaceTransform, ftransforms.back()); ftransforms.pop_back(); } else if (o == mtrans_opt) { actions_.emplace_back(AT::ModelTransform, mtransforms.back()); mtransforms.pop_back(); } } } const string & CLIContext::ifile() const { return ifile_; } const string & CLIContext::ofile() const { return ofile_; } const string & CLIContext::iformat() const { return iformat_; } const string & CLIContext::oformat() const { return oformat_; } const std::vector<Action> & CLIContext::actions() const { return actions_; } int CLIContext::verbosity() const { return verbosity_; } InfoPrinter::InfoPrinter(int verbosity) : verbosity_level_{verbosity} {} void InfoPrinter::operator()(int verbosity, const std::string &s0, const std::string &s1) { if (verbosity <= verbosity_level_) { cout << ">>> " << s0 << s1 << endl; } } FaceTransforms parse_face_transforms(const string &trstr) { FaceTransforms ft; istringstream trss{trstr}; ostringstream err_msg; string command; while (getline(trss, command, ',')) { if (command.size() != 1) { err_msg << "Invalid face transformation: " << command; throw CLIError(err_msg.str()); } switch (command[0]) { case 'c': ft.convexify = true; break; case 't': ft.triangulate = true; break; default: err_msg << "Unknown face transformation: " << command; throw CLIError(err_msg.str()); } } return ft; } void parse_ioformats(const string &ifile, const string &ofile, const string &ioformats, string &iformat, string &oformat) { iformat.clear(); oformat.clear(); /* Parse file-formats string */ if (!ioformats.empty()) { if (ioformats.find(':') == string::npos) { throw CLIError("':' character cannot be omitted."); } istringstream ioss{ioformats}; string format; size_t i = 0; while (getline(ioss, format, ':')) { switch (i) { case 0: iformat = format; break; case 1: oformat = format; break; default: throw CLIError("Too many arguments for " "format specification."); } ++i; } } /* If either of the formats are unset, check the file extensions */ if (iformat.empty()) { fs::path ipath{ifile}; if (ipath.has_extension()) { iformat = ipath.extension().string().substr(1); } else { throw CLIError("Unable to determine input file format."); } } if (oformat.empty()) { fs::path opath{ofile}; if (opath.has_extension()) { oformat = opath.extension().string().substr(1); } else if (!opath.empty()) { throw CLIError("Unable to determine output file format."); } } } FMatSq<float, 4> parse_model_transforms(const string &trstr) { auto trmat = make_id_mat<float, 4>(); istringstream trss{trstr}; ostringstream err_msg; string part; while (getline(trss, part, ',')) { istringstream pss{part}; string opcode, arg; if (getline(pss, opcode, ':')) { size_t i = 0; if (opcode == "ro") { /* Rotation */ FVec<float, 3> axis; float angle{0.f}; while (getline(pss, arg, ':')) { if (i >= 4) { throw CLIError("Too many arguments " "for rotation."); } if (i == 3) { angle = stof(arg); } else { axis[i] = stof(arg); } ++i; } if (i < 4) { throw CLIError("Not enough arguments " "for rotation."); } trmat *= make_rotation_mat(axis, angle); } else if (opcode == "sc") { /* Scaling */ float factor{1.f}; while (getline(pss, arg, ':')) { if (i >= 1) { throw CLIError("Too many arguments " "for scaling."); } factor = stof(arg); ++i; } if (i < 1) { throw CLIError("Not enough arguments " "for scaling."); } trmat *= make_scaling_mat<float, 3>(factor); } else if (opcode == "sk") { /* Skew */ size_t domain_dim, range_dim; float angle{}; while (getline(pss, arg, ':')) { if (i >= 2) { throw CLIError("Too many arguments " "for skew."); } if (i == 0) { if (arg.size() != 2 || arg[0] == arg[1]) { throw CLIError("Invalid skew map."); } switch (arg[0]) { case 'x': domain_dim = 0; break; case 'y': domain_dim = 1; break; case 'z': domain_dim = 2; break; default: throw CLIError("Invalid skew domain."); } switch (arg[1]) { case 'x': range_dim = 0; break; case 'y': range_dim = 1; break; case 'z': range_dim = 2; break; default: throw CLIError("Invalid skew range."); } } else { angle = stof(arg); } ++i; } if (i < 2) { throw CLIError("Not enough arguments for skew."); } trmat *= make_skew_mat<float, 3>(domain_dim, range_dim, angle); } else if (opcode == "tr") { /* Translation */ FVec<float, 3> tvec; while (getline(pss, arg, ':')) { if (i >= 3) { throw CLIError("Too many arguments " "for translation."); } tvec[i] = stof(arg); ++i; } if (i < 3) { throw CLIError("Not enough arguments " "for translation."); } trmat *= make_translation_mat(tvec); } else { err_msg << "Unknown transformation: " << opcode; throw CLIError(err_msg.str()); } } else { err_msg << "Missing transformation." << part; throw CLIError(err_msg.str()); } } return trmat; } void print_properties(shared_ptr<Model> m, const string &prop_str) { bool all{false}; bool connectivity{false}; bool convexity{false}; bool surface_area{false}; bool triangularity{false}; bool volume{false}; bool water_tightness{false}; for (const auto c : prop_str) { switch (c) { case 'a': all = true; break; case 'c': connectivity = true; break; case 'x': convexity = true; break; case 's': surface_area = true; break; case 't': triangularity = true; break; case 'v': volume = true; break; case 'w': water_tightness = true; break; default: ostringstream err_msg; err_msg << "Unknown property flag: " << c; throw CLIError(err_msg.str()); } } if (all || connectivity) { cout << " * Is connected: " << (m->is_connected() ? "yes" : "no") << endl; } if (all || convexity) { cout << " * Is convex: " << (m->is_convex() ? "yes" : "no") << endl; } if (all || surface_area) { cout << " * Surface area: " << m->surface_area() << endl; } if (all || triangularity) { cout << " * Is triangulated: " << (m->is_triangulated() ? "yes" : "no") << endl; } if (all || volume) { cout << " * Volume: " << m->volume() << endl; } if (all || water_tightness) { string msg; bool wt = m->is_watertight(msg); cout << " * Is watertight: " << (wt ? "yes" : "no [" + msg + "]") << endl; } }
23.839357
73
0.603605
[ "vector", "model" ]
f127061fb5bc13e45506c60d9327f3f20c6986ef
10,558
cpp
C++
questions/compr-meta-nr-20866996/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
54
2015-09-13T07:29:52.000Z
2022-03-16T07:43:50.000Z
questions/compr-meta-nr-20866996/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
null
null
null
questions/compr-meta-nr-20866996/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
31
2016-08-26T13:35:01.000Z
2022-03-13T16:43:12.000Z
#include <QScopedPointer> #include <QApplication> #include <QWidget> #include <QPushButton> #include <QPlainTextEdit> #include <QSpinBox> #include <QFormLayout> #include <QSet> #include <QMetaMethod> #include <QThread> #include <QPointer> #include <QBasicTimer> #include <QDebug> /*! A type-identifier-generating wrapper for events. * See http://stackoverflow.com/a/19189941/1329652 for discussion */ template <typename Derived> class EventWrapper : public QEvent { public: EventWrapper() : QEvent(staticType()) {} static QEvent::Type staticType() { static QEvent::Type type = static_cast<QEvent::Type>(registerEventType()); return type; } static bool is(const QEvent * ev) { return ev->type() == staticType(); } static Derived* cast(QEvent * ev) { return is(ev) ? static_cast<Derived*>(ev) : 0; } }; /*! A metacall. */ class MetaCall { Q_DISABLE_COPY(MetaCall) public: QObject * const m_sender; int const m_signal; int const m_method; private: int m_nargs; void ** m_args; public: template <typename iter> MetaCall(QObject * sender, int signal, int method, iter arguments, iter argumentsEnd, void ** argv) : m_sender(sender), m_signal(signal), m_method(method), m_nargs(1 + (argumentsEnd - arguments)), // include return type m_args((void**) malloc(m_nargs*(sizeof(void*) + sizeof(int)))) { Q_CHECK_PTR(m_args); int *types = (int *)(m_args + m_nargs); types[0] = 0; // return type m_args[0] = 0; // return value // Copy the arguments and queue the call for (int i = 1; i < m_nargs; ++i) #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) m_args[i] = QMetaType::create((types[i] = *(arguments++)), argv[i]); #else m_args[i] = QMetaType::construct((types[i] = *(arguments++)), argv[i]); #endif } ~MetaCall() { if (! m_args) return; int * types = (int*)(m_args + m_nargs); for (int i = 0; i < m_nargs; ++i) { if (types[i] && m_args[i]) QMetaType::destroy(types[i], m_args[i]); } free(m_args); } void placeCall(QObject *object) { QMetaObject::metacall(object, QMetaObject::InvokeMetaMethod, m_method, m_args); } }; /*! A meta call event, carrying detachable meta call. */ class MetaCallEvent : public EventWrapper<MetaCallEvent> { QScopedPointer<class MetaCall> m_call; public: explicit MetaCallEvent(class MetaCall * call) : m_call(call) {} class MetaCall * take() { return m_call.take(); } const class MetaCall & operator->() const { return *m_call.data(); } }; /*! Notifies the target object that a compressed connection is to be added. */ class ConnectEvent : public EventWrapper<ConnectEvent> { int m_signal; QPointer<QObject> m_receiver; int m_method; public: explicit ConnectEvent(int signal, QObject * receiver, int method) : m_signal(signal), m_receiver(receiver), m_method(method) {} inline int signal() const { return m_signal; } inline const QPointer<QObject> & receiver() const { return m_receiver; } inline int method() const { return m_method; } }; /*! Represents a compressed connection to a target object. */ struct CompressedConnection { bool valid; QVector<int> argumentTypes; int signal; QPointer<QObject> target; int method; CompressedConnection() : valid(false) {} CompressedConnection(QObject * sender, int signal_, const QPointer<QObject> & target_, int method_) : valid(false), signal(signal_), target(target_), method(method_) { QMetaMethod sig = sender->metaObject()->method(signal_); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) int nparams = sig.parameterCount(); argumentTypes.resize(nparams); valid = true; for (int i = 0; i < nparams; ++i) { if ((argumentTypes[i] = sig.parameterType(i)) == QMetaType::UnknownType) valid = false; } #else const QList<QByteArray> & types = sig.parameterTypes(); int nparams = types.count(); argumentTypes.resize(nparams); valid = true; for (int i = 0; i < nparams; ++i) { int type = QMetaType::type(types[i].constData()); if ((argumentTypes[i] = type) == 0) valid = false; } #endif } }; /*! Compressor proxy attached to each sender. */ class CompressProxy : public QObject { int m_endIndex; QList<CompressedConnection> m_connections; int qt_metacall(QMetaObject::Call call, int id, void ** argv) { if (id < m_endIndex) return QObject::qt_metacall(call, id, argv); id -= m_endIndex; if (id > m_connections.size()) return 0; const CompressedConnection & conn = m_connections.at(id); qDebug() << "got metacall [" << id << "] for" << conn.target.data(); QScopedPointer<MetaCall> mc(new MetaCall(parent(), conn.signal, conn.method, conn.argumentTypes.begin(), conn.argumentTypes.end(), argv)); QCoreApplication::postEvent(conn.target, new MetaCallEvent(mc.take())); return -1; } void customEvent(QEvent * ev) { if (ev->type() != ConnectEvent::staticType()) return; QObject * sender = parent(); ConnectEvent * cev = static_cast<ConnectEvent*>(ev); const CompressedConnection & conn = CompressedConnection(sender, cev->signal(), cev->receiver(), cev->method()); if (conn.valid) { m_connections << conn; QMetaObject::connect(sender, cev->signal(), this, m_endIndex + m_connections.size() - 1); } } public: explicit CompressProxy(QObject * parent) : QObject(parent), m_endIndex(staticMetaObject.methodOffset() + staticMetaObject.methodCount()) {} }; // A per-thread proxy exists. // Compression is done via a custom connection to the *proxy* object. Setup: // 1. The proxy installs itself as an event filter on the target. // 2. A proxy // registered with the proxy. // Compression is done via a custom connection to the target object. The connection uses a non-existent slot. // The proxy is per-thread, it is only used to // The proxy is per-thread. It's used to filter metacall and call flush events. // 1. Receive a metacall event. // 2. Check if a call flush flag is set on the object. // If not, post a call flush event and set the flag. That event brackets the event queue. // 3. In a per-object map in the userdata, retain a copy of the event data. // ... // 1. Receive a call flush event. // 2. Execute the queued calls. /*! A compressor application that processes ConnectEvent and MetaCallEvent deliveries. */ template <class Base> class CompressorApplication : public Base { public: CompressorApplication(int & argc, char ** argv) : Base(argc, argv) {} protected: bool notify(QObject * receiver, QEvent * event) { if (event->type() == ConnectEvent::staticType()) { #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) CompressProxy * proxy = receiver->findChild<CompressProxy*>(QString(), Qt::FindDirectChildrenOnly); #else CompressProxy * proxy = receiver->findChild<CompressProxy*>(); #endif if (! proxy) proxy = new CompressProxy(receiver); return Base::notify(proxy, event); } else if (event->type() == MetaCallEvent::staticType()) { MetaCallEvent * mc = static_cast<MetaCallEvent*>(event); QScopedPointer<MetaCall> call(mc->take()); call->placeCall(receiver); } return Base::notify(receiver, event); } }; bool compressedConnect(QObject * sender, const char * signalRaw, QObject * receiver, const char * methodRaw) { if (signalRaw[0] != '0'+QSIGNAL_CODE || (methodRaw[0] != '0'+QSIGNAL_CODE && methodRaw[0] != '0'+QSLOT_CODE && methodRaw[0] != '0'+QMETHOD_CODE)) return false; QByteArray signal = QMetaObject::normalizedSignature(signalRaw + 1); QByteArray method = QMetaObject::normalizedSignature(methodRaw + 1); if (! QMetaObject::checkConnectArgs(signal, method)) return false; int signalIndex = sender->metaObject()->indexOfSignal(signal); int methodIndex = receiver->metaObject()->indexOfMethod(method); if (signalIndex < 0 || methodIndex < 0) return false; if (sender->thread() == QThread::currentThread()) { ConnectEvent event(signalIndex, receiver, methodIndex); QCoreApplication::sendEvent(sender, &event); } else { QCoreApplication::postEvent(sender, new ConnectEvent(signalIndex, receiver, methodIndex)); } return true; } // // Demo GUI class Signaller : public QObject { Q_OBJECT public: Q_SIGNAL void emptySignal(); Q_SIGNAL void dataSignal(int); }; class Widget : public QWidget { Q_OBJECT QBasicTimer m_timer; QPlainTextEdit * m_edit; QSpinBox * m_count; Signaller m_signaller; Q_SLOT void emptySlot() { m_edit->appendPlainText("emptySlot invoked"); qDebug() << "empty slot"; m_timer.start(0, this); } Q_SLOT void dataSlot(int n) { m_edit->appendPlainText(QString("dataSlot(%1) invoked").arg(n)); } Q_SLOT void sendSignals() { m_edit->appendPlainText(QString("\nEmitting %1 signals").arg(m_count->value())); for (int i = 0; i < m_count->value(); ++ i) { emit m_signaller.emptySignal(); emit m_signaller.dataSignal(i + 1); } } void timerEvent(QTimerEvent * ev) { if (ev->timerId() == m_timer.timerId()) { qDebug() << "timer 0"; m_timer.stop(); } } public: Widget(QWidget * parent = 0) : QWidget(parent), m_edit(new QPlainTextEdit), m_count(new QSpinBox) { QFormLayout * l = new QFormLayout(this); QPushButton * invoke = new QPushButton("Invoke"); m_edit->setReadOnly(true); m_count->setRange(1, 1000); l->addRow("Number of slot invocations", m_count); l->addRow(invoke); l->addRow(m_edit); connect(invoke, SIGNAL(clicked()), SLOT(sendSignals()), Qt::QueuedConnection); m_edit->appendPlainText(QString("Qt %1").arg(qVersion())); compressedConnect(&m_signaller, SIGNAL(emptySignal()), this, SLOT(emptySlot())); compressedConnect(&m_signaller, SIGNAL(dataSignal(int)), this, SLOT(dataSlot(int))); } }; int main(int argc, char *argv[]) { CompressorApplication<QApplication> a(argc, argv); Widget w; w.show(); return a.exec(); } #include "main.moc"
37.842294
127
0.639799
[ "object" ]
f12d160a3fbd97cbef0faba709333421d6ff092e
2,561
cc
C++
launcher/mk-sched/smart_even_scheduler.cc
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
launcher/mk-sched/smart_even_scheduler.cc
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
launcher/mk-sched/smart_even_scheduler.cc
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
#include <cassert> #include "../../common/kernel_info_t.h" #include "smart_even_scheduler.h" extern unsigned long long get_curr_cycle(); void SmartEvenScheduler::update_scheduler(const SchedulerUpdateInfo& info) { if (info.has("AdjustSMs")) { adjust_upper_bounds(); } } void SmartEvenScheduler::add_kernel(kernel_info_t* kernel, unsigned max_cta_per_shader) { DynamicScheduler::add_kernel(kernel, max_cta_per_shader); adjust_upper_bounds(); } void SmartEvenScheduler::remove_kernel(kernel_info_t* kernel) { DynamicScheduler::remove_kernel(kernel); adjust_upper_bounds(); } void SmartEvenScheduler::adjust_upper_bounds() { const unsigned num_kernels = SM_infos.size(); const unsigned even_split = num_SMs / num_kernels; int remaining_SMs = num_SMs - (even_split * num_kernels); std::vector<kernel_info_t*> non_thread_block_bound_kernels; std::map<kernel_info_t*, unsigned> new_allocs; for (std::map<kernel_info_t*, SM_info>::iterator it = SM_infos.begin(), it_end = SM_infos.end(); it != it_end; ++it) { kernel_info_t* kernel = it->first; unsigned required_shaders = kernel->get_required_shaders(); if (even_split >= required_shaders) { // thread block bound!! remaining_SMs += even_split - required_shaders; new_allocs[kernel] = required_shaders; //it->second.set_upper_bound(required_shaders); } else { new_allocs[kernel] = even_split; non_thread_block_bound_kernels.push_back(kernel); } } while (remaining_SMs > 0 && !non_thread_block_bound_kernels.empty()) { bool no_kernel_to_allocate = true; for (std::vector<kernel_info_t*>::const_iterator it = non_thread_block_bound_kernels.begin(), it_end = non_thread_block_bound_kernels.end(); it != it_end; ++it) { kernel_info_t* kernel = *it; // not thread block bound if (kernel->get_required_shaders() > new_allocs[kernel]) { ++new_allocs[kernel]; --remaining_SMs; no_kernel_to_allocate = false; } } if (no_kernel_to_allocate) { break; } } for (std::map<kernel_info_t*, SM_info>::iterator it = SM_infos.begin(), it_end = SM_infos.end(); it != it_end; ++it) { kernel_info_t* kernel = it->first; if (new_allocs[kernel] != it->second.num_expected_shader()) { printf("GPGPU-Sim Smart: Process %d, kernel %s, sets SMs to %d @(%llu)\n", kernel->get_parent_process()->getID(), kernel->name().c_str(), new_allocs[kernel], get_curr_cycle()); } it->second.set_upper_bound(new_allocs[kernel]); } }
30.488095
182
0.696212
[ "vector" ]
f135448556bf43c76b6ba6c28f9077d762a3eb87
2,284
cpp
C++
icpcarchive.ecs.baylor.edu/Languages.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
icpcarchive.ecs.baylor.edu/Languages.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
icpcarchive.ecs.baylor.edu/Languages.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4534 Name: Languages Date: 17/03/2016 */ #include <bits/stdc++.h> #define endl "\n" #define EPS 1e-9 #define MP make_pair #define F first #define S second #define DB(x) cerr << " #" << (#x) << ": " << (x) #define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl const double PI = acos(-1.0); #define INF 1000000000 //#define MOD 1000000007ll //#define MAXN 1000005 using namespace std; typedef long long ll; typedef unsigned long long llu; typedef pair<int, int> ii; typedef pair<ii, ii> iiii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii; struct node { int word_idx; unordered_map<char, int> next; node () {word_idx = -1;} }; int n, size, ans; string lang[105], line, word; node trie[25605]; stringstream ss; inline void trie_insert (string& word, int word_idx) { int idx = 0; for (int i=0; i<word.length(); i++) { if (trie[idx].next.find(word[i]) == trie[idx].next.end()) trie[idx].next[word[i]] = size++; idx = trie[idx].next[word[i]]; } trie[idx].word_idx = word_idx; } inline int find (string& word) { int idx = 0; for (int i=0; i<word.length(); i++) { if (trie[idx].next.find(word[i]) == trie[idx].next.end()) return -1; idx = trie[idx].next[word[i]]; } return trie[idx].word_idx; } int main () { #ifdef ONLINE_JUDGE ios_base::sync_with_stdio(0); cin.tie(0); #endif //cout<<fixed<<setprecision(3); //cerr<<fixed<<setprecision(3); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) int tc = 1, i, j; cin>>n; size = 1; for (i=0; i<n; i++) { cin>>lang[i]; getline(cin, line); for (j=0; j<line.length(); j++) line[j] = tolower(line[j]); ss.clear(); ss.str(line); while (ss>>word) trie_insert(word, i); } getline(cin, line); while (getline(cin, line)) { for (i=0; i<line.length(); i++) if (line[i] == '.' || line[i] == ',' || line[i] == '!' || line[i] == '?' || line[i] == ';' || line[i] =='(' || line[i] == ')') line[i] = ' '; else line[i] = tolower(line[i]); ss.clear(); ss.str(line); while (ss>>word) { ans = find(word); if (ans != -1) { cout<<lang[ans]<<endl; break; } } } return 0; }
24.55914
126
0.586252
[ "vector" ]
f137c9cb74f801e3efbdddd50786db1c47b03b9a
15,533
cpp
C++
lonestar/eda/cpu/SPRoute/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
lonestar/eda/cpu/SPRoute/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
lonestar/eda/cpu/SPRoute/main.cpp
lineagech/Galois
5c7c0abaf7253cb354e35a3836147a960a37ad5b
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include "galois/Galois.h" #include "galois/Reduction.h" #include "galois/PriorityQueue.h" #include "galois/Timer.h" #include "galois/graphs/Graph.h" #include "galois/graphs/TypeTraits.h" #include "galois/substrate/SimpleLock.h" #include "galois/AtomicHelpers.h" #include "galois/runtime/Profile.h" #include "galois/LargeArray.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include "Lonestar/BFS_SSSP.h" #include "DataType.h" #include "flute.h" #include "DataProc.h" #include "RSMT.h" #include "maze.h" #include "RipUp.h" #include "utility.h" #include "route.h" #include "maze3D.h" #include "maze_finegrain.h" #include "maze_finegrain_lateupdate.h" #include "maze_lock.h" static const char* name = "SPRoute"; static const char* desc = "A Scalable Parallel global router with a hybrid parallel algorithm which " "combines net-level parallelism and fine-grain parallelism"; static const char* url = "SPRoute"; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<std::string> outfile("o", cll::desc("output file (optional)"), cll::init("")); static cll::opt<std::string> fluteDir("flute", cll::desc("directory of POWV9.dat and POST9.dat (REQUIRED)"), cll::Required); int main(int argc, char** argv) { // char benchFile[FILESTRLEN]; clock_t t1, t2, t3; float gen_brk_Time, reading_Time; int enlarge, ripup_threshold; int i; int ESTEP1, CSTEP1, thStep1; int ESTEP2, CSTEP2, thStep2; int ESTEP3, CSTEP3, tUsage; int Ripvalue, LVIter, cost_step; int maxOverflow, past_cong, last_cong, finallength, numVia, ripupTH3D, newTH, healingTrigger; int minofl, minoflrnd = 0, mazeRound, upType, cost_type, bmfl, bwcnt; bool goingLV, noADJ, needOUTPUT; needOUTPUT = false; /*string outFile; for(int i = 1; i < argc; i++) { string tmp(argv[i]); if(tmp == "-t") numThreads = atoi(argv[i+1]); else if(tmp == "-o") { outFile = string(argv[i+1]); needOUTPUT = true; } else if(tmp == "-h" || tmp == "--help") { printf("Usage: ./SPRoute <input> -o <output> -t <nthreads> \n"); exit(1); } }*/ galois::SharedMemSys G; LonestarStart(argc, argv, name, desc, url); galois::preAlloc(numThreads * 2); if (outfile != "") { needOUTPUT = true; } LB = 0.9; UB = 1.3; SLOPE = 5; THRESH_M = 20; ENLARGE = 15; // 5 ESTEP1 = 10; // 10 ESTEP2 = 5; // 5 ESTEP3 = 5; // 5 CSTEP1 = 2; // 5 CSTEP2 = 2; // 3 CSTEP3 = 5; // 15 COSHEIGHT = 4; L = 0; VIA = 2; Ripvalue = -1; ripupTH3D = 10; goingLV = TRUE; noADJ = FALSE; thStep1 = 10; thStep2 = 4; LVIter = 3; mazeRound = 500; bmfl = BIG_INT; minofl = BIG_INT; // galois::substrate::PerThreadStorage<THREAD_LOCAL_STORAGE> // thread_local_storage; galois::setActiveThreads(numThreads); /* galois::on_each( [&] (const unsigned tid, const unsigned numT) { printf("threadid: %d %d\n", tid, numT); } ); */ cout << " nthreads: " << numThreads << endl; int finegrain = false; int thread_choice = 0; // int thread_steps[6] = {28,14,8,4,1}; // int thread_livelock_limit[6] = {1,1,1,1,1}; bool extrarun = false; int thread_livelock = 0; if (1) { t1 = clock(); printf("\nReading %s ...\n", filename.c_str()); readFile(filename.c_str()); printf("\nReading Lookup Table ...\n"); readLUT(fluteDir.c_str()); printf("\nDone reading table\n\n"); t2 = clock(); reading_Time = (float)(t2 - t1) / CLOCKS_PER_SEC; printf("Reading Time: %f sec\n", reading_Time); // call FLUTE to generate RSMT and break the nets into segments (2-pin nets) VIA = 2; // viacost = VIA; viacost = 0; gen_brk_RSMT(FALSE, FALSE, FALSE, FALSE, noADJ); printf("first L\n"); routeLAll(TRUE); gen_brk_RSMT(TRUE, TRUE, TRUE, FALSE, noADJ); getOverflow2D(&maxOverflow); printf("second L\n"); newrouteLAll(FALSE, TRUE); getOverflow2D(&maxOverflow); spiralRouteAll(); newrouteZAll(10); printf("first Z\n"); past_cong = getOverflow2D(&maxOverflow); convertToMazeroute(); enlarge = 10; newTH = 10; healingTrigger = 0; stopDEC = 0; upType = 1; // iniBDE(); costheight = COSHEIGHT; if (maxOverflow > 700) { costheight = 8; LOGIS_COF = 1.33; VIA = 0; THRESH_M = 0; CSTEP1 = 30; slope = BIG_INT; } for (i = 0; i < LVIter; i++) { LOGIS_COF = max(2.0 / (1 + log(maxOverflow)), LOGIS_COF); LOGIS_COF = 2.0 / (1 + log(maxOverflow)); printf("LV routing round %d, enlarge %d \n", i, enlarge); routeLVAll(newTH, enlarge); past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); enlarge += 5; newTH -= 5; if (newTH < 1) { newTH = 1; } } // past_cong = getOverflow2Dmaze( &maxOverflow); t3 = clock(); reading_Time = (float)(t3 - t2) / CLOCKS_PER_SEC; printf("LV Time: %f sec\n", reading_Time); InitEstUsage(); i = 1; costheight = COSHEIGHT; enlarge = ENLARGE; ripup_threshold = Ripvalue; minofl = totalOverflow; stopDEC = FALSE; slope = 20; L = 1; cost_type = 1; InitLastUsage(upType); // OrderNetEdge* netEO = (OrderNetEdge*)calloc(2000, sizeof(OrderNetEdge)); PRINT_HEAT = 0; // checkUsageCorrectness(); galois::StatTimer roundtimer("round"); unsigned long oldtime = 0; round_avg_dist = 0; round_avg_length = 0; while (totalOverflow > 0) { if (THRESH_M > 15) { THRESH_M -= thStep1; } else if (THRESH_M >= 2) { THRESH_M -= thStep2; } else { THRESH_M = 0; } if (THRESH_M <= 0) { THRESH_M = 0; } // std::cout << "totalOverflow : " << totalOverflow << " enlarge: " << // enlarge << std::endl; if (totalOverflow > 2000) { enlarge += ESTEP1; // ENLARGE+(i-1)*ESTEP; cost_step = CSTEP1; updateCongestionHistory(upType); } else if (totalOverflow < 500) { cost_step = CSTEP3; enlarge += ESTEP3; ripup_threshold = -1; updateCongestionHistory(upType); } else { cost_step = CSTEP2; enlarge += ESTEP2; updateCongestionHistory(upType); } if (totalOverflow > 15000 && maxOverflow > 400) { enlarge = max(xGrid, yGrid) / 30; // This is the key!!!! to enlarge routing area!!!! // enlarge = max(xGrid,yGrid) / 10; slope = BIG_INT; // slope = 20; if (i == 5) { VIA = 0; LOGIS_COF = 1.33; ripup_threshold = -1; // cost_type = 3; } else if (i > 6) { if (i % 2 == 0) { LOGIS_COF += 0.5; } if (i > 20) { break; } } if (i > 10) { cost_type = 1; ripup_threshold = 0; } } int maxGrid = max(xGrid + 1, yGrid + 1); enlarge = min(enlarge, maxGrid / 2); // std::cout << "costheight : " << costheight << " enlarge: " << enlarge // << std::endl; costheight += cost_step; // std::cout << "costheight : " << costheight << " enlarge: " << enlarge // << std::endl; mazeedge_Threshold = THRESH_M; if (upType == 3) { LOGIS_COF = max(2.0 / (1 + log(maxOverflow + max_adj)), LOGIS_COF); } else { LOGIS_COF = max(2.0 / (1 + log(maxOverflow)), LOGIS_COF); } if (i == 8) { L = 0; upType = 2; InitLastUsage(upType); } if (maxOverflow == 1) { // L = 0; ripup_threshold = -1; slope = 5; } if (maxOverflow > 300 && past_cong > 15000) { L = 0; } // checkUsageCorrectness(); // getOverflow2Dmaze(&maxOverflow , & tUsage); printf("iteration %d, enlarge %d, costheight %d, threshold %d via cost " "%d \nlog_coef %f, healingTrigger %d cost_step %d slope %d L %f " "cost_type %d OBIM delta %d\n", i, enlarge, costheight, mazeedge_Threshold, VIA, LOGIS_COF, healingTrigger, cost_step, slope, L, cost_type, max(OBIM_delta, (int)(costheight / (2 * slope)))); // L = 2; roundtimer.start(); round_num = i; if (finegrain) { printf("finegrain\n"); mazeRouteMSMD_finegrain_spinlock(i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } else { mazeRouteMSMD(i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } roundtimer.stop(); cout << "round : " << i << " time(ms): " << roundtimer.get() - oldtime << " acc time(ms): " << roundtimer.get() << endl; oldtime = roundtimer.get(); last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); int nthreads_tmp = numThreads; if (past_cong > last_cong && !extrarun) // Michael { if (!finegrain && nthreads_tmp != 1) { thread_livelock++; if (thread_livelock == 1) { thread_choice++; thread_livelock = 0; if (nthreads_tmp < 6) { galois::setActiveThreads(4); numThreads = 4; finegrain = true; } else { numThreads = numThreads / 2; galois::setActiveThreads(numThreads); } } } } cout << "nthreads :" << numThreads << endl; extrarun = false; if (minofl > past_cong) { minofl = past_cong; minoflrnd = i; } if (i == 8) { L = 1; } i++; if (past_cong < 200 && i > 30 && upType == 2 && max_adj <= 20) { upType = 4; stopDEC = TRUE; } if (maxOverflow < 150) { if (i == 20 && past_cong > 200) { printf("Extra Run for hard benchmark\n"); L = 0; upType = 3; stopDEC = TRUE; slope = 5; galois::runtime::profileVtune( [&](void) { if (finegrain) { printf("finegrain\n"); mazeRouteMSMD_finegrain_spinlock( i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } else { mazeRouteMSMD(i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } }, "mazeroute"); last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); extrarun = true; str_accu(12); L = 1; stopDEC = FALSE; slope = 3; upType = 2; } if (i == 35 && tUsage > 800000) { str_accu(25); extrarun = true; } if (i == 50 && tUsage > 800000) { str_accu(40); extrarun = true; } } if (i > 50) { upType = 4; if (i > 70) { stopDEC = TRUE; } } if (past_cong > 0.7 * last_cong) { costheight += CSTEP3; } if (past_cong >= last_cong) { VIA = 0; // is this good? healingTrigger++; } if (past_cong < bmfl) { bwcnt = 0; if (i > 140 || (i > 80 && past_cong < 20)) { copyRS(); bmfl = past_cong; L = 0; slope = BIG_INT; // SLOPE = BIG_INT; galois::runtime::profileVtune( [&](void) { if (finegrain) { printf("finegrain\n"); mazeRouteMSMD_finegrain_spinlock( i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } else { mazeRouteMSMD(i, enlarge, costheight, ripup_threshold, mazeedge_Threshold, !(i % 3), cost_type); } }, "mazeroute"); last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); extrarun = true; if (past_cong < last_cong) { copyRS(); bmfl = past_cong; } L = 1; slope = 5; // SLOPE = 5; if (minofl > past_cong) { minofl = past_cong; minoflrnd = i; } if (bmfl < 72) break; } } else { bwcnt++; } if (bmfl > 10) { if (bmfl > 30 && bmfl < 72 && bwcnt > 50) { break; } if (bmfl < 30 && bwcnt > 50) { break; } if (i >= mazeRound) { getOverflow2Dmaze(&maxOverflow, &tUsage); break; } } if (i >= mazeRound) { getOverflow2Dmaze(&maxOverflow, &tUsage); break; } } if (minofl > 0) { printf("\n\n minimal ofl %d, occuring at round %d\n\n", minofl, minoflrnd); copyBR(); } freeRR(); checkUsage(); printf("maze routing finished\n"); // t4 = clock(); // maze_Time = (float)(t4-t3)/CLOCKS_PER_SEC; // printf("P3 runtime: %f sec\n", maze_Time); printf("Final 2D results: \n"); getOverflow2Dmaze(&maxOverflow, &tUsage); printf("\nLayer Assignment Begins"); newLA(); printf("layer assignment finished\n"); t2 = clock(); gen_brk_Time = (float)(t2 - t1) / CLOCKS_PER_SEC; // printf("2D + Layer Assignment Runtime: %f sec\n", gen_brk_Time); costheight = 3; viacost = 1; if (gen_brk_Time < 60) { ripupTH3D = 15; } else if (gen_brk_Time < 120) { ripupTH3D = 18; } else { ripupTH3D = 20; } if (goingLV && past_cong == 0) { printf("Post Processing Begins \n"); mazeRouteMSMDOrder3D(enlarge, 0, ripupTH3D); // mazeRouteMSMDOrder3D(enlarge, 0, 10 ); if (gen_brk_Time > 120) { mazeRouteMSMDOrder3D(enlarge, 0, 12); } printf("Post Processsing finished, starting via filling\n"); } fillVIA(); finallength = getOverflow3D(); numVia = threeDVIA(); checkRoute3D(); if (needOUTPUT) { writeRoute3D(outfile.c_str()); } } // Input ==1 // t4 = clock(); // maze_Time = (float)(t4-t1)/CLOCKS_PER_SEC; printf("Final routing length : %d\n", finallength); printf("Final number of via : %d\n", numVia); printf("Final total length 1 : %d\n\n", finallength + numVia); // printf("Final total length 3 : %d\n",(finallength+3*numVia)); // printf("3D runtime: %f sec\n", maze_Time); // freeAllMemory(); return 0; }
26.73494
80
0.512457
[ "3d" ]
f13d53f30c3700355c2d348c806b818445f45ef5
8,206
cpp
C++
src/vineyards.cpp
corybrunson/dart
b51ff967998c99ffae370e502927af83404b8374
[ "Apache-2.0" ]
null
null
null
src/vineyards.cpp
corybrunson/dart
b51ff967998c99ffae370e502927af83404b8374
[ "Apache-2.0" ]
null
null
null
src/vineyards.cpp
corybrunson/dart
b51ff967998c99ffae370e502927af83404b8374
[ "Apache-2.0" ]
1
2021-07-21T16:15:16.000Z
2021-07-21T16:15:16.000Z
#include <Rcpp.h> using namespace Rcpp; #include "reduction_concepts.h" // #include "PspMatrix.h" // // Square transposition framework // template< typename Lambda > // void transpose_schedule_full(PspBoolMatrix& R, PspBoolMatrix& V, const vector< size_t >& S, Lambda f){ // const size_t nc = R.n_cols(); // const size_t nr = R.n_rows(); // if (nc == 0 || nr == 0){ return; } // if (nc != nr){ throw std::invalid_argument("R must be square."); } // auto max_el = std::max_element(S.begin(), S.end()); // if (*max_el >= (nc-1)){ throw std::invalid_argument("Given indices exceed matrix dimensions"); } // // // // Returns the current row index of the lowest entry in column j // // const auto low_index = [&R](size_t j) -> optional< size_t >{ // // if (R.column_empty(j)){ return(std::nullopt); } // // auto& c = *R.columns[j]; // // auto me = std::max_element(c.begin(), c.end(), [&R](auto& e1, auto& e2){ // // return R.otc[e1.first] < R.otc[e2.first]; // // }); // // return(R.otc[(*me).first]); // // }; // // // Construct three O(n)-sized maps to make various checks in the loop O(1) // auto positive = vector< bool >(nc); // whether a column is a creator or destroyer // auto Low = vector< optional< size_t > >(nc); // map from column index --> low index // auto RLow = vector< optional< size_t > >(nc); // map from low index --> column index // for (size_t j = 0; j < nc; ++j){ // positive[j] = R.column_empty(j); // Low[j] = R.lowest_nonzero(j); // if (Low[j]){ // RLow[Low[j].value()] = make_optional(j); // } // } // // // Perform the transpositions // size_t status = 0; // size_t line = 1; // for (auto i: S){ // auto j = i + 1; // Rcout << line << ": swapping(0) <=> " << i << "," << j << std::endl; // if (positive[i] && positive[j]){ // if (V(i,j) != 0){ V.add_cols(j, i); } // if (RLow[i] && RLow[j] && (R(i, *RLow[j]) != 0)){ // size_t k = RLow[i].value(), l = RLow[j].value(); // // Rprintf("k: %d, l: %d \n", k, l); // status = k < l ? 1 : 2; // Cases 1.1.1 and 1.1.2 // if (l < k){ std::swap(k,l); } // // R.swap(i,j); R.add_cols(l,k); // // V.swap(i,j); V.add_cols(l,k); // R.add_cols(l,k); R.swap(i,j); // V.add_cols(l,k); V.swap(i,j); // } else { // status = 3; // Case 1.2 // } // } else if (!positive[i] && !positive[j]){ // if (V(i,j) != 0){ // Case 2.1 // if (!bool(Low[i]) || !bool(Low[j])){ Rcpp::stop("Positive not maintained."); } // if (Low[i].value() < Low[j].value()){ // R.add_cols(j,i); R.swap(i,j); // V.add_cols(j,i); V.swap(i,j); // status = 4; // Case 2.1.1 // } else { // R.add_cols(j,i); R.swap(i,j); R.add_cols(j,i); // V.add_cols(j,i); V.swap(i,j); V.add_cols(j,i); // status = 5; // Case 2.1.2 // } // } else { // status = 6; // Case 2.2 // } // } else if (!positive[i] && positive[j]){ // if (V(i,j) != 0){ // R.add_cols(j,i); R.swap(i,j); R.add_cols(j,i); // V.add_cols(j,i); R.swap(i,j); V.add_cols(j,i); // status = 7; // Case 3.1 // } else { // status = 8; // Case 3.2 // } // } else { // status = 9; // Case 4 // if (V(i,j) != 0){ V.add_cols(j,i); } // } // // Cases 1.2, 2.2, 3.2, and 4 just need a single permutation // if (status == 0 || status == 9 || status == 8 || status == 6 || status == 3){ // // Rcout << "swapping: " << i << ", " << j << std::endl; // R.swap(i,j); V.swap(i,j); // } // // // Update all the maps (all in O(1)) // // positive[i] = R.column_empty(i); // // positive[j] = R.column_empty(j); // // Rcout << " --- Updating maps --- " << std::endl; // // Columns to update low entries of // // auto ck = RLow[i]; // // auto cl = RLow[j]; // // // // Rcout << " 1" << std::endl; // // Low[i] = R.lowest_nonzero(i); // // Low[j] = R.lowest_nonzero(j); // // if (ck){ Low[*ck] = R.lowest_nonzero(*ck); } // // if (cl){ Low[*cl] = R.lowest_nonzero(*cl); } // // // // Rcout << " 2" << std::endl; // // positive[i] = !bool(Low[i]); // // positive[j] = !bool(Low[j]); // // if (ck){ positive[*ck] = !bool(Low[*ck]); } // // if (cl){ positive[*cl] = !bool(Low[*cl]); } // // // Rcout << " 3" << std::endl; // // if (Low[i]){ RLow[Low[i].value()] = make_optional(i); } // // if (Low[j]){ RLow[Low[j].value()] = make_optional(j); } // // if (ck){ RLow[Low[*ck].value()] = make_optional(*ck); } // // if (cl){ RLow[Low[*cl].value()] = make_optional(*cl); } // // // for (size_t c = 0; c < nc; ++c){ // positive[c] = R.column_empty(c); // } // for (size_t c = 0; c < nc; ++c){ // Low[c] = R.lowest_nonzero(c); // } // RLow = vector< optional< size_t > >(nc); // for (size_t c = 0; c < nc; ++c){ // if (Low[c]){ // RLow[Low[c].value()] = make_optional(c); // } // } // R.clean(false); // V.clean(false); // // Low[i] = R.lowest_nonzero(i); // // Low[j] = R.lowest_nonzero(j); // // for (size_t c = 0; c < nc; ++c){ // // auto row_entry = std::find_if(Low.begin(), Low.end(), [c](optional< size_t >& le){ // // return(bool(le) && (*le == c)); // // }); // // RLow[c] = (row_entry != Low.end()) ? make_optional(std::distance(Low.begin(), row_entry)) : std::nullopt; // // } // // if (low_i){ // // auto row_entry = std::find_if(Low.begin(), Low.end(), [&low_i](optional< size_t >& le){ // // return(bool(le) && (*le == *low_i)); // // }); // // RLow[Low[i].value()] = make_optional(std::distance(Low.begin(), row_entry)); // // } // // if (low_j){ // // auto row_entry = std::find_if(Low.begin(), Low.end(), [&low_j](optional< size_t >& le){ // // return(bool(le) && (*le == *low_j)); // // }); // // RLow[Low[j].value()] = make_optional(std::distance(Low.begin(), row_entry)); // // } // // // if (!positive[i]){ // // const auto& col_i = *R.columns[i]; // // auto me1 = std::max_element(col_i.begin(), col_i.end(), [&R](auto& e1, auto& e2){ // // return(R.otc[e1.first] < R.otc[e2.first]); // // }); // // Low[i] = R.otc[(*me1).first]; // // } else { // // Low[i] = std::nullopt; // // } // // if (!positive[j]){ // // const auto& col_j = *R.columns[j]; // // auto me2 = std::max_element(col_j.begin(), col_j.end(), [&R](auto& e1, auto& e2){ // // return(R.otc[e1.first] < R.otc[e2.first]); // // }); // // Low[j] = R.otc[(*me2).first]; // // } else { // // Low[j] = std::nullopt; // // } // // Low[i] = positive[i] ? std::nullopt : make_optional(R.cto[R.columns[i]->back().first]); // // Low[j] = positive[j] ? std::nullopt : make_optional(R.cto[R.columns[j]->back().first]); // // // if (low_i){ // // if (Low[i] && Low[i].value() == *low_i){ // // RLow[*low_i] = i; // // } else if (Low[j] && Low[j].value() == *low_i){ // // RLow[*low_i] = j; // // } else { // // RLow[*low_i] = std::nullopt; // // } // // } // // if (low_j){ // // if (Low[i] && Low[i].value() == *low_j){ // // RLow[*low_j] = i; // // } else if (Low[j] && Low[j].value() == *low_j){ // // RLow[*low_j] = j; // // } else { // // RLow[*low_j] = std::nullopt; // // } // // } // // if (low_j){ RLow[Low[j].value()] = make_optional(j); } // // Rcout << line << ": Positive: "; // for (size_t c = 0; c < nc; ++c){ // Rcout << (positive[c] ? 1 : 0) << ","; // } // Rcout << std::endl; // // Rcout << line << ": Low: "; // for (size_t c = 0; c < nc; ++c){ // Rcout << (bool(Low[c]) ? std::to_string(*Low[c]) : std::string("NA")) << std::string(","); // } // Rcout << std::endl; // // Rcout << line << ": Low (reported): "; // for (size_t c = 0; c < nc; ++c){ // auto le = R.lowest_nonzero(c); // Rcout << (bool(le) ? std::to_string(*le) : std::string("NA")) << std::string(","); // } // Rcout << std::endl; // // Rcout << line << ": RLow: "; // for (size_t c = 0; c < nc; ++c){ // Rcout << (bool(RLow[c]) ? std::to_string(*RLow[c]) : std::string("NA")) << std::string(","); // } // Rcout << std::endl; // Rcout << std::endl; // // // Apply user function // f(R, V, status); // line++; // } // }
35.834061
115
0.478187
[ "vector" ]
f15559f82b149e1b64dd0a7af4bd20d69b83665b
454
hpp
C++
src/cpu/interrupts/interrupts.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
src/cpu/interrupts/interrupts.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
src/cpu/interrupts/interrupts.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
#pragma once #include <kstd/types.hpp> #include <cpu/interrupts/idt.hpp> #include <cpu/interrupts/apic.hpp> #include <kstd/vector.hpp> namespace cpu::interrupts { kstd::Vector<IOAPIC>& ioapics(); kstd::Vector<LAPIC>& lapics(); void override_irq_source(u8 irq, u32 gsi, u16 flags); void register_gsi(u32 gsi, bool active_low, bool level_trigger, IDTHandler handler); void register_irq(u8 irq, IDTHandler handler); void eoi(); }
26.705882
88
0.715859
[ "vector" ]
f15e11453e345df4d421feee55b6f49919cdda6d
6,895
hpp
C++
public/bt/core/assets/LoadEvent.hpp
c0de4un/btSDK
fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7
[ "MIT" ]
1
2020-05-20T17:45:47.000Z
2020-05-20T17:45:47.000Z
public/bt/core/assets/LoadEvent.hpp
c0de4un/btSDK
fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7
[ "MIT" ]
null
null
null
public/bt/core/assets/LoadEvent.hpp
c0de4un/btSDK
fbdd6873cc33b5d7af09920f62edf6c1c26cf5f7
[ "MIT" ]
null
null
null
/** * Copyright © 2020 Denis Z. (code4un@yandex.ru) All rights reserved. * Authors: Denis Z. (code4un@yandex.ru) * All rights reserved. * License: see LICENSE.txt * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must display the names 'Denis Zyamaev' and * in the credits of the application, if such credits exist. * The authors of this work must be notified via email (code4un@yandex.ru) in * this case of redistribution. * 3. Neither the name of copyright holders nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef BT_CORE_LOAD_EVENT_HPP #define BT_CORE_LOAD_EVENT_HPP // ----------------------------------------------------------- // =========================================================== // INCLUDES // =========================================================== // Include ecs::Event #ifndef ECS_EVENT_HPP #include "../../ecs/event/Event.hpp" #endif // !ECS_EVENT_HPP // Include bt::vector #ifndef BT_CFG_VECTOR_HPP #include "../../cfg/bt_vector.hpp" #endif // !BT_CFG_VECTOR_HPP // =========================================================== // TYPES // =========================================================== namespace bt { namespace core { // ----------------------------------------------------------- /** * @brief * LoadEvent - allows to notify Assets & their users, * that they can be loaded/restored. * * @version 0.1 **/ class BT_API LoadEvent final : public ecs_Event { // ----------------------------------------------------------- // =========================================================== // META // =========================================================== BT_CLASS // ----------------------------------------------------------- private: // ----------------------------------------------------------- // =========================================================== // FIELDS // =========================================================== /** Flags. **/ bt_vector<bool> mFlags; // =========================================================== // DELETED // =========================================================== LoadEvent(const LoadEvent&) = delete; LoadEvent& operator=(const LoadEvent&) = delete; LoadEvent(LoadEvent&&) = delete; LoadEvent& operator=(LoadEvent&&) = delete; // ----------------------------------------------------------- public: // ----------------------------------------------------------- // =========================================================== // CONSTANTS // =========================================================== /** Flags num. **/ static constexpr const unsigned char ASSETS_FLAGS = 2; /** GPU-Related Assets flag. **/ static constexpr const unsigned char GPU_ASSETS_FLAG = 0; /** Audio-Related Assets flag. **/ static constexpr const unsigned char AUDIO_ASSETS_FLAG = 1; /** Reloading flag. Used to detect, that surface restored (lost of context, GC, device orientation change, etc). **/ const bool mReload; // =========================================================== // CONSTRUCTOR & DESTRUCTOR // =========================================================== /** * @brief * LoadEvent constructor. * * @param pReloading - reloading (restore) flag. 'true', if Rendering Surface restored. * @param pCaller - Event Invoker. Can be null. * @throws - can throw exception. **/ explicit LoadEvent( const bool pReloading, ecs_wptr<ecs_IEventInvoker> pCaller = ecs_sptr<ecs_IEventInvoker>( nullptr ) ); /** * @brief * LoadEvent destructor. * * @throws - can throw exception. **/ virtual ~LoadEvent(); // =========================================================== // GETTERS & SETTERS // =========================================================== /** * @brief * Sets flag. * * @thread_safety - not required. Set only before sending. * @param flagName - Flag Index. * @param flagValue - Flag value. * @throws - no exceptions. **/ void setFlag( const unsigned char flagName, const bool flagValue ) noexcept; /** * @brief * Returns 'true' if this events called for GPU-related users (textures, shaders, etc). * * @thread_safety - not required. * @throws - no exceptions. **/ bool isGPU() const noexcept; /** * @brief * Returns 'true' if called for Audio-assets. * * @thread_safety - not required. * @throws - no exceptions. **/ bool isAudio() const noexcept; // ----------------------------------------------------------- }; /// bt::core::LoadEvent // ----------------------------------------------------------- } /// bt::core } /// bt using bt_LoadEvent = bt::core::LoadEvent; // ----------------------------------------------------------- #endif // !BT_CORE_LOAD_EVENT_HPP
35.541237
134
0.435533
[ "vector" ]
f160f7837541ddd16b2e85bae3e2c09e3fd06c13
2,801
hpp
C++
include/eve/module/core/constant/sqrtsmallestposval.hpp
mshojatalab/eve
9fc1f46e695b05e2e72f7e2083729621e6bdb57e
[ "MIT" ]
null
null
null
include/eve/module/core/constant/sqrtsmallestposval.hpp
mshojatalab/eve
9fc1f46e695b05e2e72f7e2083729621e6bdb57e
[ "MIT" ]
null
null
null
include/eve/module/core/constant/sqrtsmallestposval.hpp
mshojatalab/eve
9fc1f46e695b05e2e72f7e2083729621e6bdb57e
[ "MIT" ]
null
null
null
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/module/core/decorator/roundings.hpp> #include <eve/module/core/regular/sqrt.hpp> #include <eve/module/core/regular/max.hpp> #include <eve/module/core/regular/floor.hpp> #include <eve/module/core/constant/constant.hpp> #include <eve/concept/value.hpp> #include <eve/detail/implementation.hpp> #include <eve/detail/meta.hpp> #include <eve/as.hpp> #include <type_traits> namespace eve { //================================================================================================ //! @addtogroup core //! @{ //! @var sqrtsmallestposval //! //! @brief Callable object computing the greatest value less //! than the square root of the greatest value. //! //! **Required header:** `#include <eve/module/core.hpp>` //! //! | Member | Effect | //! |:-------------|:-----------------------------------------------------------| //! | `operator()` | Computes the sqrtsmallestposval constant | //! //! --- //! //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} //! template < value T > T operator()( as<T> const & t) const noexcept; //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! **Parameters** //! //!`t`: [Type wrapper](@ref eve::as) instance embedding the type of the constant. //! //! **Return value** //! //! the call `eve::sqrtsmallestposval(as<T>())` is the square root of`eve::smallestposval(as<T>())`. //! //! --- //! //! #### Example //! //! @godbolt{doc/core/sqrtsmallestposval.cpp} //! //! @} //================================================================================================ EVE_MAKE_CALLABLE(sqrtsmallestposval_, sqrtsmallestposval); namespace detail { template<typename T> EVE_FORCEINLINE constexpr auto sqrtsmallestposval_(EVE_SUPPORTS(cpu_), eve::as<T> const & = {}) noexcept { using t_t = element_type_t<T>; if constexpr(std::is_same_v<t_t, float>) return Constant<T, 0x20000000U>(); else if constexpr(std::is_same_v<t_t, double>) return Constant<T, 0x2000000000000000ULL>(); else return T(1); } template<typename T, typename D> EVE_FORCEINLINE constexpr auto sqrtsmallestposval_(EVE_SUPPORTS(cpu_), D const &, as<T> const &) noexcept requires(is_one_of<D>(types<upward_type, downward_type>{})) { return sqrtsmallestposval(as<T>()); } } }
33.345238
109
0.48804
[ "object", "vector" ]
f16516b864a936836f8d8dc382ff41db6f552661
4,715
cpp
C++
BuildInput/src/Random.cpp
LilianeRA/RigidRegistration
ec735cbbf3f8816f8950e4cf77b32626a4afdebc
[ "Apache-2.0" ]
null
null
null
BuildInput/src/Random.cpp
LilianeRA/RigidRegistration
ec735cbbf3f8816f8950e4cf77b32626a4afdebc
[ "Apache-2.0" ]
null
null
null
BuildInput/src/Random.cpp
LilianeRA/RigidRegistration
ec735cbbf3f8816f8950e4cf77b32626a4afdebc
[ "Apache-2.0" ]
null
null
null
/************************************************************************************* GCG - GROUP FOR COMPUTER GRAPHICS Universidade Federal de Juiz de Fora Instituto de Ciências Exatas Departamento de Ciência da Computação RANDOM.CPP: functions for random number generation. Marcelo Bernardes Vieira Eder de Almeida Perez **************************************************************************************/ #include "Random.h" #include <random> #define GCG_MERSENNE_MATRIX_A 0x9908b0df // Constant vector a Random::Random() : a_mti(-1), a_last_interval(0), a_R_limit(0), a_mag01{0x0, GCG_MERSENNE_MATRIX_A} { //mag01[0] = 0x0; //mag01[1] = GCG_MERSENNE_MATRIX_A; // mag01[x] = x * MATRIX_A for x=0,1 m_SetSeed(rand()); // A random initial seed is used. Guarantees several instances. } Random::~Random() { } // Sets a new seed to the Mersenne Twister generator void Random::m_SetSeed(unsigned int seed) { // Setting initial seeds to mt[N] using the generator line 25 of table 1 // in [KNUTH 1981, The Art of Computer Programming, vol.2 (2nd. Ed.), pp102] a_mt[0] = seed & 0xffffffff; for(a_mti = 1; a_mti < MERSENNE_N; a_mti++) { a_mt[a_mti] = (69069 * a_mt[a_mti - 1]) & 0xffffffff; } a_last_interval = 0; // Randomize some more for(int i = 0; i < 37; i++) m_BitRandom32(); } int Random::m_IntRandom(int min_val, int max_val) { if(min_val == max_val) return min_val; // Swap if not consistent if(min_val > max_val) std::swap(min_val, max_val); unsigned int interval; // Length of interval unsigned int bran; // Random bits unsigned int iran; // bran / interval unsigned int remainder; // bran % interval interval = (unsigned int) (max_val-min_val + 1); if (interval != a_last_interval) { // Interval length has changed. Must calculate rejection limit // Reject when iran = 2^32 / interval // We can't make 2^32 so we use 2^32-1 and correct afterwards a_R_limit = (unsigned int) 0xffffffff / interval; if((unsigned int) 0xffffffff % interval == interval - 1) a_R_limit++; } do // Rejection loop { bran = m_BitRandom32(); iran = bran / interval; remainder = bran % interval; } while(iran >= a_R_limit); // Number in range return (int) remainder + min_val; } double Random::m_DoubleRandom(double min_val, double max_val) { if(min_val == max_val) return min_val; // Swap if not consistent if(min_val > max_val) std::swap(min_val, max_val); return min_val + (double)m_BitRandom32() * ((double)(max_val-min_val) / ((double)(unsigned int)(-1L) + (double) 1.0)); } float Random::m_FloatRandom(float min_val, float max_val) { if(min_val == max_val) return min_val; // Swap if not consistent if(min_val > max_val) std::swap(min_val, max_val); return min_val + (float)m_BitRandom32() * ((float)(max_val-min_val) / ((float)(unsigned int)(-1L) + (float) 1.0)); } // Generates 32 random bits. unsigned int Random::m_BitRandom32() { #define MERSENNE_M 397 #define MERSENNE_UPPER_MASK 0x80000000 // Most significant w-r bits #define MERSENNE_LOWER_MASK 0x7fffffff // Least significant r bits // Tempering parameters #define MERSENNE_TEMPERING_MASK_B 0x9d2c5680 #define MERSENNE_TEMPERING_MASK_C 0xefc60000 #define MERSENNE_TEMPERING_SHIFT_U(y) (y >> 11) #define MERSENNE_TEMPERING_SHIFT_S(y) (y << 7) #define MERSENNE_TEMPERING_SHIFT_T(y) (y << 15) #define MERSENNE_TEMPERING_SHIFT_L(y) (y >> 18) unsigned int y; if(a_mti >= MERSENNE_N) // Generate N words at one time { int kk; for(kk = 0; kk < (MERSENNE_N - MERSENNE_M); kk++) { y = (a_mt[kk] & MERSENNE_UPPER_MASK) | (a_mt[kk + 1] & MERSENNE_LOWER_MASK); a_mt[kk] = a_mt[kk + MERSENNE_M] ^ (y >> 1) ^ a_mag01[y & 0x1]; } for(; kk < MERSENNE_N - 1; kk++) { y = (a_mt[kk] && MERSENNE_UPPER_MASK) | (a_mt[kk + 1] & MERSENNE_LOWER_MASK); a_mt[kk] = a_mt[kk + (MERSENNE_M - MERSENNE_N)] ^ (y >> 1) ^ a_mag01[y & 0x01]; } y = (a_mt[MERSENNE_N - 1] & MERSENNE_UPPER_MASK) | (a_mt[0] & MERSENNE_LOWER_MASK); a_mt[MERSENNE_N - 1] = a_mt[MERSENNE_M - 1] ^ (y >> 1) ^ a_mag01[y & 0x1]; a_mti = 0; } y = a_mt[a_mti++]; y ^= MERSENNE_TEMPERING_SHIFT_U(y); y ^= MERSENNE_TEMPERING_SHIFT_S(y) & MERSENNE_TEMPERING_MASK_B; y ^= MERSENNE_TEMPERING_SHIFT_T(y) & MERSENNE_TEMPERING_MASK_C; y ^= MERSENNE_TEMPERING_SHIFT_L(y); return y; // For integer generation }
32.07483
122
0.612725
[ "vector" ]
f16958f97c05b3dbeb1592dd51885f6a87bd558a
3,713
cpp
C++
sussybard.cpp
Themaister/sussybard
ba543ad58d605d55fadd58745b2343968ed6be79
[ "MIT" ]
2
2022-01-23T17:27:58.000Z
2022-01-25T05:00:38.000Z
sussybard.cpp
Themaister/sussybard
ba543ad58d605d55fadd58745b2343968ed6be79
[ "MIT" ]
null
null
null
sussybard.cpp
Themaister/sussybard
ba543ad58d605d55fadd58745b2343968ed6be79
[ "MIT" ]
null
null
null
/* Copyright (c) 2022 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <vector> #include "midi_source.hpp" #include "key_sink.hpp" #include "audio_pulse.hpp" // 3 octave range for Bard. constexpr int base_key = 36; // C somewhere on my keyboard. constexpr int num_octaves = 3; constexpr int num_keys = num_octaves * 12 + 1; // High C is also included. static std::vector<uint32_t> initialize_bind_table(const KeySink &key) { std::vector<uint32_t> code_table; code_table.reserve(num_keys); for (int i = 0; i < num_keys; i++) { if (i + 1 == num_keys) code_table.push_back(key.translate_key(',')); else if ('a' + i <= 'z') code_table.push_back(key.translate_key('a' + i)); else if (i > ('z' - 'a')) code_table.push_back(key.translate_key('0' + i - ('z' - 'a' + 1))); } return code_table; } int main(int argc, char **argv) { const char *client = nullptr; if (argc >= 2) client = argv[1]; MIDISource source; if (!source.init(client)) return EXIT_FAILURE; KeySink key; if (!key.init()) return EXIT_FAILURE; Synth synth; Pulse pulse(&synth); if (!pulse.init(48000.0f, 2)) return EXIT_FAILURE; auto code_table = initialize_bind_table(key); pulse.start(); MIDISource::NoteEvent ev = {}; int pressed_note_offset = -1; while (source.wait_next_note_event(ev)) { int node_offset = ev.note - base_key; bool in_range = node_offset >= 0 && node_offset < num_keys; if (in_range) { // Ignore weird double taps. if (ev.pressed && pressed_note_offset == node_offset) continue; if (ev.pressed) synth.post_note_on(ev.note); else synth.post_note_off(ev.note); KeySink::Event key_events[2] = {}; unsigned event_count = 0; bool release_held_key = ev.pressed || pressed_note_offset == node_offset; // There is no polyphony, so release any pressed key before we can press another one. // If we're releasing a key, release only the held key if there's a match. if (release_held_key && pressed_note_offset >= 0) { auto &e = key_events[event_count++]; e.code = code_table[pressed_note_offset]; e.press = false; synth.post_note_off(pressed_note_offset + base_key); pressed_note_offset = -1; } if (ev.pressed) { auto &e = key_events[event_count++]; e.code = code_table[node_offset]; e.press = true; pressed_note_offset = node_offset; } if (event_count) key.dispatch(key_events, event_count); } } if (pressed_note_offset >= 0) { KeySink::Event key_event = {}; key_event.code = code_table[pressed_note_offset]; key.dispatch(&key_event, 1); } pulse.stop(); }
28.128788
88
0.699165
[ "vector" ]
f179d74bd459dd28dffc43ca96d9ac5f021afa86
4,698
cpp
C++
compiler/luci/pass/src/FoldGatherPass.cpp
glistening/ONE-1
cadf3a4da4f4340081862abbd3900af7c4b0e22d
[ "Apache-2.0" ]
null
null
null
compiler/luci/pass/src/FoldGatherPass.cpp
glistening/ONE-1
cadf3a4da4f4340081862abbd3900af7c4b0e22d
[ "Apache-2.0" ]
null
null
null
compiler/luci/pass/src/FoldGatherPass.cpp
glistening/ONE-1
cadf3a4da4f4340081862abbd3900af7c4b0e22d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2022 Samsung Electronics Co., Ltd. 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. */ #include "luci/Pass/FoldGatherPass.h" #include "CircleOptimizerUtils.h" #include <luci/IR/CircleNodes.h> namespace { /** * Fold to const if * * 1. params: const and dtype = S32 or S64 * 2. indices: const and dtype = S32 or S64 * * BEFORE * * [CircleConst] [CircleConst] * | | * +---------[Gather]---------+ * * AFTER * * [CircleConst] * **/ template <loco::DataType InputT, loco::DataType IndexT> bool fold_gather(luci::CircleGather *gather_node) { const auto params = loco::must_cast<luci::CircleConst *>(gather_node->params()); const auto indices = loco::must_cast<luci::CircleConst *>(gather_node->indices()); const auto rank = params->rank(); auto axis = gather_node->axis(); if (axis < 0) { axis += static_cast<int32_t>(rank); } if (axis < 0 or axis >= static_cast<int32_t>(rank)) throw std::runtime_error("Unsupported axis value"); const auto name = gather_node->name(); assert(name.length() > 0); auto constant = gather_node->graph()->nodes()->create<luci::CircleConst>(); constant->dtype(InputT); constant->name(name + "_folded"); constant->rank(rank + indices->rank() - 1); assert(constant->rank() > 0); std::vector<uint32_t> shape; for (uint32_t i = 0; i < rank; ++i) { if (i != static_cast<uint32_t>(axis)) { const auto dim = params->dim(i).value(); shape.push_back(dim); } else { for (uint32_t j = 0; j < indices->rank(); ++j) { const auto dim = indices->dim(j).value(); shape.push_back(dim); } } } uint32_t size = 1; for (uint32_t i = 0; i < shape.size(); ++i) { constant->dim(i).set(shape.at(i)); size *= shape.at(i); } constant->size<InputT>(size); uint32_t outer_size = 1; for (uint32_t i = 0; i < static_cast<uint32_t>(axis); ++i) { outer_size *= params->dim(i).value(); } uint32_t inner_size = 1; for (uint32_t i = axis + 1; i < rank; ++i) { inner_size *= params->dim(i).value(); } uint32_t coord_size = 1; for (uint32_t i = 0; i < indices->rank(); ++i) { coord_size *= indices->dim(i).value(); } const auto axis_size = params->dim(axis).value(); for (uint32_t outer = 0; outer < outer_size; ++outer) { for (uint32_t i = 0; i < coord_size; ++i) { constant->at<InputT>((outer * coord_size + i) * inner_size) = params->at<InputT>((outer * axis_size + indices->at<IndexT>(i)) * inner_size); } } loco::replace(gather_node).with(constant); return true; } bool fold_gather(luci::CircleGather *gather_node) { const auto params = dynamic_cast<luci::CircleConst *>(gather_node->params()); if (not params) return false; const auto indices = dynamic_cast<luci::CircleConst *>(gather_node->indices()); if (not indices) return false; // TODO: support more types if (params->dtype() != loco::DataType::S32 and params->dtype() != loco::DataType::S64) return false; if (indices->dtype() != loco::DataType::S32 and indices->dtype() != loco::DataType::S64) throw std::runtime_error("Unsupported type"); if (params->dtype() == loco::DataType::S64) { if (indices->dtype() == loco::DataType::S64) return fold_gather<loco::DataType::S64, loco::DataType::S64>(gather_node); else return fold_gather<loco::DataType::S64, loco::DataType::S32>(gather_node); } else { if (indices->dtype() == loco::DataType::S64) return fold_gather<loco::DataType::S32, loco::DataType::S64>(gather_node); else return fold_gather<loco::DataType::S32, loco::DataType::S32>(gather_node); } } } // namespace namespace luci { /** * Constant Folding for Gather Op **/ bool FoldGatherPass::run(loco::Graph *g) { bool changed = false; for (auto node : loco::active_nodes(loco::output_nodes(g))) { if (auto gather_node = dynamic_cast<luci::CircleGather *>(node)) { if (fold_gather(gather_node)) changed = true; } } return changed; } } // namespace luci
25.258065
90
0.625798
[ "shape", "vector" ]
f17e7bcd4be9195db7c82e485879e9533f883fa4
1,055
cpp
C++
Engine/Source/Tools/CCBaseTools.cpp
playir/PhoneWarsDemo
088ef2bf0cb445eb290bb4150f88ed0cc8ab6ff5
[ "Apache-2.0" ]
3
2015-03-23T02:52:26.000Z
2016-07-23T19:54:29.000Z
Engine/Source/Tools/CCBaseTools.cpp
patelmanthan777/PhoneWarsDemo
088ef2bf0cb445eb290bb4150f88ed0cc8ab6ff5
[ "Apache-2.0" ]
null
null
null
Engine/Source/Tools/CCBaseTools.cpp
patelmanthan777/PhoneWarsDemo
088ef2bf0cb445eb290bb4150f88ed0cc8ab6ff5
[ "Apache-2.0" ]
2
2017-09-16T05:40:17.000Z
2018-03-20T00:25:35.000Z
/*----------------------------------------------------------- * 2c - Cross Platform 3D Application Framework *----------------------------------------------------------- * Copyright © 2010 – 2011 France Telecom * This software is distributed under the Apache 2.0 license. * http://www.apache.org/licenses/LICENSE-2.0.html *----------------------------------------------------------- * File Name : CCBaseTypes.cpp *----------------------------------------------------------- */ #include "CCDefines.h" #include <assert.h> #ifdef ANDROID #include "CCJNI.h" #endif #ifdef DEBUGON void CCDebugAssert(const bool condition, const char *file, const int line, const char *message) { if( !condition ) { DEBUGLOG( "%s %i \n", file, line ); fflush( stdout ); if( message ) { DEBUGLOG( "ASSERT: %s \n", message ); } // Root call to Java on Android for ease of debugging #ifdef ANDROID CCJNI::Assert( file, line, message ); #endif assert( condition ); } } #endif
25.119048
95
0.474882
[ "3d" ]
f18153b97f51c9d68b449472cedb6260db818651
4,262
hpp
C++
src/KBDDaemon.hpp
aidanharris/Hawck
aab56e85fb7408d9020f6e387b93d9f18d902415
[ "BSD-2-Clause" ]
null
null
null
src/KBDDaemon.hpp
aidanharris/Hawck
aab56e85fb7408d9020f6e387b93d9f18d902415
[ "BSD-2-Clause" ]
null
null
null
src/KBDDaemon.hpp
aidanharris/Hawck
aab56e85fb7408d9020f6e387b93d9f18d902415
[ "BSD-2-Clause" ]
null
null
null
/* ===================================================================================== * Keyboard daemon. * * Copyright (C) 2018 Jonas Møller (no) <jonasmo441@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ===================================================================================== */ #pragma once #include <unordered_map> #include <set> #include <mutex> #include <thread> #include "KBDConnection.hpp" #include "UNIXSocket.hpp" #include "UDevice.hpp" #include "LuaUtils.hpp" #include "Keyboard.hpp" #include "SystemError.hpp" #include "FSWatcher.hpp" extern "C" { #include <fcntl.h> #include <sys/stat.h> } // XXX: DO NOT ENABLE THIS FOR NON-DEBUGGING BUILDS // This will log keypresses to stdout #define DANGER_DANGER_LOG_KEYS 0 class KBDDaemon { using Milliseconds = std::chrono::milliseconds; private: Milliseconds timeout = Milliseconds(1024); std::set<int> passthrough_keys; std::mutex passthrough_keys_mtx; std::string home_path = "/var/lib/hawck-input"; std::unordered_map<std::string, std::string> data_dirs = { {"keys", home_path + "/keys"} }; std::unordered_map<std::string, std::vector<int>*> key_sources; UNIXSocket<KBDAction> kbd_com; UDevice udev; /** All keyboards. */ std::vector<Keyboard *> kbds; std::mutex kbds_mtx; /** Keyboards available for listening. */ std::vector<Keyboard *> available_kbds; std::mutex available_kbds_mtx; /** Keyboards that were removed. */ std::vector<Keyboard *> pulled_kbds; std::mutex pulled_kbds_mtx; /** Watcher for /var/lib/hawck/keys */ FSWatcher keys_fsw; /** Watcher for /dev/input/ hotplug */ FSWatcher input_fsw; public: explicit KBDDaemon(const char *device); KBDDaemon(); ~KBDDaemon(); void initPassthrough(); /** Listen on a new device. * * @param device Full path to the device in /dev/input/ */ void addDevice(const std::string& device); /** * Load passthrough keys from a file at `path`. * * @param path Path to csv file containing a `key_codes` column. */ void loadPassthrough(std::string path); /** * Load passthrough keys from a file system event. * * @param ev File system event to load from. */ void loadPassthrough(FSEvent *ev); /** Unload passthrough keys from file at `path`. * * @param path Path to csv file to remove key codes from. */ void unloadPassthrough(std::string path); /** * Start running the daemon. */ void run(); /** * Check which keyboards have become unavailable/available again. */ void updateAvailableKBDs(); /** Set delay between outputted events in µs * * @param delay Delay in µs. */ void setEventDelay(int delay); /** Set timeout for read() on sockets. */ inline void setSocketTimeout(int time) { timeout = Milliseconds(time); } };
31.57037
88
0.656499
[ "vector" ]
f182cf8249742201ef8d16082ab4caf27bc68d3f
1,095
cpp
C++
buildingTriples2graph copy.cpp
jeswr-university-projects/comp3600-project
e327fd78b4f964de35f0f92d233c083eabfc7095
[ "MIT" ]
null
null
null
buildingTriples2graph copy.cpp
jeswr-university-projects/comp3600-project
e327fd78b4f964de35f0f92d233c083eabfc7095
[ "MIT" ]
null
null
null
buildingTriples2graph copy.cpp
jeswr-university-projects/comp3600-project
e327fd78b4f964de35f0f92d233c083eabfc7095
[ "MIT" ]
null
null
null
#pragma once // #include "graph.h" #include "rdf-types.h" #include <set> #include <cmath> #include "graph-matrix.cpp" #include <vector> using namespace std; string pathTo = "http://architecture#hasPathTo"; GraphMatrix<string> buildingsTriplesToGraph(Triples buildingTriples) { // First we need to determine int noEdges = 0; // TODO: Double check set<string> rooms; Triples pathTriples; for (Triple triple : buildingTriples) { if (triple[1] == pathTo) { rooms.insert(triple[0]); noEdges++; pathTriples.push_back(triple); }; }; // In the true case we consider the // rooms to be dense enough to use // a matrix as the uderlying data structure // rather than linked list // TODO: FIX UP POLYMORPHISM OF DATA STRUCUTURES GraphMatrix<string> buildingGraph = ((2 * noEdges) > pow(rooms.size(), 2)) ? GraphMatrix<string>() : GraphMatrix<string>(); for (Triple triple : pathTriples) { buildingGraph.addEdge(triple[0], triple[2], 1); }; return buildingGraph; };
25.465116
127
0.634703
[ "vector" ]
f185aa4ab9c9282f10a459979eaf9075a7a558ab
7,778
cpp
C++
RequestLib/request.cpp
magiruuvelvet/QAPI-IDE
7634acfd4a46075abefad0a2d6fded263b5d222d
[ "BSD-3-Clause" ]
2
2019-08-16T16:08:00.000Z
2019-11-01T00:47:52.000Z
RequestLib/request.cpp
magiruuvelvet/QAPI-IDE
7634acfd4a46075abefad0a2d6fded263b5d222d
[ "BSD-3-Clause" ]
8
2019-07-03T09:02:51.000Z
2019-07-27T13:01:35.000Z
RequestLib/request.cpp
magiruuvelvet/QAPI-IDE
7634acfd4a46075abefad0a2d6fded263b5d222d
[ "BSD-3-Clause" ]
null
null
null
#include <requestlib/request.hpp> #include <algorithm> #define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_ZLIB_SUPPORT #include <httplib.h> #include <url.h> #include <utils/string.hpp> #include <utils/list.hpp> Request::Request(const std::string &url, RequestMethod method, const std::string &custom_method) : _full_url(url) { // set request method as string this->_method = RequestMethodString(method, custom_method); // don't do anything on empty url if (url.empty()) { return; } // parse url try { this->_url = std::make_shared<Url::Url>(url); } catch (Url::UrlParseException &e) { this->_url = nullptr; // throw custom exception with same name and error message // the url lib is not visible in the other modules of the application // and the public interface to avoid cluttering the global scope throw UrlParseException(e.what()); } // fixup some derps from the url parsing library if (this->_url->scheme().empty()) { // assume http by default for local development this->_url->setScheme("http"); } if (string::compare(this->_url->scheme(), std::string{"http"}, string::case_insensitive_compare) && this->_url->port() == 0) { this->_url->setPort(80); } else if (string::compare(this->_url->scheme(), std::string{"https"}, string::case_insensitive_compare) && this->_url->port() == 0) { this->_url->setPort(443); } if (this->_url->path().empty()) { this->_url->setPath("/"); } } Request::Request(const std::string &url, const std::string &method) : Request(url, RequestMethod::CUSTOM, method) { } Request::Request(const std::string &url, const std::string &method, const HeaderMap &headers, const std::string &data, std::uint16_t current_redirect_count, std::uint16_t max_redirect_attempts) : Request(url, method) { // this is a private constructor to recursively follow redirects this->_followRedirects = true; this->_redirect_count = current_redirect_count; this->_max_redirect_attempts = max_redirect_attempts; // transfer headers and body this->_headers = headers; this->_data = data; } Request::~Request() { } const std::string Request::url() const { return this->_url ? this->_url->str() : ""; } void Request::verifyCertificate(bool enabled) { this->_verifyCertificate = enabled; } void Request::followRedirects(bool enabled) { this->_followRedirects = enabled; } void Request::setMaxRedirectAttempts(std::uint16_t attempts) { this->_max_redirect_attempts = attempts; } void Request::setRequestBody(const std::string &data) { this->_data = data; } void Request::appendToRequestBody(const std::string &data) { this->_data.append(data); } void Request::setHeader(const std::string &header, const std::string &value) { this->_headers.insert(std::pair{header, value}); } bool Request::hasHeader(const std::string &header) const { return list::strcontains_key(this->_headers, header, string::case_insensitive_compare); } const std::list<std::string> Request::getHeaderValues(const std::string &header) const { if (this->hasHeader(header)) { return list::mm_values(this->_headers, header, string::case_insensitive_compare); } return {}; } const std::string Request::getHeaderValue(const std::string &header) const { const auto res = this->getHeaderValues(header); if (!res.empty()) { return res.front(); } return {}; } void Request::removeHeader(const std::string &header) { if (this->hasHeader(header)) { this->_headers.erase(header); } } const Response Request::performRequest() { // return invalid response on empty url if (this->_full_url.empty()) { return {}; } struct ClientWrapper { ClientWrapper(const Url::Url *url, bool verifyCertificate) : url(url), verifyCertificate(verifyCertificate) { } // wrapper around Client and SSLClient to support both at the same time bool send(httplib::Request &req, httplib::Response &res) { if (string::compare(this->url->scheme(), std::string{"https"}, string::case_insensitive_compare)) { httplib::SSLClient client(this->url->host().c_str(), this->url->port()); client.enable_server_certificate_verification(this->verifyCertificate); return client.send(req, res); } else { httplib::Client client(this->url->host().c_str(), this->url->port()); return client.send(req, res); } } private: const Url::Url *url; bool verifyCertificate = false; }; // create http client instance with parsed URL ClientWrapper c(this->_url.get(), this->_verifyCertificate); // compose http request httplib::Request req; // make headers for httplib for (auto&& h : this->_headers) { req.set_header(h.first.c_str(), h.second.c_str()); } // set http request method req.method = this->_method; // set http request path req.path = this->_url->path(); // set request body req.body = this->_data; const auto res = std::make_shared<httplib::Response>(); if (c.send(req, *res)) { // check if to follow redirects if (this->_followRedirects) { if (res->status >= 301 && res->status <= 303) { std::string new_url; if (res->has_header("Location")) { const auto location = res->get_header_value("Location"); // location header is empty or doesn't exist if (location.empty()) { throw InvalidRedirect("got redirect status, but no location header"); } if (location.rfind("http://", 0) == 0 || location.rfind("https://", 0) == 0) { // new url becomes absolute new_url = location; } else { // set path of current url auto tmp_url = *this->_url.get(); tmp_url.setPath(location); new_url = tmp_url.str(); } } // check redirect count if (this->_redirect_count >= this->_max_redirect_attempts) { throw TooManyRedirects("reached maximum redirect attempts"); } // increase redirect attempts this->_redirect_count++; // recursively perform requests until the result is no longer 3xx (redirect) // or too many attempts where performed return Request(new_url, this->_method, this->_headers, this->_data, this->_redirect_count, this->_max_redirect_attempts) .performRequest(); } } // create response object Response response; response.setSuccess(true); response.setStatus(res->status); HeaderMap headers; for (auto&& h : res->headers) { headers.insert(std::pair{h.first, h.second}); } response.setHeaders(headers); response.setBody(res->body); return response; } // create invalid empty response return Response(); }
27.58156
134
0.577012
[ "object" ]
f185aa4d0be715435384c430dfe69f68e9e76cd0
7,557
hpp
C++
target-selector/include/target_selector/target_selector.hpp
codeplaysoftware/sycl-info
b47d498ee2d6b77ec21972de5882e8e12efecd6c
[ "BSL-1.0" ]
9
2019-11-19T20:48:11.000Z
2021-09-30T13:26:47.000Z
target-selector/include/target_selector/target_selector.hpp
codeplaysoftware/sycl-info
b47d498ee2d6b77ec21972de5882e8e12efecd6c
[ "BSL-1.0" ]
null
null
null
target-selector/include/target_selector/target_selector.hpp
codeplaysoftware/sycl-info
b47d498ee2d6b77ec21972de5882e8e12efecd6c
[ "BSL-1.0" ]
2
2019-11-18T18:09:21.000Z
2020-01-24T11:52:17.000Z
//////////////////////////////////////////////////////////////////////////////// // target_selector.h // // Copyright 2019 Codeplay Software, Ltd. // // 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. // //////////////////////////////////////////////////////////////////////////////// #ifndef UTIL_DEVICE_SELECTOR_H #define UTIL_DEVICE_SELECTOR_H #include "target_selector/config.hpp" #include "color_scope.hpp" #include <CL/opencl.h> #include <sstream> #include <stdexcept> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace target_selector { /** @brief Exception thrown when there is an internal error in sycl_info */ struct sycl_info_error : public std::runtime_error { sycl_info_error(std::string message) : std::runtime_error(message) {} }; /** * @brief Gets the value of the an environment variable. * * Uses std::getenv as a cross-platform way for retrieving environment * variables: https://en.cppreference.com/w/cpp/utility/program/getenv. */ TARGET_SELECTOR_EXPORT std::string getenv_variable(const char* identifier); /**get_target_from_environment_var * @brief Returns the value of the environment variable SYCL_VENDOR_PATHS in an * std::string if it is set. * @return target String specifying the value of the environment variable * SYCL_VENDOR_PATHS */ TARGET_SELECTOR_EXPORT std::string get_target_from_environment_var(); /** parse_target. * @brief Parses the target, either from the environment variable or via * command line arg. vendor and deviceType parameters are set accordingly. * * The SYCL_TARGET variable is interpreted as platform[:deviceType], * whereas platform is the name of the platform vendor (e.g amd, intel) * and deviceType is the OpenCL type of device (cpu, gpu, accel). * No errors are reported at this stage if the vendor and/or deviceType are * not valid, hence, the strings parsed from the environment variable may be * reused. * @param target String specifying the target to be processed. * @param vendor String returning the vendor given by the environment variable. * @param deviceType String returning the type of the device given by the * environment variable. */ TARGET_SELECTOR_EXPORT void parse_target(const std::string& target, std::string& vendor, std::string& deviceType); /** is_target_any. * @brief Checks whether the requested target can be any target * @param target String specifying the target to be processed. * @return True if target is empty string, "any", or "*" */ TARGET_SELECTOR_EXPORT bool is_target_any(const std::string& target); /** find_Devices. * @brief Finds all devices matching the given vendor and device type and * returns them as a pair of (platform_id, device_id) in a vector. * whereas platform is the name of the platform vendor (e.g amd, intel) * and deviceType is the OpenCL type of device (cpu, gpu, accel). * @param devicesFound List of devices found by the routine * @param reqVendor Required name of the vendor to pick devices from * @param reqDeviceType Required type of device to select * @param all Whether all device should be searched, including non-SPIR ones * @param usedVendorAsType Set to true if reqVendor was used for the device * type * @param platforms, the platforms to search for */ TARGET_SELECTOR_EXPORT void find_devices( std::vector<std::pair<cl_platform_id, cl_device_id>>& devicesFound, const std::string& reqVendor, const std::string& reqDeviceType, bool& usedVendorAsType, const std::unordered_map<std::string, std::string>& platforms, bool all = false); /*! @brief Checks whether the device supports SPIR. @param device The device to get the info from @return Whether the device supports SPIR or not. */ TARGET_SELECTOR_EXPORT bool has_spir(cl_device_id device) noexcept; /* *@brief Helper function boilerplate to generate a target_selector warning */ TARGET_SELECTOR_EXPORT void target_selector_warning(const std::string& message); /* *@brief Helper function boilerplate to throw a target_selector error */ TARGET_SELECTOR_EXPORT void target_selector_throw_error( const std::string& message); /* *@brief Helper function boilerplate that calls an OpenCL function and generate a warning *upon failure *@param a functor and a string message *@return the error code for the OpenCL function called and generate a warning with a the message passed if the call failed */ template <typename Callback> ::cl_int target_selector_warn_on_cl_error(Callback&& functor, const std::string& message) { ::cl_int err = functor(); if (err != CL_SUCCESS) { std::stringstream stream; stream << "OpenCL error " << err << ": " << message; target_selector_warning(message); } return err; } /* *@brief Helper function boilerplate that calls an OpenCL function and throw an *error upon failure *@param a functor and a string message *@return the error code for the OpenCL function called or throw upon failure */ template <typename Callback> ::cl_int target_selector_throw_on_cl_error(Callback&& functor, const std::string& message) { ::cl_int err = functor(); if (err != CL_SUCCESS) { std::stringstream stream; stream << "OpenCL error " << err << ": " << message; target_selector_warning(stream.str()); throw sycl_info_error(stream.str()); } return err; } /*! @brief Trips the end of a string by removing whitespaces, '\0' and */ TARGET_SELECTOR_EXPORT std::string trim_end(std::string str); /*! @brief Boilerplate template that queries an OpenCL function @tparam IdType: the type of the id For example: cl_platform_id, cl_device_id, etc @tparam InfoType: the type of the information retrieved For example: cl_platform_info, cl_device_info @tparam Function: OpenCL function to query For example clGetPlatormInfo, clGetDeviceInfo. @param id: the unique identifier to query the OpenCL function Function @param attr: the information to query For example: CL_DEVICE_NAME @return The information specified with attr as a std::string. The error string otherwise */ template <typename IdType, typename InfoType, typename Function> std::string get_info_from_opencl(IdType id, InfoType attr, Function fun) noexcept { size_t size = 0; auto result = target_selector_warn_on_cl_error( [&id, &attr, &size, &fun]() { return fun(id, attr, 0, nullptr, &size); }, "Failed to retrieve the size."); if (result != CL_SUCCESS) { return "(ERROR)"; } auto idString = std::string(size, ' '); result = target_selector_warn_on_cl_error( [&]() { return fun(id, attr, size, &idString[0], nullptr); }, "Failed to retrieve the name"); if (result != CL_SUCCESS) { return "(ERROR)"; } return trim_end(std::move(idString)); } } // namespace target_selector #endif // UTIL_DEVICE_SELECTOR_H
36.684466
80
0.704645
[ "vector" ]
f185ed78152df68bd894d555b05c07e57042a2dd
4,136
cxx
C++
modules/core/tests/basicStatismoTest.cxx
tom-albrecht/statismo
e7825afadb1accc4902d911d5f00a8c4bd383a31
[ "BSD-3-Clause" ]
null
null
null
modules/core/tests/basicStatismoTest.cxx
tom-albrecht/statismo
e7825afadb1accc4902d911d5f00a8c4bd383a31
[ "BSD-3-Clause" ]
null
null
null
modules/core/tests/basicStatismoTest.cxx
tom-albrecht/statismo
e7825afadb1accc4902d911d5f00a8c4bd383a31
[ "BSD-3-Clause" ]
null
null
null
/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS addINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "TrivialVectorialRepresenter.h" #include "StatisticalModel.h" #include "PCAModelBuilder.h" #include "DataManager.h" #include <boost/scoped_ptr.hpp> typedef statismo::TrivialVectorialRepresenter RepresenterType; /** * This basic test case, covers the model creation pipeline and tests whether a model can be successfully * saved to disk. If the test runs correctly, it merely means that statismo has been setup correclty and hdf5 * works. * * Real unit tests that test the functionality of statismo are provided in the statismoTests directory (these tests * require VTK to be installed and the statismo python wrapping to be working). */ int main(int argc, char* argv[]) { typedef statismo::PCAModelBuilder<statismo::VectorType> ModelBuilderType; typedef statismo::StatisticalModel<statismo::VectorType> StatisticalModelType; typedef statismo::DataManager<statismo::VectorType> DataManagerType; try { const unsigned Dim = 3; boost::scoped_ptr<RepresenterType> representer(RepresenterType::Create(Dim)); boost::scoped_ptr<DataManagerType> dataManager(DataManagerType::Create(representer.get())); // we create three simple datasets statismo::VectorType dataset1(Dim), dataset2(Dim), dataset3(Dim); dataset1 << 1,0,0; dataset2 << 0,2,0; dataset3 << 0,0,4; dataManager->AddDataset(dataset1, "dataset1"); dataManager->AddDataset(dataset2, "dataset1"); dataManager->AddDataset(dataset3, "dataset1"); boost::scoped_ptr<ModelBuilderType> pcaModelBuilder(ModelBuilderType::Create()); boost::scoped_ptr<StatisticalModelType> model(pcaModelBuilder->BuildNewModel(dataManager->GetData(), 0.01)); // As we have added 3 linearly independent samples, we get 2 principal components. if (model->GetNumberOfPrincipalComponents() != 2) { return EXIT_FAILURE; } model->Save("test.h5"); RepresenterType* newRepresenter = RepresenterType::Create(); boost::scoped_ptr<StatisticalModelType> loadedModel(StatisticalModelType::Load(newRepresenter, "test.h5")); if (model->GetNumberOfPrincipalComponents() != loadedModel->GetNumberOfPrincipalComponents()) { return EXIT_FAILURE; } } catch (statismo::StatisticalModelException& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
39.390476
116
0.731383
[ "model" ]
f187f8f1bd46b75ddcbbc8796326b2f603cf3f38
1,573
cpp
C++
Cplus/CreateTargetArrayintheGivenOrder.cpp
Jum1023/leetcode
d8248aa84452cb1ea768d9b05ecd72a6746c0016
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/CreateTargetArrayintheGivenOrder.cpp
Jum1023/leetcode
d8248aa84452cb1ea768d9b05ecd72a6746c0016
[ "MIT" ]
null
null
null
Cplus/CreateTargetArrayintheGivenOrder.cpp
Jum1023/leetcode
d8248aa84452cb1ea768d9b05ecd72a6746c0016
[ "MIT" ]
null
null
null
#include <set> #include <vector> using namespace std; class Solution { public: vector<int> createTargetArray(vector<int> &nums, vector<int> &index) { int N = index.size(); // this O(n^2) part can be optimized using BIT to O(nlogn) // for (int i = 0; i < indexSize; ++i) // { // for (int j = i + 1; j < indexSize; ++j) // { // if (index[i] >= index[j]) // ++index[i]; // } // } vector<pair<int, int>> v, dup(N); //{new val,origin index} for (int i = 0; i < N; ++i) v.push_back({index[i], i}); divide(v, dup, 0, N); vector<int> res(N); for (int i = 0; i < N; ++i) res[v[i].first] = nums[v[i].second]; return res; } //divide and conquer void merge(vector<pair<int, int>> &arr, vector<pair<int, int>> &dup, int first, int mid, int last) { for (int i = first, j = mid, d = 0; i < mid || j < last;) { if (i == mid) dup[d++] = arr[j++]; else if (j == last) dup[d++] = arr[i++]; else dup[d++] = (arr[i] > arr[j]) ? arr[j++] : arr[i++]; } for (int i = first, j = 0; i < last; ++i, ++j) arr[i] = dup[j]; } void divide(vector<pair<int, int>> &arr, vector<pair<int, int>> &dup, int first, int last) { if (last - first <= 1) return; int mid = first + (last - first) / 2; divide(arr, dup, first, mid); divide(arr, dup, mid, last); for (int i = first, j = mid, count = 0; i < mid; ++i) { for (; j < last && arr[i].first + count >= arr[j].first; ++j) ++count; arr[i].first += count; } merge(arr, dup, first, mid, last); } /********end of divide and conquer********/ };
25.370968
99
0.520025
[ "vector" ]
f188d1ae64d78b14ee161350c07edce26f306d71
1,099
cpp
C++
toolbox/test/IteratorRecorder.cpp
campx/toolbox
c19ac77981360345acf2ca53479583042e4f018c
[ "Apache-2.0" ]
null
null
null
toolbox/test/IteratorRecorder.cpp
campx/toolbox
c19ac77981360345acf2ca53479583042e4f018c
[ "Apache-2.0" ]
null
null
null
toolbox/test/IteratorRecorder.cpp
campx/toolbox
c19ac77981360345acf2ca53479583042e4f018c
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include <toolbox/Iterator.h> #include <toolbox/IteratorRecorder.h> TEST(Toolbox, IteratorRecorder) { using Input = std::vector<int>; using Recorder = toolbox::IteratorRecorder<Input::const_iterator>; auto input = Input{1, 2, 3, 4, 5, 6, 7, 8, 9}; auto recorder = Recorder{input.cbegin()}; EXPECT_EQ(input.cbegin(), recorder); EXPECT_EQ(1, *recorder); EXPECT_EQ(1, *recorder); EXPECT_EQ(2, *(++recorder)); EXPECT_EQ(1, *(--recorder)); EXPECT_EQ(1, *recorder); auto begin = Recorder(input.cbegin()); auto end = Recorder(input.cend()); auto last = toolbox::end(begin, end); EXPECT_EQ(end, end); EXPECT_EQ(input.cend(), last); EXPECT_EQ(input.cend(), end); last = toolbox::end(begin, end); EXPECT_EQ(last, toolbox::end(begin, end)); auto reverse = Input{}; auto rbegin = std::make_reverse_iterator(toolbox::end(begin, end)); auto rend = std::make_reverse_iterator(begin); std::copy(rbegin, rend, std::back_inserter(reverse)); EXPECT_EQ((Input{9, 8, 7, 6, 5, 4, 3, 2, 1}), reverse); }
35.451613
71
0.647862
[ "vector" ]
f195722c328b8a6eb2ad67fe176432114933c508
14,353
hpp
C++
compiler/src/ast/stmt/ast_stmts.hpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
15
2017-08-15T20:46:44.000Z
2021-12-15T02:51:13.000Z
compiler/src/ast/stmt/ast_stmts.hpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
null
null
null
compiler/src/ast/stmt/ast_stmts.hpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
1
2017-09-28T14:48:15.000Z
2017-09-28T14:48:15.000Z
#pragma once #include "ast_stmt_node.hpp" #include "ast/ast_fielddef_node.hpp" #include "ast/expr/ast_assignee_node.hpp" #include "ast/expr/ast_exprs.hpp" /** Local field declaration */ class TxFieldStmtNode : public TxStatementNode { TxDeclarationFlags declFlags = TXD_NONE; protected: void set_exp_error_stmt() override { this->declFlags = TXD_EXPERROR; } void stmt_declaration_pass() override; void verification_pass() const override; public: TxLocalFieldDefNode* fieldDef; TxFieldStmtNode( const TxLocation& ploc, TxLocalFieldDefNode* fieldDef ) : TxStatementNode( ploc ), fieldDef( fieldDef ) { } TxFieldStmtNode* make_ast_copy() const override { return new TxFieldStmtNode( this->ploc, this->fieldDef->make_ast_copy() ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->fieldDef->visit_ast( visitor, cursor, "fielddef", aux ); } }; /** Local type declaration */ class TxTypeStmtNode : public TxStatementNode { protected: void set_exp_error_stmt() override { this->typeDecl->declFlags |= TXD_EXPERROR; } public: TxTypeDeclNode* const typeDecl; TxTypeStmtNode( const TxLocation& ploc, TxTypeDeclNode* typeDecl ) : TxStatementNode( ploc ), typeDecl( typeDecl ) { } TxTypeStmtNode( const TxLocation& ploc, TxIdentifierNode* typeName, const std::vector<TxDeclarationNode*>* typeParamDecls, TxTypeCreatingNode* typeCreatingNode, bool interfaceKW = false, bool mutableType = false ) : TxTypeStmtNode( ploc, new TxTypeDeclNode( ploc, TXD_NONE, typeName, typeParamDecls, typeCreatingNode, interfaceKW, mutableType ) ) { } TxTypeStmtNode* make_ast_copy() const override { return new TxTypeStmtNode( this->ploc, this->typeDecl->make_ast_copy() ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->typeDecl->visit_ast( visitor, cursor, "typedecl", aux ); } }; /** A statement that executes an expression. */ class TxExprStmtNode : public TxStatementNode { public: TxExpressionNode* expr; TxExprStmtNode( const TxLocation& ploc, TxExpressionNode* expr ) : TxStatementNode( ploc ), expr( expr ) { } explicit TxExprStmtNode( TxExpressionNode* expr ) : TxExprStmtNode( expr->ploc, expr ) { } TxExprStmtNode* make_ast_copy() const override { return new TxExprStmtNode( this->ploc, this->expr->make_ast_copy() ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->expr->visit_ast( visitor, cursor, "expr", aux ); } }; /* Executes a function call without assigning its return value, if any. */ class TxCallStmtNode : public TxExprStmtNode { public: TxCallStmtNode( const TxLocation& ploc, TxFunctionCallNode* call ) : TxExprStmtNode( ploc, call ) { } TxCallStmtNode* make_ast_copy() const override { return new TxCallStmtNode( this->ploc, static_cast<TxFunctionCallNode*>( this->expr )->make_ast_copy() ); } }; class TxSelfSuperFieldsStmtNode : public TxStatementNode { TxLocalFieldDefNode* selfRefNode; TxLocalFieldDefNode* superRefNode; protected: void stmt_declaration_pass() override; public: explicit TxSelfSuperFieldsStmtNode( const TxLocation& ploc ); TxSelfSuperFieldsStmtNode* make_ast_copy() const override { return new TxSelfSuperFieldsStmtNode( this->ploc ); } /** Returns the current type (Self) */ TxQualType resolve_type( TxTypeResLevel typeResLevel ) { return selfRefNode->resolve_type( typeResLevel )->target_type(); } /** Returns the current type (Self) */ TxQualType qtype() const { return selfRefNode->qtype()->target_type(); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->selfRefNode->visit_ast( visitor, cursor, "selfref", aux ); this->superRefNode->visit_ast( visitor, cursor, "superref", aux ); } }; class TxMemberInitNode : public TxStatementNode { TxIdentifierNode* identifier; const std::vector<TxExpressionNode*>* argsExprList; TxFunctionCallNode* constructorCallExpr; public: TxMemberInitNode( const TxLocation& ploc, TxIdentifierNode* identifier, const std::vector<TxExpressionNode*>* argsExprList ); TxMemberInitNode* make_ast_copy() const override { return new TxMemberInitNode( this->ploc, this->identifier->make_ast_copy(), make_node_vec_copy( this->argsExprList ) ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override; const TxIdentifierNode* get_identifier() const { return this->identifier; } [[maybe_unused]] const std::vector<TxExpressionNode*>* get_args_expr_list() const { return this->argsExprList; } const std::string& get_descriptor() const override { return this->identifier->get_descriptor(); } }; /* Represents the #init ... ; / self() special initialization statement within a constructor. */ class TxInitStmtNode : public TxStatementNode { TxSelfSuperFieldsStmtNode* selfSuperStmt; std::vector<TxMemberInitNode*>* initClauseList; protected: void stmt_declaration_pass() override; void resolution_pass() override; void verification_pass() const override; public: TxInitStmtNode( const TxLocation& ploc, std::vector<TxMemberInitNode*>* initClauseList ); /** The #self( ... ); short-hand */ TxInitStmtNode( const TxLocation& ploc, std::vector<TxExpressionNode*>* argsExprList ); /** The #init; short-hand */ explicit TxInitStmtNode( const TxLocation& ploc ); TxInitStmtNode* make_ast_copy() const override { return new TxInitStmtNode( this->ploc, make_node_vec_copy( this->initClauseList ) ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->selfSuperStmt->visit_ast( visitor, cursor, "self", aux ); for ( auto initClause : *this->initClauseList ) initClause->visit_ast( visitor, cursor, "init-clause", aux ); } }; class TxTerminalStmtNode : public TxStatementNode { protected: explicit TxTerminalStmtNode( const TxLocation& ploc ) : TxStatementNode( ploc ) { } bool ends_with_terminal_stmt() const final { return true; } }; class TxReturnStmtNode : public TxTerminalStmtNode { protected: void resolution_pass() override; public: TxMaybeConversionNode* expr; explicit TxReturnStmtNode( const TxLocation& ploc ) : TxTerminalStmtNode( ploc ), expr() { } TxReturnStmtNode( const TxLocation& ploc, TxExpressionNode* expr ) : TxTerminalStmtNode( ploc ), expr( new TxMaybeConversionNode( expr ) ) { } TxReturnStmtNode* make_ast_copy() const override { return new TxReturnStmtNode( this->ploc, this->expr->originalExpr->make_ast_copy() ); } bool ends_with_return_stmt() const override { return true; } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { if (this->expr) this->expr->visit_ast( visitor, cursor, "value", aux ); } }; class TxBreakStmtNode : public TxTerminalStmtNode { public: explicit TxBreakStmtNode( const TxLocation& ploc ) : TxTerminalStmtNode( ploc ) { } TxBreakStmtNode* make_ast_copy() const override { return new TxBreakStmtNode( this->ploc ); } bool may_end_with_non_return_stmt() const override { return true; } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { } }; class TxContinueStmtNode : public TxTerminalStmtNode { public: explicit TxContinueStmtNode( const TxLocation& ploc ) : TxTerminalStmtNode( ploc ) { } TxContinueStmtNode* make_ast_copy() const override { return new TxContinueStmtNode( this->ploc ); } bool may_end_with_non_return_stmt() const override { return true; } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { } }; class TxSuiteNode : public TxStatementNode { protected: void stmt_declaration_pass() override; void verification_pass() const override { TxStatementNode* prev_stmt = nullptr; for ( auto stmt : *this->suite ) { if ( prev_stmt && prev_stmt->ends_with_terminal_stmt() ) CERROR( stmt, "This statement is unreachable." ); prev_stmt = stmt; } } public: std::vector<TxStatementNode*>* suite; TxSuiteNode( const TxLocation& ploc, std::vector<TxStatementNode*>* suite ) : TxStatementNode( ploc ), suite( suite ) { if (suite->size() > 1) { // inject predecessor links TxStatementNode* pred = suite->front(); for ( auto stmtI = std::next( suite->begin() ); stmtI != suite->end(); stmtI++ ) { (*stmtI)->predecessor = pred; pred = (*stmtI); } } } explicit TxSuiteNode( const TxLocation& ploc ) : TxSuiteNode( ploc, new std::vector<TxStatementNode*>() ) { } TxSuiteNode* make_ast_copy() const override { return new TxSuiteNode( this->ploc, make_node_vec_copy( this->suite ) ); } bool may_end_with_non_return_stmt() const override { for ( auto stmt : *this->suite ) if ( stmt->may_end_with_non_return_stmt() ) return true; return false; } bool ends_with_terminal_stmt() const override { return ( !this->suite->empty() && this->suite->back()->ends_with_terminal_stmt() ); } bool ends_with_return_stmt() const override { if ( this->suite->empty() ) return false; for ( auto stmt : *this->suite ) { if ( stmt->may_end_with_non_return_stmt() ) return false; } return this->suite->back()->ends_with_return_stmt(); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { for ( auto stmt : *this->suite ) stmt->visit_ast( visitor, cursor, "stmt", aux ); } }; class TxAssignStmtNode : public TxStatementNode { protected: void resolution_pass() override; void verification_pass() const override; public: TxAssigneeNode* lvalue; TxMaybeConversionNode* rvalue; TxAssignStmtNode( const TxLocation& ploc, TxAssigneeNode* lvalue, TxExpressionNode* rvalue ) : TxStatementNode( ploc ), lvalue( lvalue ), rvalue( new TxMaybeConversionNode( rvalue ) ) { } TxAssignStmtNode* make_ast_copy() const override { return new TxAssignStmtNode( this->ploc, this->lvalue->make_ast_copy(), this->rvalue->originalExpr->make_ast_copy() ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override; void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->lvalue->visit_ast( visitor, cursor, "lvalue", aux ); this->rvalue->visit_ast( visitor, cursor, "rvalue", aux ); } static void code_gen_array_copy( const TxNode* origin, LlvmGenerationContext& context, GenScope* scope, const TxActualType* lvalType, llvm::Value* lvalTypeIdV, llvm::Value* lvalArrayPtrV, llvm::Value* rvalArrayPtrV ); }; class TxExpErrStmtNode : public TxStatementNode { ExpectedErrorClause* expError; protected: void stmt_declaration_pass() override; public: TxStatementNode* body; TxExpErrStmtNode( const TxLocation& ploc, ExpectedErrorClause* expError, TxStatementNode* body ) : TxStatementNode( ploc ), expError( expError ), body( body ) { if ( dynamic_cast<const TxExpErrStmtNode*>( body ) ) CERROR( this, "Can't nest Expected Error constructs in a statement" ); body->set_exp_error_stmt(); } TxExpErrStmtNode* make_ast_copy() const override { return new TxExpErrStmtNode( this->ploc, new ExpectedErrorClause(), this->body->make_ast_copy() ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override { } void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { this->body->visit_ast( visitor, cursor, "stmt", aux ); } }; class TxNoOpStmtNode : public TxStatementNode { public: explicit TxNoOpStmtNode( const TxLocation& ploc ) : TxStatementNode( ploc ) { } TxNoOpStmtNode* make_ast_copy() const override { return new TxNoOpStmtNode( this->ploc ); } void code_gen( LlvmGenerationContext& context, GenScope* scope ) const override { } void visit_descendants( const AstVisitor& visitor, const AstCursor& cursor, const std::string& role, void* aux ) override { } };
34.337321
137
0.678186
[ "vector" ]
1afb54e9d2faf7f413491432b40245cf31bce911
12,378
cpp
C++
simulation/traffic_simulator/test/src/traffic_lights/test_traffic_light.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
45
2021-04-12T22:43:25.000Z
2022-02-27T23:57:53.000Z
simulation/traffic_simulator/test/src/traffic_lights/test_traffic_light.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
140
2021-04-13T04:28:19.000Z
2022-03-30T12:44:32.000Z
simulation/traffic_simulator/test/src/traffic_lights/test_traffic_light.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
13
2021-05-22T02:24:49.000Z
2022-03-25T05:16:31.000Z
// Copyright 2015-2020 Tier IV, 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. #include <gtest/gtest.h> #include <regex> #include <scenario_simulator_exception/exception.hpp> #include <traffic_simulator/traffic_lights/traffic_light.hpp> #include "../expect_eq_macros.hpp" geometry_msgs::msg::Point getPoint(double val) { geometry_msgs::msg::Point p; p.x = val; p.y = val; p.z = val; return p; } TEST(TrafficLights, getPositionError) { traffic_simulator::TrafficLight light(0); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::NONE), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::GREEN), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::YELLOW), common::SemanticError); EXPECT_THROW(light.getPosition(traffic_simulator::TrafficLightColor::RED), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::NONE), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::LEFT), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::RIGHT), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::STRAIGHT), common::SemanticError); EXPECT_EQ(light.id, static_cast<std::int64_t>(0)); } TEST(TrafficLights, getColorPosition) { std::unordered_map<traffic_simulator::TrafficLightColor, geometry_msgs::msg::Point> color_positions; color_positions[traffic_simulator::TrafficLightColor::GREEN] = getPoint(0); color_positions[traffic_simulator::TrafficLightColor::YELLOW] = getPoint(1); color_positions[traffic_simulator::TrafficLightColor::RED] = getPoint(2); traffic_simulator::TrafficLight light(0, color_positions); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::NONE), common::SemanticError); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::GREEN), getPoint(0)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::YELLOW), getPoint(1)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::RED), getPoint(2)); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::NONE), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::LEFT), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::RIGHT), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::STRAIGHT), common::SemanticError); EXPECT_EQ(light.id, static_cast<std::int64_t>(0)); } TEST(TrafficLights, getArrowPosition) { std::unordered_map<traffic_simulator::TrafficLightArrow, geometry_msgs::msg::Point> arrow_positions; arrow_positions[traffic_simulator::TrafficLightArrow::STRAIGHT] = getPoint(0); arrow_positions[traffic_simulator::TrafficLightArrow::LEFT] = getPoint(1); arrow_positions[traffic_simulator::TrafficLightArrow::RIGHT] = getPoint(2); traffic_simulator::TrafficLight light(1, {}, arrow_positions); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::NONE), common::SemanticError); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::STRAIGHT), getPoint(0)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::LEFT), getPoint(1)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::RIGHT), getPoint(2)); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::NONE), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::GREEN), common::SemanticError); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::YELLOW), common::SemanticError); EXPECT_THROW(light.getPosition(traffic_simulator::TrafficLightColor::RED), common::SemanticError); EXPECT_EQ(light.id, static_cast<std::int64_t>(1)); } TEST(TrafficLights, getColorAndArrowPosition) { std::unordered_map<traffic_simulator::TrafficLightColor, geometry_msgs::msg::Point> color_positions; color_positions[traffic_simulator::TrafficLightColor::GREEN] = getPoint(0); color_positions[traffic_simulator::TrafficLightColor::YELLOW] = getPoint(1); color_positions[traffic_simulator::TrafficLightColor::RED] = getPoint(2); std::unordered_map<traffic_simulator::TrafficLightArrow, geometry_msgs::msg::Point> arrow_positions; arrow_positions[traffic_simulator::TrafficLightArrow::STRAIGHT] = getPoint(3); arrow_positions[traffic_simulator::TrafficLightArrow::LEFT] = getPoint(4); arrow_positions[traffic_simulator::TrafficLightArrow::RIGHT] = getPoint(5); traffic_simulator::TrafficLight light(0, color_positions, arrow_positions); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightArrow::NONE), common::SemanticError); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::STRAIGHT), getPoint(3)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::LEFT), getPoint(4)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightArrow::RIGHT), getPoint(5)); EXPECT_THROW( light.getPosition(traffic_simulator::TrafficLightColor::NONE), common::SemanticError); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::GREEN), getPoint(0)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::YELLOW), getPoint(1)); EXPECT_POINT_EQ(light.getPosition(traffic_simulator::TrafficLightColor::RED), getPoint(2)); EXPECT_EQ(light.id, static_cast<std::int64_t>(0)); } TEST(TrafficLights, setColorPhase) { std::unordered_map<traffic_simulator::TrafficLightColor, geometry_msgs::msg::Point> color_positions; color_positions[traffic_simulator::TrafficLightColor::GREEN] = getPoint(0); color_positions[traffic_simulator::TrafficLightColor::YELLOW] = getPoint(1); color_positions[traffic_simulator::TrafficLightColor::RED] = getPoint(2); std::unordered_map<traffic_simulator::TrafficLightArrow, geometry_msgs::msg::Point> arrow_positions; arrow_positions[traffic_simulator::TrafficLightArrow::STRAIGHT] = getPoint(3); arrow_positions[traffic_simulator::TrafficLightArrow::LEFT] = getPoint(4); arrow_positions[traffic_simulator::TrafficLightArrow::RIGHT] = getPoint(5); traffic_simulator::TrafficLight light(302120, color_positions, arrow_positions); std::vector<std::pair<double, traffic_simulator::TrafficLightColor> > color_phases; color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::RED)); color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::GREEN)); color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::YELLOW)); light.setColorPhase(color_phases); EXPECT_DOUBLE_EQ(light.getColorPhaseDuration(), 30); EXPECT_DOUBLE_EQ(light.getArrowPhaseDuration(), std::numeric_limits<double>::infinity()); EXPECT_EQ(light.id, static_cast<std::int64_t>(302120)); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::GREEN); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::YELLOW); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::GREEN); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::YELLOW); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::NONE); } TEST(TrafficLights, setColorAndArrowPhase) { std::unordered_map<traffic_simulator::TrafficLightColor, geometry_msgs::msg::Point> color_positions; color_positions[traffic_simulator::TrafficLightColor::GREEN] = getPoint(0); color_positions[traffic_simulator::TrafficLightColor::YELLOW] = getPoint(1); color_positions[traffic_simulator::TrafficLightColor::RED] = getPoint(2); std::unordered_map<traffic_simulator::TrafficLightArrow, geometry_msgs::msg::Point> arrow_positions; arrow_positions[traffic_simulator::TrafficLightArrow::STRAIGHT] = getPoint(3); arrow_positions[traffic_simulator::TrafficLightArrow::LEFT] = getPoint(4); arrow_positions[traffic_simulator::TrafficLightArrow::RIGHT] = getPoint(5); traffic_simulator::TrafficLight light(302120, color_positions, arrow_positions); std::vector<std::pair<double, traffic_simulator::TrafficLightColor> > color_phases; color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::RED)); color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::GREEN)); color_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightColor>( 10, traffic_simulator::TrafficLightColor::YELLOW)); light.setColorPhase(color_phases); std::vector<std::pair<double, traffic_simulator::TrafficLightArrow> > arrow_phases; arrow_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightArrow>( 5, traffic_simulator::TrafficLightArrow::STRAIGHT)); arrow_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightArrow>( 5, traffic_simulator::TrafficLightArrow::LEFT)); arrow_phases.emplace_back(std::make_pair<double, traffic_simulator::TrafficLightArrow>( 5, traffic_simulator::TrafficLightArrow::RIGHT)); light.setArrowPhase(arrow_phases); EXPECT_DOUBLE_EQ(light.getColorPhaseDuration(), 30); EXPECT_DOUBLE_EQ(light.getArrowPhaseDuration(), 15); EXPECT_EQ(light.id, static_cast<std::int64_t>(302120)); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::STRAIGHT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::GREEN); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::RIGHT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::YELLOW); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::LEFT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::STRAIGHT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::GREEN); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::RIGHT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::YELLOW); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::LEFT); light.update(10); EXPECT_EQ(light.getColor(), traffic_simulator::TrafficLightColor::RED); EXPECT_EQ(light.getArrow(), traffic_simulator::TrafficLightArrow::STRAIGHT); } int main(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
53.584416
100
0.793909
[ "vector" ]
2105c4adeadcd6dc7f863c51eb741d288be7979a
6,375
cpp
C++
automated-tests/src/dali-toolkit/utc-Dali-BloomView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
automated-tests/src/dali-toolkit/utc-Dali-BloomView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
automated-tests/src/dali-toolkit/utc-Dali-BloomView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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. * */ #include <iostream> #include <stdlib.h> #include <dali-toolkit-test-suite-utils.h> #include <dali-toolkit/dali-toolkit.h> #include <dali-toolkit/devel-api/controls/bloom-view/bloom-view.h> using namespace Dali; using namespace Dali::Toolkit; void bloom_view_startup(void) { test_return_value = TET_UNDEF; } void bloom_view_cleanup(void) { test_return_value = TET_PASS; } // Negative test case for a method int UtcDaliBloomViewUninitialized(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomViewUninitialized"); Toolkit::BloomView view; try { // New() must be called to create a BloomView or it wont be valid. Actor a = Actor::New(); view.Add( a ); DALI_TEST_CHECK( false ); } catch (Dali::DaliException& e) { // Tests that a negative test of an assertion succeeds DALI_TEST_PRINT_ASSERT( e ); DALI_TEST_CHECK(!view); } END_TEST; } // Positive test case for a method int UtcDaliBloomViewNew(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomViewNew"); Toolkit::BloomView view = Toolkit::BloomView::New(); DALI_TEST_CHECK( view ); Toolkit::BloomView view2 = Toolkit::BloomView::New(10, 1.0f, Pixel::RGB888, 0.5f, 0.5f); DALI_TEST_CHECK( view2 ); END_TEST; } // Positive test case for a method int UtcDaliBloomViewDownCast(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomViewDownCast"); Toolkit::BloomView view = Toolkit::BloomView::New(); BaseHandle handle(view); Toolkit::BloomView bloomView = Toolkit::BloomView::DownCast( handle ); DALI_TEST_CHECK( view ); DALI_TEST_CHECK( bloomView ); DALI_TEST_CHECK( bloomView == view ); END_TEST; } // Positive test case for a method int UtcDaliBloomViewPropertyNames(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomViewPropertyNames"); Toolkit::BloomView view = Toolkit::BloomView::New(); DALI_TEST_CHECK( view ); // Check the names, this names are used in the shader code, // if they change in the shader code, then it has to be updated here. DALI_TEST_EQUALS( view.GetBloomThresholdPropertyIndex(), view.GetPropertyIndex("uBloomThreshold"), TEST_LOCATION ); DALI_TEST_EQUALS( view.GetBlurStrengthPropertyIndex(), view.GetPropertyIndex("BlurStrengthProperty"), TEST_LOCATION ); DALI_TEST_EQUALS( view.GetBloomIntensityPropertyIndex(), view.GetPropertyIndex("uBloomIntensity"), TEST_LOCATION ); DALI_TEST_EQUALS( view.GetBloomSaturationPropertyIndex(), view.GetPropertyIndex("uBloomSaturation"), TEST_LOCATION ); DALI_TEST_EQUALS( view.GetImageIntensityPropertyIndex(), view.GetPropertyIndex("uImageIntensity"), TEST_LOCATION ); DALI_TEST_EQUALS( view.GetImageSaturationPropertyIndex(), view.GetPropertyIndex("uImageSaturation"), TEST_LOCATION ); END_TEST; } // Positive test case for a method int UtcDaliBloomViewAddRemove(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomViewAddRemove"); Toolkit::BloomView view = Toolkit::BloomView::New(); DALI_TEST_CHECK( view ); Actor actor = Actor::New(); DALI_TEST_CHECK( !actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); view.SetProperty( Actor::Property::SIZE, application.GetScene().GetSize()); view.Add(actor); application.GetScene().Add(view); DALI_TEST_CHECK( actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ); view.Remove(actor); DALI_TEST_CHECK( !actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ); END_TEST; } // Positive test case for a method int UtcDaliBloomActivateDeactivate(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliBloomActivateDeactivate"); Toolkit::BloomView view = Toolkit::BloomView::New(); DALI_TEST_CHECK( view ); RenderTaskList taskList = application.GetScene().GetRenderTaskList(); DALI_TEST_CHECK( 1u == taskList.GetTaskCount() ); view.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER); view.SetProperty( Actor::Property::SIZE, application.GetScene().GetSize()); view.Add(Actor::New()); application.GetScene().Add(view); view.Activate(); RenderTaskList taskList2 = application.GetScene().GetRenderTaskList(); DALI_TEST_CHECK( 1u != taskList2.GetTaskCount() ); view.Deactivate(); RenderTaskList taskList3 = application.GetScene().GetRenderTaskList(); DALI_TEST_CHECK( 1u == taskList3.GetTaskCount() ); END_TEST; } int UtcDaliBloomCopyAndAssignment(void) { ToolkitTestApplication application; BloomView view = Toolkit::BloomView::New(); DALI_TEST_CHECK( view ); BloomView copy( view ); DALI_TEST_CHECK( view == copy ); BloomView assign; DALI_TEST_CHECK( ! assign ); assign = copy; DALI_TEST_CHECK( assign == view ); END_TEST; } int UtcDaliBloomTypeRegistry(void) { ToolkitTestApplication application; TypeRegistry typeRegistry = TypeRegistry::Get(); DALI_TEST_CHECK( typeRegistry ); TypeInfo typeInfo = typeRegistry.GetTypeInfo( "BloomView" ); DALI_TEST_CHECK( typeInfo ); BaseHandle handle = typeInfo.CreateInstance(); DALI_TEST_CHECK( handle ); BloomView view = BloomView::DownCast( handle ); DALI_TEST_CHECK( view ); END_TEST; } int UtcDaliBloomOnSizeSet(void) { ToolkitTestApplication application; BloomView view = Toolkit::BloomView::New(); application.GetScene().Add( view ); application.SendNotification(); application.Render(); Vector3 size( 200.0f, 300.0f, 0.0f ); view.SetProperty( Actor::Property::SIZE, size ); application.SendNotification(); application.Render(); DALI_TEST_EQUALS( view.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), size, TEST_LOCATION ); END_TEST; }
28.0837
120
0.746196
[ "render" ]
210620091f5f1fbf193a95cc728ba9b7fbbe4d21
4,514
cpp
C++
alica_cace_tests/src/test_alica_authority.cpp
carpe-noctem-cassel/cace
e3c9cad6ca2e5b6ec5cb3b3c913a196fb95065b1
[ "MIT" ]
null
null
null
alica_cace_tests/src/test_alica_authority.cpp
carpe-noctem-cassel/cace
e3c9cad6ca2e5b6ec5cb3b3c913a196fb95065b1
[ "MIT" ]
null
null
null
alica_cace_tests/src/test_alica_authority.cpp
carpe-noctem-cassel/cace
e3c9cad6ca2e5b6ec5cb3b3c913a196fb95065b1
[ "MIT" ]
null
null
null
/* * test_alica_authority.cpp * * Created on: Oct 27, 2014 * Author: Stefan Jakob */ #include <gtest/gtest.h> #include <engine/AlicaEngine.h> #include <engine/IAlicaClock.h> #include "engine/IAlicaCommunication.h" #include "BehaviourCreator.h" #include "ConditionCreator.h" #include "ConstraintCreator.h" #include "UtilityFunctionCreator.h" #include <clock/AlicaROSClock.h> #include <communication/AlicaRosCommunication.h> #include "TestWorldModel.h" #include "engine/PlanRepository.h" #include "engine/UtilityFunction.h" #include "engine/model/Plan.h" #include "DummyTestSummand.h" #include "engine/teamobserver/TeamObserver.h" #include "engine/PlanBase.h" #include "engine/model/State.h" #include "cace.h" #include "clock/AlicaCaceClock.h" #include "communication/AlicaCaceCommunication.h" class AlicaEngineAuthorityManager : public ::testing::Test { protected: supplementary::SystemConfig* sc; alica::AlicaEngine* ae; Cace* cace; alica::AlicaEngine* ae2; Cace* cace2; alica::BehaviourCreator* bc; alica::ConditionCreator* cc; alica::UtilityFunctionCreator* uc; alica::ConstraintCreator* crc; virtual void SetUp() { // determine the path to the test config string path = supplementary::FileSystem::getSelfPath(); int place = path.rfind("devel"); path = path.substr(0, place); path = path + "src/alica/alica_test/src/test"; // bring up the SystemConfig with the corresponding path sc = supplementary::SystemConfig::getInstance(); sc->setRootPath(path); sc->setConfigPath(path + "/etc"); sc->setHostname("nase"); // setup the engine ae = new alica::AlicaEngine(); bc = new alica::BehaviourCreator(); cc = new alica::ConditionCreator(); uc = new alica::UtilityFunctionCreator(); crc = new alica::ConstraintCreator(); } virtual void TearDown() { ae->shutdown(); sc->shutdown(); ae2->shutdown(); delete cace; delete ae->getCommunicator(); delete cace2; delete ae2->getCommunicator(); delete ae->getIAlicaClock(); delete ae2->getIAlicaClock(); delete cc; delete bc; delete uc; delete crc; } }; TEST_F(AlicaEngineAuthorityManager, authority) { sc->setHostname("nase"); cace = Cace::getEmulated(sc->getHostname(), sc->getOwnRobotID()); cace->safeStepMode = true; ae = new alica::AlicaEngine(); ae->setIAlicaClock(new alicaCaceProxy::AlicaCaceClock(cace)); ae->setCommunicator(new alicaCaceProxy::AlicaCaceCommunication(ae, cace)); EXPECT_TRUE(ae->init(bc, cc, uc, crc, "RolesetTA", "AuthorityTestMaster", ".", true)) << "Unable to initialise the Alica Engine!"; sc->setHostname("hairy"); cace2 = Cace::getEmulated(sc->getHostname(), sc->getOwnRobotID()); cace2->safeStepMode = true; ae2 = new alica::AlicaEngine(); ae2->setIAlicaClock(new alicaCaceProxy::AlicaCaceClock(cace2)); ae2->setCommunicator(new alicaCaceProxy::AlicaCaceCommunication(ae2, cace2)); EXPECT_TRUE(ae2->init(bc, cc, uc, crc, "RolesetTA", "AuthorityTestMaster", ".", true)) << "Unable to initialise the Alica Engine!"; auto uSummandAe = *((ae->getPlanRepository()->getPlans().find(1414403413451))->second->getUtilityFunction()->getUtilSummands().begin()); DummyTestSummand* dbr = dynamic_cast<DummyTestSummand*>(uSummandAe); dbr->robotId = ae->getTeamObserver()->getOwnId(); auto uSummandAe2 = *((ae2->getPlanRepository()->getPlans().find(1414403413451))->second->getUtilityFunction()->getUtilSummands().begin()); DummyTestSummand* dbr2 = dynamic_cast<DummyTestSummand*>(uSummandAe2); dbr2->robotId = ae2->getTeamObserver()->getOwnId(); ae->start(); ae2->start(); alicaTests::TestWorldModel::getOne()->robotsXPos.push_back(0); alicaTests::TestWorldModel::getOne()->robotsXPos.push_back(2000); alicaTests::TestWorldModel::getTwo()->robotsXPos.push_back(2000); alicaTests::TestWorldModel::getTwo()->robotsXPos.push_back(0); for (int i = 0; i < 21; i++) { ae->stepNotify(); chrono::milliseconds duration(33); this_thread::sleep_for(duration); ae2->stepNotify(); this_thread::sleep_for(duration); if (i == 1) { EXPECT_EQ((*ae->getPlanBase()->getRootNode()->getChildren()->begin())->getActiveState()->getId(), 1414403553717); EXPECT_EQ((*ae2->getPlanBase()->getRootNode()->getChildren()->begin())->getActiveState()->getId(), 1414403553717); } if (i == 20) { EXPECT_EQ((*ae->getPlanBase()->getRootNode()->getChildren()->begin())->getActiveState()->getId(), 1414403553717); EXPECT_EQ((*ae2->getPlanBase()->getRootNode()->getChildren()->begin())->getActiveState()->getId(), 1414403429950); } } }
32.710145
139
0.719761
[ "model" ]
210a6de1fd198069022bf8c0beabef5cf6fd113d
9,001
cpp
C++
src/stochMath.cpp
KorfLab/StochHMM
965ee4fbe2f2dac8868387989901369cba452086
[ "MIT" ]
127
2015-01-16T13:05:48.000Z
2022-01-27T15:17:25.000Z
src/stochMath.cpp
johnson056029/nycuPPproj
a6231db4b0a29ddd509bff75e00d11c3f83d43a7
[ "MIT" ]
11
2015-03-19T16:51:42.000Z
2021-09-10T02:15:00.000Z
src/stochMath.cpp
johnson056029/nycuPPproj
a6231db4b0a29ddd509bff75e00d11c3f83d43a7
[ "MIT" ]
41
2015-06-04T02:02:09.000Z
2021-11-09T17:14:15.000Z
// // stochMath.cpp //Copyright (c) 2007-2012 Paul C Lott //University of California, Davis //Genome and Biomedical Sciences Facility //UC Davis Genome Center //Ian Korf Lab //Website: www.korflab.ucdavis.edu //Email: lottpaul@gmail.com // //Permission is hereby granted, free of charge, to any person obtaining a copy of //this software and associated documentation files (the "Software"), to deal in //the Software without restriction, including without limitation the rights to //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //the Software, and to permit persons to whom the Software is furnished to do so, //subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS //FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER //IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN //CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "stochMath.h" namespace StochHMM{ void generateUnknownIndices(std::vector<size_t>& results, size_t alphabetSize, size_t order ,size_t value){ results.assign(alphabetSize,0); for (size_t i = 0; i < (size_t) alphabetSize; i++){ results[i]= (size_t)value + i * (size_t) POWER[order-1][alphabetSize-1]; } return; } //Linear interpolation of y value given two pair<x,y> and x value double interpolate(std::pair<double,double>& a, std::pair<double,double>& b, double& cx){ //std::cout << a.first << "\t" << a.second <<std::endl; //std::cout << b.first << "\t" << b.second <<std::endl; return a.second+(b.second-a.second)*((cx-a.first)/(b.first-a.first)); } //Linear extrapolation of y value given two pair<x,y> and x value double extrapolate(std::pair<double,double>& a, std::pair<double,double>& b, double& cx){ return a.second+((cx-a.first)/(b.first-a.first))*(b.second-a.second); } //Shannon's entropy float entropy (std::vector<float> &set){ float entropy=0; for(size_t i=0;i<set.size();i++){ entropy+=set[i]*(log(set[i])/log(2)); } return entropy*-1; } //Shannon's entropy double entropy (std::vector<double> &set){ double entropy=0; for(size_t i=0;i<set.size();i++){ entropy+=set[i]*(log(set[i])/log(2)); } return entropy*-1; } //Shannon's Relative Entropy (Kullback-Liebler Convergence) //Normalized for A->B and B->A float rel_entropy (std::vector<float> &set, std::vector<float> &set2){ float rel_entropy=0; if (set.size()!=set2.size()){ std::cerr << "Distributions aren't the same size"; } for(size_t i=0;i<set.size();i++){ rel_entropy+=0.5*(set[i]* (log (set[i]/set2[i]) /log(2) )+set2[i]*(log(set2[i]/set[i])/log(2))); } return rel_entropy; } //Shannon's Relative Entropy (Kullback-Liebler Convergence) //Normalized for A->B and B->A double rel_entropy (std::vector<double> &set, std::vector<double> &set2){ double rel_entropy=0; if (set.size()!=set2.size()){ std::cerr << "Distributions aren't the same size"; } for(size_t i=0;i<set.size();i++){ rel_entropy+=0.5*(set[i]* (log (set[i]/set2[i]) /log(2) )+set2[i]*(log(set2[i]/set[i])/log(2))); } return rel_entropy; } /////////////////////////////////////////// Integration & Summation ////////////////////////////////////////////// //Need to adapt to take up to three paramenter and pass them to the function. //If one parameter is given then only pass one to function and so on. //Fix: variable handed to function to include only vector<double> double _integrate (double (*funct)(double, std::vector<double>&),double upper, double lower,std::vector<double>& param){ double mid=(lower+upper)/2.0; double h3=fabs(upper-lower)/6.0; return h3*(funct(lower,param)+4*funct(mid,param)+funct(upper,param)); } double integrate (double (*funct)(double,std::vector<double>&),double lower, double upper ,std::vector<double>& param, double max_error=0.000001, double sum=0){ double mid=(upper+lower)/2.0; double left=_integrate(funct,lower, mid, param); double right=_integrate(funct,mid,upper, param); if (fabs(left+right-sum)<=15*max_error){ return left+right +(left+right-sum)/15; } return integrate(funct,lower,mid,param,max_error/2,left) + integrate(funct,mid,upper,param,max_error/2,right); } // Adaptive Simpson's numerical integration method double simpson (double (*funct)(double,double,double),double alpha, double beta, double lower, double upper){ double mid=(lower+upper)/2.0; double h3=fabs(upper-lower)/6.0; return h3*(funct(lower,alpha,beta)+4*funct(mid,alpha,beta)+funct(upper,alpha,beta)); } double adapt_simpson (double (*funct)(double,double,double),double alpha, double beta, double lower, double upper, double max_error, double sum){ double mid=(upper+lower)/2.0; double left=simpson(funct,alpha,beta,lower, mid); double right=simpson(funct,alpha,beta,mid,upper); if (fabs(left+right-sum)<=15*max_error){ return left+right +(left+right-sum)/15; } return adapt_simpson(funct,alpha,beta,lower,mid,max_error/2,left) + adapt_simpson(funct,alpha,beta,mid,upper,max_error/2,right); } double summation (double (*funct)(int,std::vector<double>), int lower, int upper, std::vector<double> param){ double sum=0; for(int i=lower;i<=upper;i++){ sum+=funct(i,param); } return sum; } /////////////////////////////////////// FUNCTIONS ////////////////////////////////////////////// double igamma_upper (double s, double x){ return tgamma(s)-igamma_lower(s,x); } //incomplete lower gamma (a,x) ///http://wwwC/.rskey.org/CMS/index.php/the-library/11 double igamma_lower (double a, double x){ double constant = pow(x,a) * exp(-1 * x); double sum =0; for (int n=0;n<60;n++){ double num = pow(x,(double)n); double denom=a; for(int m=1;m<=n;m++){ denom*=a+m; } num/=denom; sum+=num; } return constant * sum; } double rgammap(double s, double x){ return igamma_lower(s,x)/tgamma(s); } double rgammaq(double s, double x){ return igamma_upper(s,x)/tgamma(s); } //Beta(a,b) = Beta function double beta(double a, double b){ double value=(tgamma(a)*tgamma(b))/tgamma(a+b); return value; } //Incomplete beta function B(x,a,b) double ibeta(double x, double a, double b){ return betaPDF(x,a,b) * exp(log(tgamma(a)) + log(tgamma(b)) - log(tgamma(a+b))); } //!Beta probability distribution function //!param x Value 0<x<1 //!param a Shape parameter a>0 //!param b Shape parameter b>0 float betaPDF(float x, float a, float b){ float constant = 1/beta(a,b); constant*=pow(x,a-1) * pow(1-x,b-1); return constant; } // ////Incomplete beta function B(x,a,b) //double ibeta(double x, double a, double b){ // vector<double> parameters(2,0.0); // parameters[0]=a; // parameters[1]=b; // return (integrate(_ibeta,0.0,x,parameters)); //} // //double _ibeta(double x, vector<double>& parameters){ // double a=parameters[0]; // double b=parameters[1]; // return (pow(x,a-1)*pow(1-x,b-1)); //} //Regularized incomplete beta Ix(a,b) double ribeta(double x, double a, double b){ return ibeta(x,a,b)/beta(a,b); } //Returns stirlings approximation of floor(X!) double factorial(double x){ double f=sqrt((2*x+(1/3))*M_PI)*pow(x,x)*exp(-1*x); return floor(f); } //Calculate the binomial coefficient double bin_coef (double n, double r){ double c=0; for(int i=r+1;i<=n;i++) {c+=log(i);} for(int j=1;j<=(n-r);j++) {c-=log(j);} return exp(c); } int bin_coef (int n, int r){ float c=0; for(int i=r+1;i<=n;i++) {c+=log(i);} for(int j=1;j<=(n-r);j++) {c-=log(j);} return exp(c); } }
34.887597
164
0.585046
[ "shape", "vector" ]
210e228c18346b6ac2ab839d82346f080fb4d4ac
14,363
hpp
C++
include/musycl/midi/controller/keylab_essential.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
16
2021-05-07T11:33:59.000Z
2022-03-05T02:36:06.000Z
include/musycl/midi/controller/keylab_essential.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
null
null
null
include/musycl/midi/controller/keylab_essential.hpp
keryell/muSYCL
130e4b29c3a4daf4c908b08263b53910acb13787
[ "Apache-2.0" ]
null
null
null
#ifndef MUSYCL_MIDI_CONTROLLER_KEYLAB_ESSENTIAL_HPP #define MUSYCL_MIDI_CONTROLLER_KEYLAB_ESSENTIAL_HPP /** \file Represent a MIDI controller like the Arturia KeyLab49 Essential */ #include <chrono> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <string> #include <thread> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include <range/v3/all.hpp> #include "musycl/midi.hpp" #include "musycl/midi/midi_out.hpp" namespace musycl { // To use time unit literals directly using namespace std::chrono_literals; class controller { public: /** Mapping of button light to SySex button light command Some names have the suffix \c _bis and \c _ter because they are alternative code to do the same action. It is not clear which value trigger the Vegas light show mode. */ enum class button_out : std::int8_t { vegas_mode = 0x0d, vegas_mode_bis = 0x0e, vegas_mode_ter = 0x0f, octave_minus = 0x10, octave_plus = 0x11, chord = 0x12, transpose = 0x13, midi_channel = 0x14, map_select = 0x15, cat_char = 0x16, preset = 0x17, backward = 0x18, forward = 0x19, part_1_next = 0x1a, part_2_prev = 0x1b, live_bank = 0x1c, metro = 0x1d, fast_forward = 0x1e, record = 0x1f, pad_1_blue = 0x20, pad_1_green = 0x21, pad_1_red = 0x22, pad_2_blue = 0x23, pad_2_green = 0x24, pad_2_red = 0x25, pad_3_blue = 0x26, pad_3_green = 0x27, pad_3_red = 0x28, pad_4_blue = 0x29, pad_4_green = 0x2a, pad_4_red = 0x2b, pad_5_blue = 0x2c, pad_5_green = 0x2d, pad_5_red = 0x2e, pad_6_blue = 0x2f, pad_6_green = 0x30, pad_6_red = 0x31, pad_7_blue = 0x32, pad_7_green = 0x33, pad_7_red = 0x34, pad_8_blue = 0x35, pad_8_green = 0x36, pad_8_red = 0x37, chord_bis = 0x38, transpose_bis = 0x39, octave_minus_bis = 0x3a, octave_plus_bis = 0x3b, map_select_bis = 0x3c, midi_channel_bis = 0x3d, save = 0x3e, punch = 0x3f, save_bis = 0x56, undo = 0x57, punch_bis = 0x58, metro_bis = 0x59, loop = 0x5a, rewind = 0x5b, fast_forward_bis = 0x5c, stop = 0x5d, play_pause = 0x5e, record_bis = 0x5f, pad_1_blue_bis = 0x70, pad_2_blue_bis = 0x71, pad_3_blue_bis = 0x72, pad_4_blue_bis = 0x73, pad_5_blue_bis = 0x74, pad_6_blue_bis = 0x75, pad_7_blue_bis = 0x76, pad_8_blue_bis = 0x77, pad_1_blue_ter = 0x78, pad_2_blue_ter = 0x79, pad_3_blue_ter = 0x7a, pad_4_blue_ter = 0x7b, pad_5_blue_ter = 0x7c, pad_6_blue_ter = 0x7d, pad_7_blue_ter = 0x7e, pad_8_blue_ter = 0x7f, }; /** An Arturia KeyLab MIDI controller This is made by gathering some information on-line, such as https://forum.arturia.com/index.php?topic=90496.0 https://forum.renoise.com/t/tool-development-arturia-keylab-mkii-49-61-mcu-midi-messages/57343 https://community.cantabilesoftware.com/t/questions-about-expressions-in-sysex-data/5175 Some SysEx values can be seen in the MIDI console of the MIDI Control Center from Arturia. */ class keylab_essential : public clock::follow<keylab_essential> { /** Arturia MIDI SysEx Id https://www.midi.org/specifications/midi-reference-tables/manufacturer-sysex-id-numbers */ static auto constexpr sysex_id = { '\0', '\x20', '\x6b' }; /// The device ID seems just "broadcast" static auto constexpr dev_id = { '\x7f' }; /// The sub device ID? static auto constexpr sub_dev_id = { '\x42' }; static auto constexpr sysex_vegas_mode_off = { '\x2', '\0', '\x40', '\x50', '\0' }; static auto constexpr sysex_vegas_mode_on = { '\x2', '\0', '\x40', '\x50', '\x1' }; /** Button light fuzzing Experiment with some light commands */ void button_light_fuzzing() { // Pick a button range to check for (auto b = 0x00; b <= 0x0f; ++b) { for (auto l = 0; l <= 127; ++l) { button_light(b, l); std::this_thread::sleep_for(10ms); } std::this_thread::sleep_for(2s); button_light(b, 0); } /* Increase light level across all the buttons. The problem is that it triggers the Vegas light show mode */ for (auto l = 0; l <= 127; ++l) for (auto b = 0; b <= 127; ++b) { button_light(b, l); std::this_thread::sleep_for(10ms); } } public: /// List all the control items // std::vector<control::control_item> inputs; control::control_item cutoff_pan_1 { this, control::control_item::type::knob, control::control_item::cc { 0x4a }, control::control_item::cc_inc { 0x10 } }; control::control_item resonance_pan_2 { this, control::control_item::type::knob, control::control_item::cc { 0x47 }, control::control_item::cc_inc { 0x11 } }; control::control_item lfo_rate_pan_3 { this, control::control_item::type::knob, control::control_item::cc { 0x4c }, control::control_item::cc_inc { 0x12 } }; control::control_item lfo_amt_pan_4 { this, control::control_item::type::knob, control::control_item::cc { 0x4d }, control::control_item::cc_inc { 0x13 } }; control::control_item param_1_pan_5 { this, control::control_item::type::knob, control::control_item::cc { 0x5d }, control::control_item::cc_inc { 0x14 } }; control::control_item param_2_pan_6 { this, control::control_item::type::knob, control::control_item::cc { 0x12 }, control::control_item::cc_inc { 0x15 } }; control::control_item param_3_pan_7 { this, control::control_item::type::knob, this, control::control_item::cc { 0x13 }, control::control_item::cc_inc { 0x16 } }; control::control_item param_4_pan_8 { this, control::control_item::type::knob, control::control_item::cc { 0x10 }, control::control_item::cc_inc { 0x17 } }; // The unnamed knob on the top right, non mapped in DAW mode control::control_item top_right_knob_9 { this, control::control_item::type::knob, control::control_item::cc { 0x11 } }; control::control_item attack_ch_1 { this, control::control_item::type::slider, control::control_item::cc { 0x49 } }; control::control_item decay_ch_2 { this, control::control_item::type::slider, control::control_item::cc { 0x4b } }; control::control_item sustain_ch_3 { this, control::control_item::type::slider, control::control_item::cc { 0x4f } }; control::control_item release_ch_4 { this, control::control_item::type::slider, control::control_item::cc { 0x48 } }; control::control_item attack_ch_5 { this, control::control_item::type::slider, control::control_item::cc { 0x50 } }; control::control_item decay_ch_6 { this, control::control_item::type::slider, control::control_item::cc { 0x51 } }; control::control_item sustain_ch_7 { this, control::control_item::type::slider, control::control_item::cc { 0x52 } }; control::control_item release_ch_8 { this, control::control_item::type::slider, control::control_item::cc { 0x53 } }; control::control_item play_pause { this, control::control_item::type::button, control::control_item::note { 0x5e } }; control::control_item pad_1 = { this, control::control_item::type::button, control::control_item::pad { 0x24, button_out::pad_1_red, button_out::pad_1_blue, button_out::pad_1_green } }; control::control_item pad_2 = { this, control::control_item::type::button, control::control_item::pad { 0x25, button_out::pad_2_red, button_out::pad_2_blue, button_out::pad_2_green } }; control::control_item pad_3 = { this, control::control_item::type::button, control::control_item::pad { 0x26, button_out::pad_3_red, button_out::pad_3_blue, button_out::pad_3_green } }; control::control_item pad_4 = { this, control::control_item::type::button, control::control_item::pad { 0x27, button_out::pad_4_red, button_out::pad_4_blue, button_out::pad_4_green } }; control::control_item pad_5 = { this, control::control_item::type::button, control::control_item::pad { 0x28, button_out::pad_5_red, button_out::pad_5_blue, button_out::pad_5_green } }; control::control_item pad_6 = { this, control::control_item::type::button, control::control_item::pad { 0x29, button_out::pad_6_red, button_out::pad_6_blue, button_out::pad_6_green } }; control::control_item pad_7 = { this, control::control_item::type::button, control::control_item::pad { 0x2a, button_out::pad_7_red, button_out::pad_7_blue, button_out::pad_7_green } }; control::control_item pad_8 = { this, control::control_item::type::button, control::control_item::pad { 0x2b, button_out::pad_8_red, button_out::pad_8_blue, button_out::pad_8_green } }; /// Start the KeyLab controller keylab_essential() { display("Salut les petits amis"); // button_light_fuzzing(); // Refresh the LCD display because it is garbled by various information clock::scheduler.appoint_cyclic(0.25s, [this](auto) { refresh_display(); }); } /** Send a MIDI SysEx message by prepending SysEx Start and appending SysEx End \return a copy of the full MIDI message sent, for example for later replay. */ template <typename... Ranges> auto send_sysex(Ranges&&... messages) { static auto constexpr sysex_start = { '\xf0' }; static auto constexpr sysex_end = { '\xf7' }; auto sysex_message = ranges::to<std::vector<std::uint8_t>>( ranges::view::concat(sysex_start, sysex_id, dev_id, sub_dev_id, messages..., sysex_end)); midi_out::write(sysex_message); return sysex_message; } void button_light(std::int8_t button, std::int8_t level) { static auto constexpr sysex_button_light = { '\x2', '\0', '\x10' }; send_sysex(sysex_button_light, ranges::view::single(button), ranges::view::single(level)); } /// Store the last displayed message to refresh the display regularly std::vector<std::uint8_t> last_displayed_sysex_message; /// Display a message on the LCD display void display(const std::string& message) { // Split the string in at most 2 lines of 16 characters max auto r = ranges::view::all(message) | ranges::view::chunk(16) | ranges::view::take(2) | ranges::view::enumerate | ranges::view::transform([](auto&& enumeration) { auto [line_number, line_content] = enumeration; return ranges::view::concat( ranges::view::single(char(line_number + 1)), line_content, ranges::view::single('\0')); }) | ranges::view::join; static auto constexpr sysex_display_command = { '\x4', '\0', '\x60' }; last_displayed_sysex_message = send_sysex(sysex_display_command, r); } /// Refresh the LCD display with the last displayed message void refresh_display() { midi_out::write(last_displayed_sysex_message); } /** Display a blinking cursor It looks like having 0 as a line number erase the fist line with a blinking cursor but the first line can be then displayed on the second line. Actually it looks more like a random bug which is triggered here... */ void blink() { static auto constexpr blink_display_command = { '\x4', '\0', '\x60', '\0', '\0' }; send_sysex(blink_display_command); } /// This is notified on each beat by the clocking framework void midi_clock(clock::type ct) { /* Blink the Metro light for 16th of note at the start of each (quarter) beat at half the brightness, with the first beat of the measure being full brightness */ auto light_level = (ct.midi_clock_index < midi::clock_per_quarter / 4) * (32 + 95 * (ct.beat_index == 0)); button_light((int)button_out::metro, light_level); } }; }; } // namespace musycl #endif // MUSYCL_MIDI_CONTROLLER_KEYLAB_ESSENTIAL_HPP
36.734015
100
0.559354
[ "vector", "transform" ]
211293551468e79f78e55b2004c596c58cf24eb5
41,169
cpp
C++
mojiben1/mojiben1.cpp
katahiromz/mojiben
8a8d1a3fdffe6ff78165c50e37a6c44aee335e82
[ "MIT" ]
null
null
null
mojiben1/mojiben1.cpp
katahiromz/mojiben
8a8d1a3fdffe6ff78165c50e37a6c44aee335e82
[ "MIT" ]
3
2021-07-27T11:19:34.000Z
2021-07-27T12:01:43.000Z
mojiben1/mojiben1.cpp
katahiromz/mojiben
8a8d1a3fdffe6ff78165c50e37a6c44aee335e82
[ "MIT" ]
null
null
null
// Moji No Benkyo (1) // Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com> // This file is public domain software. #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <cstdlib> #include <process.h> #include <cmath> #include <new> #include <vector> #include <map> #include <set> #include "kakijun.h" #ifndef M_PI #define M_PI 3.141592653589 #endif static const TCHAR g_szClassName[] = TEXT("Moji No Benkyou (1)"); static const TCHAR g_szKakijunClassName[] = TEXT("Moji No Benkyou (1) Kakijun"); HINSTANCE g_hInstance; HWND g_hMainWnd; HWND g_hKakijunWnd; HBITMAP g_hbmHiragana, g_hbmHiragana2; HBITMAP g_hbmKatakana, g_hbmKatakana2; HBITMAP g_aahbmHiragana[11][5]; HBITMAP g_aahbmKatakana[11][5]; HBITMAP g_hbm; BOOL g_fKatakana; HBITMAP g_hbm2; INT g_nMoji; HANDLE g_hThread; HBRUSH g_hbrRed; std::set<INT> g_katakana_history; std::set<INT> g_hiragana_history; LPTSTR LoadStringDx(INT ids) { static TCHAR sz[512]; LoadString(g_hInstance, ids, sz, 512); return sz; } BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct) { INT i, j; HMENU hSysMenu; MENUITEMINFO mii; g_hThread = NULL; g_hbm2 = NULL; g_hbrRed = CreateSolidBrush(RGB(255, 0, 0)); g_hbmHiragana = LoadBitmap(g_hInstance, MAKEINTRESOURCE(100)); g_hbmHiragana2 = LoadBitmap(g_hInstance, MAKEINTRESOURCE(150)); g_hbmKatakana = LoadBitmap(g_hInstance, MAKEINTRESOURCE(200)); g_hbmKatakana2 = LoadBitmap(g_hInstance, MAKEINTRESOURCE(250)); g_fKatakana = FALSE; hSysMenu = GetSystemMenu(hwnd, FALSE); ZeroMemory(&mii, sizeof(MENUITEMINFO)); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE; mii.fType = MFT_SEPARATOR; mii.fState = MFS_ENABLED; mii.wID = (UINT)-1; mii.dwTypeData = 0; InsertMenuItem(hSysMenu, -1, TRUE, &mii); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE; mii.fType = MFT_STRING; mii.fState = MFS_ENABLED; mii.wID = 0x3330; mii.dwTypeData = LoadStringDx(2); InsertMenuItem(hSysMenu, -1, TRUE, &mii); ZeroMemory(g_aahbmHiragana, sizeof(g_aahbmHiragana)); for (j = 0; j <= 100; j += 10) { if (j == 70) { i = 0; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; i = 2; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; i = 4; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; } else if (j == 90) { i = 0; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; i = 4; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; } else if (j == 100) { i = 4; g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; } else { for (i = 0; i < 5; i++) { g_aahbmHiragana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(1000 + j + i)); if (g_aahbmHiragana[j / 10][i] == NULL) return FALSE; } } } ZeroMemory(g_aahbmKatakana, sizeof(g_aahbmKatakana)); for (j = 0; j <= 100; j += 10) { if (j == 70) { i = 0; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; i = 2; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; i = 4; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; } else if (j == 90) { i = 0; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; i = 4; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; } else if (j == 100) { i = 4; g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; } else { for (i = 0; i < 5; i++) { g_aahbmKatakana[j / 10][i] = LoadBitmap(g_hInstance, MAKEINTRESOURCE(2000 + j + i)); if (g_aahbmKatakana[j / 10][i] == NULL) return FALSE; } } } g_hbm = NULL; try { InitHiragana(); InitKatakana(); } catch (std::bad_alloc) { return FALSE; } INT cx = GetSystemMetrics(SM_CXBORDER); INT cy = GetSystemMetrics(SM_CYBORDER); g_hKakijunWnd = CreateWindow(g_szKakijunClassName, TEXT(""), WS_POPUPWINDOW, CW_USEDEFAULT, 0, 300 + cx * 2, 300 + cy * 2, hwnd, NULL, g_hInstance, NULL); if (g_hKakijunWnd == NULL) return FALSE; return TRUE; } VOID OnDraw(HWND hwnd, HDC hdc) { HDC hdcMem, hdcMem2; HGDIOBJ hbmOld, hbmOld2; INT i, j; RECT rc; SIZE siz; HBRUSH hbr; hdcMem = CreateCompatibleDC(hdc); hdcMem2 = CreateCompatibleDC(hdc); GetClientRect(hwnd, &rc); siz.cx = rc.right - rc.left; siz.cy = rc.bottom - rc.top; if (g_hbm == NULL) { g_hbm = CreateCompatibleBitmap(hdc, siz.cx, siz.cy); hbmOld2 = SelectObject(hdcMem2, g_hbm); hbr = CreateSolidBrush(RGB(255, 255, 192)); FillRect(hdcMem2, &rc, hbr); DeleteObject(hbr); typedef HBITMAP MYBITMAPS[11][5]; MYBITMAPS *bitmaps; if (g_fKatakana) { hbmOld = SelectObject(hdcMem, g_hbmHiragana2); BitBlt(hdcMem2, 160, 10, 200, 76, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); hbmOld = SelectObject(hdcMem, g_hbmKatakana); BitBlt(hdcMem2, siz.cx - (160 + 200), 10, 200, 76, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); bitmaps = &g_aahbmKatakana; } else { hbmOld = SelectObject(hdcMem, g_hbmHiragana); BitBlt(hdcMem2, 160, 10, 200, 76, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); hbmOld = SelectObject(hdcMem, g_hbmKatakana2); BitBlt(hdcMem2, siz.cx - (160 + 200), 10, 200, 76, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); bitmaps = &g_aahbmHiragana; } for (j = 0; j <= 100; j += 10) { if (j == 70) { i = 0; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); i = 2; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); i = 4; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); } else if (j == 90) { i = 0; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); i = 4; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); } else if (j == 100) { i = 4; hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); } else { for (i = 0; i < 5; i++) { hbmOld = SelectObject(hdcMem, (*bitmaps)[j / 10][i]); rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (g_fKatakana) { if (g_katakana_history.find(j + i) != g_katakana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } else { if (g_hiragana_history.find(j + i) != g_hiragana_history.end()) FillRect(hdcMem2, &rc, g_hbrRed); else FillRect(hdcMem2, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); } BitBlt(hdcMem2, 685 - (j * 65) / 10, i * 60 + 100, 70, 70, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); } } } SelectObject(hdcMem2, hbmOld2); } hbmOld2 = SelectObject(hdcMem2, g_hbm); BitBlt(hdc, 0, 0, siz.cx, siz.cy, hdcMem2, 0, 0, SRCCOPY); SelectObject(hdcMem2, hbmOld2); DeleteDC(hdcMem); DeleteDC(hdcMem2); } unsigned __stdcall ThreadProc( void * ) { RECT rc; SIZE siz; HDC hdc, hdcMem; HBITMAP hbm, hbm2, hbmTemp; HGDIOBJ hbmOld; HRGN hRgn, hRgn2, hRgn3, hRgn4, hRgn5; std::vector<GA> v; INT k; POINT apt[4]; double cost, sint, cost2, sint2; const char *romaji = NULL; HFONT hFont; HGDIOBJ hFontOld; LOGFONT lf; ZeroMemory(&lf, sizeof(lf)); lf.lfHeight = -20; lf.lfCharSet = ANSI_CHARSET; lf.lfQuality = ANTIALIASED_QUALITY; lstrcpy(lf.lfFaceName, TEXT("Tahoma")); hFont = CreateFontIndirect(&lf); GetClientRect(g_hKakijunWnd, &rc); siz.cx = rc.right - rc.left; siz.cy = rc.bottom - rc.top; if (g_fKatakana) v = g_katakana_kakijun[g_nMoji]; else v = g_hiragana_kakijun[g_nMoji]; switch (g_nMoji / 10) { case 0: switch (g_nMoji % 10) { case 0: romaji = "a"; break; case 1: romaji = "i"; break; case 2: romaji = "u"; break; case 3: romaji = "e"; break; case 4: romaji = "o"; break; } break; case 1: switch (g_nMoji % 10) { case 0: romaji = "ka"; break; case 1: romaji = "ki"; break; case 2: romaji = "ku"; break; case 3: romaji = "ke"; break; case 4: romaji = "ko"; break; } break; case 2: switch (g_nMoji % 10) { case 0: romaji = "sa"; break; case 1: romaji = "shi"; break; case 2: romaji = "su"; break; case 3: romaji = "se"; break; case 4: romaji = "so"; break; } break; case 3: switch (g_nMoji % 10) { case 0: romaji = "ta"; break; case 1: romaji = "chi"; break; case 2: romaji = "tsu"; break; case 3: romaji = "te"; break; case 4: romaji = "to"; break; } break; case 4: switch (g_nMoji % 10) { case 0: romaji = "na"; break; case 1: romaji = "ni"; break; case 2: romaji = "nu"; break; case 3: romaji = "ne"; break; case 4: romaji = "no"; break; } break; case 5: switch (g_nMoji % 10) { case 0: romaji = "ha"; break; case 1: romaji = "hi"; break; case 2: romaji = "fu"; break; case 3: romaji = "he"; break; case 4: romaji = "ho"; break; } break; case 6: switch (g_nMoji % 10) { case 0: romaji = "ma"; break; case 1: romaji = "mi"; break; case 2: romaji = "mu"; break; case 3: romaji = "me"; break; case 4: romaji = "mo"; break; } break; case 7: switch (g_nMoji % 10) { case 0: romaji = "ya"; break; case 2: romaji = "yu"; break; case 4: romaji = "yo"; break; } break; case 8: switch (g_nMoji % 10) { case 0: romaji = "ra"; break; case 1: romaji = "ri"; break; case 2: romaji = "ru"; break; case 3: romaji = "re"; break; case 4: romaji = "ro"; break; } break; case 9: switch (g_nMoji % 10) { case 0: romaji = "wa"; break; case 4: romaji = "wo"; break; } break; case 10: switch (g_nMoji % 10) { case 4: romaji = "nn"; break; } break; } hRgn = CreateRectRgn(0, 0, 0, 0); for (UINT i = 0; i < v.size(); i++) { if (v[i].pb != NULL) { hRgn2 = ExtCreateRegion(NULL, v[i].cb, (RGNDATA *)v[i].pb); CombineRgn(hRgn, hRgn, hRgn2, RGN_OR); DeleteObject(hRgn2); } } hdc = GetDC(g_hKakijunWnd); hdcMem = CreateCompatibleDC(hdc); hbm = CreateCompatibleBitmap(hdc, siz.cx, siz.cy); hbm2 = CreateCompatibleBitmap(hdc, siz.cx, siz.cy); hbmOld = SelectObject(hdcMem, hbm); rc.left = 0; rc.top = 0; rc.right = siz.cx; rc.bottom = siz.cy; FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(WHITE_BRUSH)); FillRgn(hdcMem, hRgn, (HBRUSH)GetStockObject(BLACK_BRUSH)); { hFontOld = SelectObject(hdcMem, hFont); SetTextColor(hdcMem, RGB(0, 0, 0)); SetBkColor(hdcMem, RGB(255, 255, 255)); SetBkMode(hdcMem, OPAQUE); DrawTextA(hdcMem, romaji, lstrlenA(romaji), &rc, DT_SINGLELINE | DT_RIGHT | DT_BOTTOM); SelectObject(hdcMem, hFontOld); } SelectObject(hdcMem, hbmOld); DeleteDC(hdcMem); ReleaseDC(g_hKakijunWnd, hdc); g_hbm2 = hbm; InvalidateRect(g_hKakijunWnd, NULL, FALSE); ShowWindow(g_hKakijunWnd, SW_SHOWNORMAL); Sleep(300); hRgn5 = CreateRectRgn(0, 0, 0, 0); PlaySound(MAKEINTRESOURCE(400), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); for (UINT i = 0; i < v.size(); i++) { switch (v[i].type) { case WAIT: Sleep(500); PlaySound(MAKEINTRESOURCE(400), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); break; case LINEAR: hdc = GetDC(g_hKakijunWnd); hdcMem = CreateCompatibleDC(hdc); hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); rc.left = 0; rc.top = 0; rc.right = siz.cx; rc.bottom = siz.cy; FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(WHITE_BRUSH)); FillRgn(hdcMem, hRgn, (HBRUSH)GetStockObject(BLACK_BRUSH)); { hFontOld = SelectObject(hdcMem, hFont); SetTextColor(hdcMem, RGB(0, 0, 0)); SetBkColor(hdcMem, RGB(255, 255, 255)); SetBkMode(hdcMem, OPAQUE); DrawTextA(hdcMem, romaji, lstrlenA(romaji), &rc, DT_SINGLELINE | DT_RIGHT | DT_BOTTOM); SelectObject(hdcMem, hFontOld); } SelectObject(hdcMem, hbmOld); hRgn2 = ExtCreateRegion(NULL, v[i].cb, (RGNDATA *)v[i].pb); cost = cos(v[i].angle0 * M_PI / 180); sint = sin(v[i].angle0 * M_PI / 180); for (k = -200; k < 200; k += 20) { apt[0].x = LONG(150 + k * cost + 150 * sint); apt[0].y = LONG(150 + k * sint - 150 * cost); apt[1].x = LONG(150 + k * cost - 150 * sint); apt[1].y = LONG(150 + k * sint + 150 * cost); apt[2].x = LONG(150 + (k + 20) * cost - 150 * sint); apt[2].y = LONG(150 + (k + 20) * sint + 150 * cost); apt[3].x = LONG(150 + (k + 20) * cost + 150 * sint); apt[3].y = LONG(150 + (k + 20) * sint - 150 * cost); BeginPath(hdcMem); Polygon(hdcMem, apt, 4); EndPath(hdcMem); hRgn3 = PathToRegion(hdcMem); hRgn4 = CreateRectRgn(0, 0, 0, 0); INT n = CombineRgn(hRgn4, hRgn2, hRgn3, RGN_AND); if (n != NULLREGION) { DeleteObject(hRgn4); break; } DeleteObject(hRgn4); } for ( ; k < 200; k += 20) { hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); apt[0].x = LONG(150 + k * cost + 150 * sint); apt[0].y = LONG(150 + k * sint - 150 * cost); apt[1].x = LONG(150 + k * cost - 150 * sint); apt[1].y = LONG(150 + k * sint + 150 * cost); apt[2].x = LONG(150 + (k + 20) * cost - 150 * sint); apt[2].y = LONG(150 + (k + 20) * sint + 150 * cost); apt[3].x = LONG(150 + (k + 20) * cost + 150 * sint); apt[3].y = LONG(150 + (k + 20) * sint - 150 * cost); BeginPath(hdcMem); Polygon(hdcMem, apt, 4); EndPath(hdcMem); hRgn3 = PathToRegion(hdcMem); hRgn4 = CreateRectRgn(0, 0, 0, 0); INT n = CombineRgn(hRgn4, hRgn2, hRgn3, RGN_AND); CombineRgn(hRgn5, hRgn5, hRgn4, RGN_OR); FillRgn(hdcMem, hRgn5, g_hbrRed); DeleteObject(hRgn4); SelectObject(hdcMem, hbmOld); InvalidateRect(g_hKakijunWnd, NULL, FALSE); if (n == NULLREGION) break; Sleep(35); } DeleteObject(hRgn2); DeleteDC(hdcMem); ReleaseDC(g_hKakijunWnd, hdc); break; case POLAR: hdc = GetDC(g_hKakijunWnd); hdcMem = CreateCompatibleDC(hdc); hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); rc.left = 0; rc.top = 0; rc.right = siz.cx; rc.bottom = siz.cy; FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(WHITE_BRUSH)); FillRgn(hdcMem, hRgn, (HBRUSH)GetStockObject(BLACK_BRUSH)); { hFontOld = SelectObject(hdcMem, hFont); SetTextColor(hdcMem, RGB(0, 0, 0)); SetBkColor(hdcMem, RGB(255, 255, 255)); SetBkMode(hdcMem, OPAQUE); DrawTextA(hdcMem, romaji, lstrlenA(romaji), &rc, DT_SINGLELINE | DT_RIGHT | DT_BOTTOM); SelectObject(hdcMem, hFontOld); } SelectObject(hdcMem, hbmOld); hRgn2 = ExtCreateRegion(NULL, v[i].cb, (RGNDATA *)v[i].pb); if (v[i].angle0 <= v[i].angle1) { for (k = v[i].angle0; k < v[i].angle1; k += 20) { double theta = k * M_PI / 180.0; double theta2 = (k + 20) * M_PI / 180.0; cost = cos(theta); sint = sin(theta); cost2 = cos(theta2); sint2 = sin(theta2); hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); apt[0].x = LONG(v[i].cx + 200 * cost); apt[0].y = LONG(v[i].cy + 200 * sint); apt[1].x = LONG(v[i].cx + 200 * cost2); apt[1].y = LONG(v[i].cy + 200 * sint2); apt[2].x = v[i].cx; apt[2].y = v[i].cy; BeginPath(hdcMem); Polygon(hdcMem, apt, 3); EndPath(hdcMem); hRgn3 = PathToRegion(hdcMem); hRgn4 = CreateRectRgn(0, 0, 0, 0); INT n = CombineRgn(hRgn4, hRgn2, hRgn3, RGN_AND); CombineRgn(hRgn5, hRgn5, hRgn4, RGN_OR); FillRgn(hdcMem, hRgn5, g_hbrRed); DeleteObject(hRgn4); SelectObject(hdcMem, hbmOld); InvalidateRect(g_hKakijunWnd, NULL, FALSE); if (n == NULLREGION) break; Sleep(35); } } else { for (k = v[i].angle0; k > v[i].angle1; k -= 20) { double theta = (k - 20) * M_PI / 180.0; double theta2 = k * M_PI / 180.0; cost = cos(theta); sint = sin(theta); cost2 = cos(theta2); sint2 = sin(theta2); hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); apt[0].x = LONG(v[i].cx + 200 * cost); apt[0].y = LONG(v[i].cy + 200 * sint); apt[1].x = LONG(v[i].cx + 200 * cost2); apt[1].y = LONG(v[i].cy + 200 * sint2); apt[2].x = v[i].cx; apt[2].y = v[i].cy; BeginPath(hdcMem); Polygon(hdcMem, apt, 3); EndPath(hdcMem); hRgn3 = PathToRegion(hdcMem); hRgn4 = CreateRectRgn(0, 0, 0, 0); INT n = CombineRgn(hRgn4, hRgn2, hRgn3, RGN_AND); CombineRgn(hRgn5, hRgn5, hRgn4, RGN_OR); FillRgn(hdcMem, hRgn5, g_hbrRed); DeleteObject(hRgn4); SelectObject(hdcMem, hbmOld); InvalidateRect(g_hKakijunWnd, NULL, FALSE); if (n == NULLREGION) break; Sleep(35); } } DeleteObject(hRgn2); DeleteDC(hdcMem); ReleaseDC(g_hKakijunWnd, hdc); break; } } DeleteObject(hRgn5); Sleep(500); PlaySound(MAKEINTRESOURCE(3000 + g_nMoji), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); hdc = GetDC(g_hKakijunWnd); hdcMem = CreateCompatibleDC(hdc); hbmTemp = hbm; hbm = hbm2; hbm2 = hbmTemp; g_hbm2 = hbm; hbmOld = SelectObject(hdcMem, hbm); rc.left = 0; rc.top = 0; rc.right = siz.cx; rc.bottom = siz.cy; FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(WHITE_BRUSH)); FillRgn(hdcMem, hRgn, g_hbrRed); { hFontOld = SelectObject(hdcMem, hFont); SetTextColor(hdcMem, RGB(0, 0, 0)); SetBkColor(hdcMem, RGB(255, 255, 255)); SetBkMode(hdcMem, OPAQUE); DrawTextA(hdcMem, romaji, lstrlenA(romaji), &rc, DT_SINGLELINE | DT_RIGHT | DT_BOTTOM); SelectObject(hdcMem, hFontOld); } SelectObject(hdcMem, hbmOld); DeleteDC(hdcMem); ReleaseDC(g_hKakijunWnd, hdc); InvalidateRect(g_hKakijunWnd, NULL, FALSE); Sleep(500); ShowWindow(g_hKakijunWnd, SW_HIDE); g_hbm2 = NULL; DeleteObject(hbm); DeleteObject(hbm2); DeleteObject(hFont); return 0; } VOID MojiOnClick(HWND hwnd, INT nMoji, BOOL fRight) { RECT rc, rc2; GetWindowRect(hwnd, &rc); GetWindowRect(g_hKakijunWnd, &rc2); MoveWindow(g_hKakijunWnd, rc.left + (rc.right - rc.left - (rc2.right - rc2.left)) / 2, rc.top + (rc.bottom - rc.top - (rc2.bottom - rc2.top)) / 2, rc2.right - rc2.left, rc2.bottom - rc2.top, TRUE); g_nMoji = nMoji; if (fRight) { HMENU hMenu = CreatePopupMenu(); AppendMenu(hMenu, MF_ENABLED | MF_STRING, 100 + nMoji, LoadStringDx(1000 + g_nMoji)); SetForegroundWindow(hwnd); POINT pt; GetCursorPos(&pt); INT nCmd = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, hwnd, NULL); SendMessage(hwnd, WM_COMMAND, nCmd, 0); DestroyMenu(hMenu); return; } if (g_fKatakana) g_katakana_history.insert(nMoji); else g_hiragana_history.insert(nMoji); if (g_hbm != NULL) DeleteObject(g_hbm); g_hbm = NULL; InvalidateRect(hwnd, NULL, FALSE); PlaySound(MAKEINTRESOURCE(3000 + nMoji), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); if (g_hThread != NULL) { TerminateThread(g_hThread, 0); CloseHandle(g_hThread); } g_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL); } VOID OnButtonDown(HWND hwnd, INT x, INT y, BOOL fRight) { INT i, j; POINT pt; RECT rc; SIZE siz; DWORD dw; GetClientRect(hwnd, &rc); siz.cx = rc.right - rc.left; siz.cy = rc.bottom - rc.top; dw = 0; GetExitCodeThread(g_hThread, &dw); if (dw == STILL_ACTIVE) return; pt.x = x; pt.y = y; SetRect(&rc, 160, 10, 160 + 200, 10 + 76); if (PtInRect(&rc, pt)) { g_fKatakana = FALSE; PlaySound(MAKEINTRESOURCE(300), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); if (g_hbm != NULL) DeleteObject(g_hbm); g_hbm = NULL; InvalidateRect(hwnd, NULL, FALSE); return; } SetRect(&rc, siz.cx - (160 + 200), 10, siz.cx - 160, 10 + 76); if (PtInRect(&rc, pt)) { g_fKatakana = TRUE; PlaySound(MAKEINTRESOURCE(350), g_hInstance, SND_ASYNC | SND_RESOURCE | SND_NODEFAULT); if (g_hbm != NULL) DeleteObject(g_hbm); g_hbm = NULL; InvalidateRect(hwnd, NULL, FALSE); return; } for (j = 0; j <= 100; j += 10) { if (j == 70) { i = 0; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } i = 2; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } i = 4; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } } else if (j == 90) { i = 0; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } i = 4; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } } else if (j == 100) { i = 4; rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } } else { for (i = 0; i < 5; i++) { rc.left = 685 - (j * 65) / 10 - 3; rc.top = i * 60 + 100 - 3; rc.right = rc.left + 50 + 6; rc.bottom = rc.top + 50 + 6; if (PtInRect(&rc, pt)) { MojiOnClick(hwnd, j + i, fRight); return; } } } } } BOOL Kakijun_OnEraseBkgnd(HWND hwnd, HDC hdc) { return TRUE; } VOID Kakijun_OnDraw(HWND hwnd, HDC hdc) { RECT rc; SIZE siz; HDC hdcMem; HGDIOBJ hbmOld; GetClientRect(hwnd, &rc); siz.cx = rc.right - rc.left; siz.cy = rc.bottom - rc.top; if (g_hbm2 != NULL) { hdcMem = CreateCompatibleDC(hdc); hbmOld = SelectObject(hdcMem, g_hbm2); BitBlt(hdc, 0, 0, siz.cx, siz.cy, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); } } void Kakijun_OnPaint(HWND hwnd) { PAINTSTRUCT ps; if (HDC hdc = BeginPaint(hwnd, &ps)) { Kakijun_OnDraw(hwnd, hdc); EndPaint(hwnd, &ps); } } LRESULT CALLBACK KakijunWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_ERASEBKGND, Kakijun_OnEraseBkgnd); HANDLE_MSG(hwnd, WM_PAINT, Kakijun_OnPaint); default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } INT_PTR CALLBACK AboutDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: EndDialog(hDlg, IDOK); break; case IDCANCEL: EndDialog(hDlg, IDCANCEL); break; } } return FALSE; } BOOL OnEraseBkgnd(HWND hwnd, HDC hdc) { return TRUE; } void OnPaint(HWND hwnd) { PAINTSTRUCT ps; if (HDC hdc = BeginPaint(hwnd, &ps)) { OnDraw(hwnd, hdc); EndPaint(hwnd, &ps); } } void OnLButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) { OnButtonDown(hwnd, x, y, FALSE); } void OnRButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) { OnButtonDown(hwnd, x, y, TRUE); } void OnSysCommand(HWND hwnd, UINT cmd, int x, int y) { if ((cmd & 0xFFF0) == 0x3330) { DialogBox(g_hInstance, MAKEINTRESOURCE(1), hwnd, AboutDialogProc); return; } FORWARD_WM_SYSCOMMAND(hwnd, cmd, x, y, DefWindowProc); } void OnDestroy(HWND hwnd) { if (g_hThread != NULL) { TerminateThread(g_hThread, 0); CloseHandle(g_hThread); } PostQuitMessage(0); } void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { if (id == 0) return; LPTSTR psz = LoadStringDx(2000 + g_nMoji); if (psz[0]) ShellExecute(hwnd, NULL, psz, NULL, NULL, SW_SHOWNORMAL); } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_CREATE, OnCreate); HANDLE_MSG(hwnd, WM_ERASEBKGND, OnEraseBkgnd); HANDLE_MSG(hwnd, WM_PAINT, OnPaint); HANDLE_MSG(hwnd, WM_LBUTTONDOWN, OnLButtonDown); HANDLE_MSG(hwnd, WM_RBUTTONDOWN, OnRButtonDown); HANDLE_MSG(hwnd, WM_COMMAND, OnCommand); HANDLE_MSG(hwnd, WM_SYSCOMMAND, OnSysCommand); HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy); default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } INT WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pszCmdLine, INT nCmdShow) { WNDCLASSEX wcx; MSG msg; BOOL f; g_hInstance = hInstance; wcx.cbSize = sizeof(WNDCLASSEX); wcx.style = 0; wcx.lpfnWndProc = WindowProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.hInstance = hInstance; wcx.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(1)); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); wcx.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255, 255, 192)); wcx.lpszMenuName = NULL; wcx.lpszClassName = g_szClassName; wcx.hIconSm = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(1), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0); if (!RegisterClassEx(&wcx)) return 1; wcx.style = CS_NOCLOSE; wcx.lpfnWndProc = KakijunWndProc; wcx.hIcon = NULL; wcx.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH); wcx.lpszClassName = g_szKakijunClassName; wcx.hIconSm = NULL; if (!RegisterClassEx(&wcx)) return 1; g_hMainWnd = CreateWindow(g_szClassName, LoadStringDx(1), WS_SYSMENU | WS_CAPTION | WS_OVERLAPPED, CW_USEDEFAULT, 0, 780, 430, NULL, NULL, hInstance, NULL); if (g_hMainWnd == NULL) { MessageBox(NULL, LoadStringDx(3), NULL, MB_ICONERROR); return 2; } ShowWindow(g_hMainWnd, nCmdShow); UpdateWindow(g_hMainWnd); while((f = GetMessage(&msg, NULL, 0, 0)) != FALSE) { if (f == -1) return -1; TranslateMessage(&msg); DispatchMessage(&msg); } return (INT)msg.wParam; }
33.254443
104
0.468022
[ "vector" ]
21143836574f4b5e430654803548b170a4d6d18a
4,375
cpp
C++
Source/ArticyEditor/Private/Customizations/Details/ArticyRefCustomization.cpp
ArticySoftware/ArticyUnrealImporter
e70c6b5dd060c93e9ad0fb5c730801c9eca63479
[ "MIT" ]
71
2017-09-12T14:58:41.000Z
2022-03-31T23:42:53.000Z
Source/ArticyEditor/Private/Customizations/Details/ArticyRefCustomization.cpp
ArticySoftware/ArticyUnrealImporter
e70c6b5dd060c93e9ad0fb5c730801c9eca63479
[ "MIT" ]
38
2017-09-19T04:56:57.000Z
2022-01-25T17:55:38.000Z
Source/ArticyEditor/Private/Customizations/Details/ArticyRefCustomization.cpp
ArticySoftware/ArticyUnrealImporter
e70c6b5dd060c93e9ad0fb5c730801c9eca63479
[ "MIT" ]
25
2017-09-22T10:40:03.000Z
2021-08-25T12:39:22.000Z
// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "Customizations/Details/ArticyRefCustomization.h" #include "ArticyFunctionLibrary.h" #include "IDetailChildrenBuilder.h" #include "DetailWidgetRow.h" #include "ArticyObject.h" #include "ArticyRef.h" #include "UObject/ConstructorHelpers.h" #include "Slate/UserInterfaceHelperFunctions.h" #include "EditorCategoryUtils.h" TSharedRef<IPropertyTypeCustomization> FArticyRefCustomization::MakeInstance() { return MakeShareable(new FArticyRefCustomization()); } void FArticyRefCustomization::CustomizeHeader(TSharedRef<IPropertyHandle> PropertyHandle, FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& CustomizationUtils) { ArticyRefPropertyHandle = PropertyHandle; ; ArticyRefPropertyWidget = SNew(SArticyRefProperty) .ArticyRefToDisplay(this, &FArticyRefCustomization::GetArticyRef) .OnArticyRefChanged(this, &FArticyRefCustomization::OnArticyRefChanged) .TopLevelClassRestriction(this, &FArticyRefCustomization::GetClassRestriction) .bExactClass(IsExactClass()) .bExactClassEditable(!HasExactClassMetaData()) .bIsReadOnly(this, &FArticyRefCustomization::IsReadOnly); HeaderRow.NameContent() [ ArticyRefPropertyHandle->CreatePropertyNameWidget() ] .ValueContent() .MinDesiredWidth(150) [ ArticyRefPropertyWidget.ToSharedRef() ]; } void FArticyRefCustomization::CustomizeChildren(TSharedRef<IPropertyHandle> PropertyHandle, IDetailChildrenBuilder& ChildBuilder, IPropertyTypeCustomizationUtils& CustomizationUtils) { // dont do children } FArticyRef* FArticyRefCustomization::RetrieveArticyRef(IPropertyHandle* ArticyRefHandle) { FArticyRef* ArticyRef = nullptr; void* ArticyRefAddress; ArticyRefHandle->GetValueData(ArticyRefAddress); ArticyRef = static_cast<FArticyRef*>(ArticyRefAddress); return ArticyRef; } FArticyRef FArticyRefCustomization::GetArticyRef() const { FArticyRef* ArticyRef = RetrieveArticyRef(ArticyRefPropertyHandle.Get()); return ArticyRef ? *ArticyRef : FArticyRef(); } void FArticyRefCustomization::OnArticyRefChanged(const FArticyRef& NewArticyRef) const { // update the articy ref with the new ID: // done via Set functions instead of accessing the ref object directly because using "Set" handles various Unreal logic, such as: // - CDO default change forwarding to instances // - marking dirty // - transaction buffer (Undo, Redo) ArticyRefPropertyHandle->SetValueFromFormattedString(NewArticyRef.ToString()); } UClass* FArticyRefCustomization::GetClassRestriction() const { UClass* Restriction = nullptr; if (HasClassRestrictionMetaData()) { const FString ArticyClassRestriction = ArticyRefPropertyHandle->GetMetaData("ArticyClassRestriction"); auto FullClassName = FString::Printf(TEXT("Class'/Script/%s.%s'"), TEXT("ArticyRuntime"), *ArticyClassRestriction); Restriction = ConstructorHelpersInternal::FindOrLoadClass(FullClassName, UArticyObject::StaticClass()); // the class name can be in the ArticyRuntime module or in the project module. If it wasn't found in ArticyRuntime, check the project module if (Restriction == nullptr) { FullClassName = FString::Printf(TEXT("Class'/Script/%s.%s'"), FApp::GetProjectName(), *ArticyClassRestriction); Restriction = ConstructorHelpersInternal::FindOrLoadClass(FullClassName, UArticyObject::StaticClass()); } } if (Restriction == nullptr) { Restriction = UArticyObject::StaticClass(); } return Restriction; } bool FArticyRefCustomization::HasClassRestrictionMetaData() const { return ArticyRefPropertyHandle->HasMetaData(TEXT("ArticyClassRestriction")); } bool FArticyRefCustomization::IsExactClass() const { if(HasExactClassMetaData()) { return ArticyRefPropertyHandle->GetBoolMetaData(TEXT("ArticyExactClass")); } return false; } bool FArticyRefCustomization::IsReadOnly() const { return ArticyRefPropertyHandle->GetNumPerObjectValues() != 1 || ArticyRefPropertyHandle->IsEditConst(); } bool FArticyRefCustomization::HasExactClassMetaData() const { return ArticyRefPropertyHandle->HasMetaData(TEXT("ArticyExactClass")); } FArticyId FArticyRefCustomization::GetIdFromValueString(FString SourceString) { int32 Low, High = 0; const bool bSuccess = FParse::Value(*SourceString, TEXT("Low="), Low) && FParse::Value(*SourceString, TEXT("High="), High); FArticyId Id; Id.High = High; Id.Low = Low; return Id; }
32.407407
182
0.794057
[ "object" ]
211585fff5d7012d709a0d610d21275d076d1aa6
2,318
cpp
C++
fw/source/numerical/ParametricSurfaceMeshBuilder.cpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
fw/source/numerical/ParametricSurfaceMeshBuilder.cpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
9
2016-12-09T13:02:18.000Z
2019-09-13T09:29:18.000Z
fw/source/numerical/ParametricSurfaceMeshBuilder.cpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
#include "fw/numerical/ParametricSurfaceMeshBuilder.hpp" #include "fw/numerical/IParametricSurfaceUV.hpp" #include "Mesh.hpp" #include "Vertices.hpp" #include <iostream> #include <vector> #include <glm/glm.hpp> namespace fw { ParametricSurfaceMeshBuilder::ParametricSurfaceMeshBuilder() { } ParametricSurfaceMeshBuilder::~ParametricSurfaceMeshBuilder() { } void ParametricSurfaceMeshBuilder::setSamplingResolution( glm::ivec2 samplingResolution ) { _samplingResolution = samplingResolution; } glm::ivec2 ParametricSurfaceMeshBuilder::getSamplingResolution() const { return _samplingResolution; } std::shared_ptr<Mesh<VertexNormalTexCoords>> ParametricSurfaceMeshBuilder::build( std::shared_ptr<IParametricSurfaceUV> surface, glm::dvec2 minimumParameter, glm::dvec2 maximumParameter ) const { std::vector<VertexNormalTexCoords> vertices; std::vector<GLuint> indices; vertices.reserve(_samplingResolution.x * _samplingResolution.y); for (auto y = 0; y < _samplingResolution.y; ++y) { auto dy = static_cast<double>(y)/(_samplingResolution.y - 1); for (auto x = 0; x < _samplingResolution.x; ++x) { auto dx = static_cast<double>(x)/(_samplingResolution.x - 1); glm::dvec2 dp { dx, dy }; glm::dvec2 parametrisation = glm::mix(minimumParameter, maximumParameter, dp); auto position = surface->getPosition(parametrisation); auto normal = surface->getNormal(parametrisation); vertices.push_back({ glm::vec3(position), glm::vec3(normal), glm::vec2(dp) }); } } for (auto y = 0; y < _samplingResolution.y - 1; ++y) { for (auto x = 0; x < _samplingResolution.x - 1; ++x) { auto baseIndex = y * _samplingResolution.x + x; indices.push_back(baseIndex); indices.push_back(baseIndex+1); indices.push_back(baseIndex+_samplingResolution.x); indices.push_back(baseIndex+1); indices.push_back(baseIndex+_samplingResolution.x); indices.push_back(baseIndex+_samplingResolution.x+1); } } return std::make_shared<Mesh<VertexNormalTexCoords>>(vertices, indices); } }
26.953488
76
0.652286
[ "mesh", "vector" ]
21158ab916d853921c68d2ddc447553c9aa9814f
1,022
cpp
C++
BFS.cpp
sanjeev30798/Hacktoberfest2020
9aee25770b79101b6e5ca19de107cca21d24b7b5
[ "MIT" ]
null
null
null
BFS.cpp
sanjeev30798/Hacktoberfest2020
9aee25770b79101b6e5ca19de107cca21d24b7b5
[ "MIT" ]
1
2020-10-02T05:19:47.000Z
2020-10-02T05:19:47.000Z
BFS.cpp
sanjeev30798/Hacktoberfest2020
9aee25770b79101b6e5ca19de107cca21d24b7b5
[ "MIT" ]
1
2020-10-02T03:40:13.000Z
2020-10-02T03:40:13.000Z
#include<bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin>>t; while(t--) { int n,m; cin>>n>>m; // number of nodes and edges vector<int> adj[n+1]; deque<int> q; int i; q.push_back(1); // starting node 1 for(i=0;i<m;++i) { int e1,e2; cin>>e1>>e2; adj[e1].push_back(e2); // undirected graph adj[e2].push_back(e1); // undirected graph } bool b[n]; memset(b,false,sizeof b); b[1]=true; while(q.size()!=0) { int y=q.front(); cout<<y<<" "; q.pop_front(); for(i=0;i<adj[y].size();i++) { if(b[adj[y][i]]==false) { b[adj[y][i]]=true; q.push_back(adj[y][i]); } } } } }
23.767442
55
0.365949
[ "vector" ]
21177c3588481354e9629a31e1fb6cf859b6f86f
2,991
hpp
C++
sdl/Hypergraph/ParserUtil.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/ParserUtil.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/ParserUtil.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // 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. /** \file structures built by parser (then used to build states and arcs for a hypergraph). */ #ifndef HYP__HYPERGRAPH_PARSERUTIL_HPP #define HYP__HYPERGRAPH_PARSERUTIL_HPP #pragma once #include <sdl/Hypergraph/Types.hpp> #include <boost/optional.hpp> #include <string> #include <vector> namespace sdl { namespace Hypergraph { namespace ParserUtil { // State and Arc hold information about the actual states and arcs // parsed. We are using these wrappers instead of the real Arcs // because otherwise we'd have to template the parser on the arc. // TODO: Field instead of string (0 copy) - but then need to translate each arc // as you go, which means custom spirit actions instead of just relying on // attributes+fusion struct State { State() : id(kNoState), isInputSymbolLexical(false), isOutputSymbolLexical(false) {} State(StateId i) : id(i), isInputSymbolLexical(false), isOutputSymbolLexical(false) {} StateId id; /// if empty / unset then we assume an unlabeled state (use <eps> instead of empty string when you mean /// empty string) std::string inputSymbol; /// if empty / unset, output sym is same as input (use <eps> instead of empty string when you mean empty /// string) std::string outputSymbol; bool isInputSymbolLexical; bool isOutputSymbolLexical; static const StateId kStart = kNoState - 1; static const StateId kFinal = kNoState - 2; bool hasId() const { return id != kNoState && id != kStart && id != kFinal; } void increaseMaxId(StateId& maxId) const { if (!hasId()) return; if (maxId < id) maxId = id; } template <class Out> void print(Out& out) const { char const* inQuote = isInputSymbolLexical ? "\"" : ""; char const* outQuote = isOutputSymbolLexical ? "\"" : ""; out << id << '(' << inQuote << inputSymbol << inQuote << ' ' << outQuote << outputSymbol << outQuote << ')'; } template <class C, class T> friend std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, State const& self) { self.print(out); return out; } template <class C, class T> friend std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, State const* selfp) { out << "State@0x" << (void*)selfp << ": "; if (selfp) selfp->print(out); return out; } }; struct Arc { State head; Arc() : head(kNoState) {} std::vector<State> tails; std::string weightStr; }; }}} #endif
30.835052
112
0.694082
[ "vector" ]
211e40b2af9b8e93d90950a40087abc730669c78
1,285
cpp
C++
1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.cpp
shreydevep/SpojList
c6436525fc26824e7d3b604aba40640d9b25aed2
[ "MIT" ]
null
null
null
1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.cpp
shreydevep/SpojList
c6436525fc26824e7d3b604aba40640d9b25aed2
[ "MIT" ]
null
null
null
1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.cpp
shreydevep/SpojList
c6436525fc26824e7d3b604aba40640d9b25aed2
[ "MIT" ]
null
null
null
class Solution { public: int furthestBuilding(vector<int>& heights, int bricks, int ladders) { int ans = 0; multiset<int> usedBricks; for(int i=1;i<heights.size();++i){ if(heights[i] > heights[i-1]){ //Ladder or Brick int req = abs(heights[i]-heights[i-1]); if(ladders > 0){ usedBricks.insert(req); ladders--; ans = i; } else{ auto itr = usedBricks.begin(); if(usedBricks.size() > 0 && *itr <= bricks && *itr <= req){ bricks -= (*itr); usedBricks.erase(usedBricks.find(*itr)); usedBricks.insert(req); ans = i; } else if(req <= bricks){ bricks -= req; ans = i; } else{ break; } } } else{ ans = i; } } return ans; } };
29.204545
79
0.308171
[ "vector" ]
211ffaf598e58132afc966b7e62581d7ac00783d
981
cc
C++
JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" #include "JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h" namespace npstat { void StorableMultivariateFunctor::validateDescription( const std::string& description) const { if (description_ != description) { std::string mesage = "In StorableMultivariateFunctor::validateDescription: " "argument description string \""; mesage += description; mesage += "\" is different from the object description string \""; mesage += description_; mesage += "\""; throw npstat::NpstatRuntimeError(mesage.c_str()); } } StorableMultivariateFunctor* StorableMultivariateFunctor::read( const gs::ClassId& id, std::istream& in) { return StaticStorableMultivariateFunctorReader::instance().read(id, in); } }
35.035714
94
0.649337
[ "object" ]
21303de8eee6eb9a69bd9cbd6d999616b81bcc11
2,721
cc
C++
algo/pyq/Find Substring/1.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
1
2017-10-14T04:23:45.000Z
2017-10-14T04:23:45.000Z
algo/pyq/Find Substring/1.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
null
null
null
algo/pyq/Find Substring/1.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
null
null
null
/* * * string s1 = "waeginsapnaabangpisebbasepgnccccapisdnfngaabndlrjngeuiogbbegbuoecccc"; * * string s2 = "a+b+c-"; * * s2的形式是一个字母加上一个符号,正号代表有两个前面的字符,负号代表有四个,也就是 * 说s2其实是"aabbcccc", 不考虑invalid. * * 在s1中,找出连续或者不连续的s2,也就是说从s1中找出"aa....bb.....cccc", abc顺序不能变, * 但是中间可以有零个或者多个字符,返回工作共有多少个。在上面这个鸽子中,有四个。 */ /* * * First we can simplify it to a similar problem * * * s1 = "abcabc" * * s2 = "abc". * * Find number of occurrences of s2 in s1. * */ #include <vector> #include <string> #include <iostream> using namespace std; /* * dp[i][j]: numSubstrs(s1[i:], s2[j:]) * dp[s1.length()][s2.length()] = 1; * if (s1[i] == s2[j]) { * dp[i][j] = dp[i+1][j+1] // match i and j * + dp[i+1][j]; // not match i and j * } else { * dp[i][j] = dp[i+1][j] * } * */ int numSubstrs(string s1, string s2) { vector<vector<int>> dp(2, vector<int>(s2.length()+1, 0)); // initially, s2[s2.length():] is empty, so every substring of s1 // contain it once. dp[0][s2.length()] = 1; dp[1][s2.length()] = 1; for (int i = s1.length()-1; i>=0; i--) { for (int j = s2.length()-1; j >= 0; j--) { if (s1[i] == s2[j]) { dp[i%2][j] = dp[(i+1)%2][j+1] // match i and j + dp[(i+1)%2][j]; // not match i and j } else { dp[i%2][j] = dp[(i+1)%2][j]; // not match i and j } // cout << i << " " << j << " " << dp[i%2][j] << endl; } } return dp[0][0]; } /* * * This question is similar. The only difference is that we need to * compare each unit of s2(a+, b+, a-) instead of each character. */ /* match a unit from s2 at s1 starting at i. return true for matching */ inline bool unitEqual(const string &s1, int i, const string &s2, int j) { /* count: number of chars */ int count = (s2[j+1] == '+')?2:4; for (int num = 0; num < count; num++) { if (s1[i+num] != s2[j]) return false; } return true; } int numSubstrs1(string s1, string s2) { // each unit is a single block that we need to match. // For example, for unit a+, we should match aa, // for unit a-, we should match aaaa int num_units = s2.length() / 2; vector<vector<int>> dp(2, vector<int>(num_units+1, 0)); dp[0][num_units] = 1; dp[1][num_units] = 1; for (int i = s1.length() - 2; i >= 0; i -= 1) { for (int j = s2.length() - 2; j >= 0; j-=2) { int unit_idx = j / 2; if (unitEqual(s1, i, s2, j)) { dp[i%2][unit_idx] = dp[(i+1)%2][unit_idx+1] + dp[(i+1)%2][unit_idx]; } else { dp[i%2][unit_idx] = dp[(i+1)%2][unit_idx]; } } } return dp[0][0]; } int main() { cout << numSubstrs1("waeginsapnaabangpisebbasepgnccccapisdnfngaabndlrjngeuiogbbegbuoecccc", "a+b+c-") << endl; return 0; }
23.66087
112
0.552003
[ "vector" ]
2132a27f2c0f55a07ee14ed3602c7bd69e9e3999
71,599
hh
C++
src/Field/FieldInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Field/FieldInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Field/FieldInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
#include "Field/FieldBase.hh" #include "Geometry/Dimension.hh" #include "NodeList/NodeList.hh" #include "Field/NodeIterators.hh" #include "Utilities/packElement.hh" #include "Utilities/removeElements.hh" #include "Utilities/safeInv.hh" #include "Utilities/allReduce.hh" #include "Distributed/Communicator.hh" #include <cmath> #include <iostream> #include <algorithm> #include <numeric> #include <sstream> #include <limits> #ifdef USE_MPI extern "C" { #include <mpi.h> } #endif // Inlined methods. namespace Spheral { // Construct with name. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>:: Field(typename FieldBase<Dimension>::FieldName name): FieldBase<Dimension>(name), mDataArray(), mValid(false) {} //------------------------------------------------------------------------------ // Construct with name and field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>:: Field(typename FieldBase<Dimension>::FieldName name, const Field<Dimension, DataType>& field): FieldBase<Dimension>(name, *field.nodeListPtr()), mDataArray(field.mDataArray), mValid(field.mValid) {} //------------------------------------------------------------------------------ // Construct with the given name and NodeList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>:: Field(typename FieldBase<Dimension>::FieldName name, const NodeList<Dimension>& nodeList): FieldBase<Dimension>(name, nodeList), mDataArray((size_t) nodeList.numNodes(), DataType()), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); } template<> inline Field<Dim<1>, Dim<1>::Scalar>:: Field(FieldBase<Dim<1> >::FieldName name, const NodeList<Dim<1> >& nodeList): FieldBase<Dim<1> >(name, nodeList), mDataArray((size_t) nodeList.numNodes(), 0.0), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); } template<> inline Field<Dim<2>, Dim<2>::Scalar>:: Field(FieldBase<Dim<2> >::FieldName name, const NodeList<Dim<2> >& nodeList): FieldBase<Dim<2> >(name, nodeList), mDataArray((size_t) nodeList.numNodes(), 0.0), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); } template<> inline Field<Dim<3>, Dim<3>::Scalar>:: Field(FieldBase<Dim<3> >::FieldName name, const NodeList<Dim<3> >& nodeList): FieldBase<Dim<3> >(name, nodeList), mDataArray((size_t) nodeList.numNodes(), 0.0), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); } //------------------------------------------------------------------------------ // Construct with given name, NodeList, and value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>:: Field(typename FieldBase<Dimension>::FieldName name, const NodeList<Dimension>& nodeList, DataType value): FieldBase<Dimension>(name, nodeList), mDataArray((size_t) nodeList.numNodes(), value), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); } //------------------------------------------------------------------------------ // Construct for a given name, NodeList, and vector of values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>:: Field(typename FieldBase<Dimension>::FieldName name, const NodeList<Dimension>& nodeList, const std::vector<DataType,DataAllocator<DataType>>& array): FieldBase<Dimension>(name, nodeList), mDataArray((size_t) nodeList.numNodes()), mValid(true) { REQUIRE(numElements() == nodeList.numNodes()); REQUIRE(numElements() == array.size()); mDataArray = array; } //------------------------------------------------------------------------------ // Construct by copying the values of another Field, but using a different // node list. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>::Field(const NodeList<Dimension>& nodeList, const Field<Dimension, DataType>& field): FieldBase<Dimension>(field.name(), nodeList), mDataArray(field.mDataArray), mValid(true) { ENSURE(numElements() == nodeList.numNodes()); } //------------------------------------------------------------------------------ // Copy Constructor. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>::Field(const Field& field): FieldBase<Dimension>(field), mDataArray(field.mDataArray), mValid(field.valid()) { } //------------------------------------------------------------------------------ // The virtual clone method, allowing us to duplicate fields with just // FieldBase*. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::shared_ptr<FieldBase<Dimension> > Field<Dimension, DataType>::clone() const { return std::shared_ptr<FieldBase<Dimension>>(new Field<Dimension, DataType>(*this)); } //------------------------------------------------------------------------------ // Destructor. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>::~Field() { } //------------------------------------------------------------------------------ // Assignment operator with FieldBase. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldBase<Dimension>& Field<Dimension, DataType>::operator=(const FieldBase<Dimension>& rhs) { if (this != &rhs) { try { const Field<Dimension, DataType>* rhsPtr = dynamic_cast<const Field<Dimension, DataType>*>(&rhs); CHECK2(rhsPtr != 0, "Passed incorrect Field to operator=!"); FieldBase<Dimension>::operator=(rhs); mDataArray = rhsPtr->mDataArray; mValid = rhsPtr->mValid; } catch (const std::bad_cast &) { VERIFY2(false, "Attempt to assign a field to an incompatible field type."); } } return *this; } //------------------------------------------------------------------------------ // Assignment operator to another Field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator=(const Field<Dimension, DataType>& rhs) { REQUIRE(rhs.valid()); if (this != &rhs) { FieldBase<Dimension>::operator=(rhs); mDataArray = rhs.mDataArray; mValid = rhs.mValid; } return *this; } //------------------------------------------------------------------------------ // Assigment operator with a vector. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator=(const std::vector<DataType,DataAllocator<DataType>>& rhs) { REQUIRE(mValid); REQUIRE(this->nodeList().numNodes() == rhs.size()); mDataArray = rhs; return *this; } //------------------------------------------------------------------------------ // Assignment operator with a constant value of DataType //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator=(const DataType& rhs) { REQUIRE(mValid); std::fill(begin(), end(), rhs); return *this; } //------------------------------------------------------------------------------ // Test equivalence with a FieldBase. //------------------------------------------------------------------------------ template<typename Value> struct CrappyFieldCompareMethod { static bool compare(const std::vector<Value,DataAllocator<Value>>& lhs, const std::vector<Value,DataAllocator<Value>>& rhs) { return lhs == rhs; } }; template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>::operator==(const FieldBase<Dimension>& rhs) const { if (this->name() != rhs.name()) return false; if (this->nodeListPtr() != rhs.nodeListPtr()) return false; try { const Field<Dimension, DataType>* rhsPtr = dynamic_cast<const Field<Dimension, DataType>*>(&rhs); if (rhsPtr == 0) return false; return CrappyFieldCompareMethod<DataType>::compare(mDataArray, rhsPtr->mDataArray); } catch (const std::bad_cast &) { return false; } } //------------------------------------------------------------------------------ // Element access by integer index. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& Field<Dimension, DataType>::operator()(int index) { CHECK(index >= 0 && index < (int)numElements()); return mDataArray[index]; } template<typename Dimension, typename DataType> inline const DataType& Field<Dimension, DataType>::operator()(int index) const { CHECK(index >= 0 && index < (int)numElements()); return mDataArray[index]; } //------------------------------------------------------------------------------ // at version, for consistency with STL interface. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& Field<Dimension, DataType>::at(int index) { return this->operator()(index); } template<typename Dimension, typename DataType> inline const DataType& Field<Dimension, DataType>::at(int index) const { return this->operator()(index); } //------------------------------------------------------------------------------ // Element access by Node ID iterator. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& Field<Dimension, DataType>:: operator()(const NodeIteratorBase<Dimension>& itr) { CHECK(itr.nodeListPtr() == this->nodeListPtr()); CHECK(itr.nodeID() >= 0 && itr.nodeID() < numElements()); return mDataArray[itr.nodeID()]; } template<typename Dimension, typename DataType> inline const DataType& Field<Dimension, DataType>:: operator()(const NodeIteratorBase<Dimension>& itr) const { CHECK(itr.nodeListPtr() == this->nodeListPtr()); CHECK(itr.nodeID() >= 0 && itr.nodeID() < numElements()); return mDataArray[itr.nodeID()]; } // //------------------------------------------------------------------------------ // // Element access by CoarseNodeIterator. // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // inline // DataType& // Field<Dimension, DataType>:: // operator()(const CoarseNodeIterator<Dimension>& itr) { // CHECK(itr.nodeListPtr() == nodeListPtr()); // if (mNewCoarseNodes) { // cacheCoarseValues(); // mNewCoarseNodes = false; // } // CHECK(itr.cacheID() >= 0 && itr.cacheID() < mCoarseCache.size()); // return mCoarseCache[itr.cacheID()]; // } // template<typename Dimension, typename DataType> // inline // const DataType& // Field<Dimension, DataType>:: // operator()(const CoarseNodeIterator<Dimension>& itr) const { // CHECK(itr.nodeListPtr() == nodeListPtr()); // if (mNewCoarseNodes) { // cacheCoarseValues(); // mNewCoarseNodes = false; // } // CHECK(itr.cacheID() >= 0 && itr.cacheID() < mCoarseCache.size()); // return mCoarseCache[itr.cacheID()]; // } // //------------------------------------------------------------------------------ // // Element access by RefineNodeIterator. // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // inline // DataType& // Field<Dimension, DataType>:: // operator()(const RefineNodeIterator<Dimension>& itr) { // CHECK(itr.nodeListPtr() == nodeListPtr()); // if (mNewRefineNodes) { // cacheRefineValues(); // mNewRefineNodes = false; // } // CHECK(itr.cacheID() >= 0 && itr.cacheID() < mRefineCache.size()); // return mRefineCache[itr.cacheID()]; // } // template<typename Dimension, typename DataType> // inline // const DataType& // Field<Dimension, DataType>:: // operator()(const RefineNodeIterator<Dimension>& itr) const { // CHECK(itr.nodeListPtr() == nodeListPtr()); // if (mNewRefineNodes) { // cacheRefineValues(); // mNewRefineNodes = false; // } // CHECK(itr.cacheID() >= 0 && itr.cacheID() < mRefineCache.size()); // return mRefineCache[itr.cacheID()]; // } //------------------------------------------------------------------------------ // Number of elements in the field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline unsigned Field<Dimension, DataType>::numElements() const { return mDataArray.size(); } template<typename Dimension, typename DataType> inline unsigned Field<Dimension, DataType>::numInternalElements() const { return this->nodeList().numInternalNodes(); } template<typename Dimension, typename DataType> inline unsigned Field<Dimension, DataType>::numGhostElements() const { return this->nodeList().numGhostNodes(); } template<typename Dimension, typename DataType> inline unsigned Field<Dimension, DataType>::size() const { return numElements(); } //------------------------------------------------------------------------------ // Zero out the field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::Zero() { REQUIRE(mValid); std::fill(begin(), end(), DataTypeTraits<DataType>::zero()); } //------------------------------------------------------------------------------ // Apply a minimum value to the Field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::applyMin(const DataType& dataMin) { REQUIRE(mValid); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) mDataArray[i] = std::max(mDataArray[i], dataMin); } //------------------------------------------------------------------------------ // Apply a maximum value to the Field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::applyMax(const DataType& dataMax) { REQUIRE(mValid); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) mDataArray[i] = std::min(mDataArray[i], dataMax); } //------------------------------------------------------------------------------ // Apply a (double) minimum value to the Field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::applyScalarMin(const double dataMin) { REQUIRE(mValid); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) mDataArray[i] = std::max(mDataArray[i], dataMin); } //------------------------------------------------------------------------------ // Apply a (double) maximum value to the Field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::applyScalarMax(const double dataMax) { REQUIRE(mValid); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) mDataArray[i] = std::min(mDataArray[i], dataMax); } //------------------------------------------------------------------------------ // Addition with another field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>::operator+(const Field<Dimension, DataType>& rhs) const { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); Field<Dimension, DataType> result(*this); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) result(i) += rhs(i); return result; } //------------------------------------------------------------------------------ // Subtract another field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>::operator-(const Field<Dimension, DataType>& rhs) const { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); Field<Dimension, DataType> result(*this); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) result(i) -= rhs(i); return result; } //------------------------------------------------------------------------------ // Addition with another field in place //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator+=(const Field<Dimension, DataType>& rhs) { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) += rhs(i); return *this; } //------------------------------------------------------------------------------ // Subtract another field from this one in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator-=(const Field<Dimension, DataType>& rhs) { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) -= rhs(i); return *this; } //------------------------------------------------------------------------------ // Add a single value to every element of a field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>::operator+(const DataType& rhs) const { REQUIRE(valid()); Field<Dimension, DataType> result(*this); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) result(i) += rhs; return result; } //------------------------------------------------------------------------------ // Subtract a single value from every element of a field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>::operator-(const DataType& rhs) const { REQUIRE(valid()); Field<Dimension, DataType> result(*this); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) result(i) -= rhs; return result; } //------------------------------------------------------------------------------ // Addition with a single value in place //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator+=(const DataType& rhs) { REQUIRE(valid()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) += rhs; return *this; } //------------------------------------------------------------------------------ // Subtract a single value in place //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>::operator-=(const DataType& rhs) { REQUIRE(valid()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) -= rhs; return *this; } //------------------------------------------------------------------------------ // Multiplication by another Field in place. Only meaningful when multiplying // by a scalar field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>:: operator*=(const Field<Dimension, Scalar>& rhs) { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) *= rhs(i); return *this; } //------------------------------------------------------------------------------ // Multiplication by a Scalar in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>:: operator*=(const Scalar& rhs) { REQUIRE(valid()); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) (*this)(i) *= rhs; return *this; } //------------------------------------------------------------------------------ // Division by another Field. // Only meaningful for Scalar Fields! //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>:: operator/(const Field<Dimension, typename Dimension::Scalar>& rhs) const { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); Field<Dimension, DataType> result(*this); const unsigned n = this->numElements(); for (unsigned i = 0; i != n; ++i) { result(i) *= safeInvVar(rhs(i), 1.0e-60); } return result; } //------------------------------------------------------------------------------ // Division by another Field in place. // Only meaningful for Scalar Fields! //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>:: operator/=(const Field<Dimension, typename Dimension::Scalar>& rhs) { REQUIRE(valid() && rhs.valid()); REQUIRE(this->nodeListPtr() == rhs.nodeListPtr()); const unsigned n = this->numElements(); for (auto i = 0u; i < n; ++i) { (*this)(i) *= safeInvVar(rhs(i), 1.0e-60); } return *this; } //------------------------------------------------------------------------------ // Division by a Scalar value. //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline Field<Dimension, DataType> Field<Dimension, DataType>:: operator/(const Scalar& rhs) const { REQUIRE(valid()); REQUIRE(rhs != 0.0); Field<Dimension, DataType> result(*this); result /= rhs; return result; } //------------------------------------------------------------------------------ // Division by a Scalar value in place. //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline Field<Dimension, DataType>& Field<Dimension, DataType>:: operator/=(const Scalar& rhs) { REQUIRE(valid()); REQUIRE(rhs != 0.0); const unsigned n = this->numElements(); for (int i = 0; i < (int)n; ++i) { (*this)(i) /= rhs; } return *this; } //------------------------------------------------------------------------------ // Sum the elements of the field (assumes the DataType::operator+= is // available). //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: sumElements() const { return allReduce(this->localSumElements(), MPI_SUM, Communicator::communicator()); } //------------------------------------------------------------------------------ // Minimum. //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: min() const { return allReduce(this->localMin(), MPI_MIN, Communicator::communicator()); } //------------------------------------------------------------------------------ // Maximum. //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: max() const { return allReduce(this->localMax(), MPI_MAX, Communicator::communicator()); } //------------------------------------------------------------------------------ // Sum the elements of the field (assumes the DataType::operator+= is // available). // LOCAL to processor! //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: localSumElements() const { return std::accumulate(begin(), begin() + numInternalElements(), DataTypeTraits<DataType>::zero()); } //------------------------------------------------------------------------------ // Minimum. // LOCAL to processor! //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: localMin() const { DataType result; if (size() == 0) { result = std::numeric_limits<DataType>::max(); } else { result = *std::min_element(begin(), begin() + numInternalElements()); } return result; } //------------------------------------------------------------------------------ // Maximum. // LOCAL to processor! //------------------------------------------------------------------------------- template<typename Dimension, typename DataType> inline DataType Field<Dimension, DataType>:: localMax() const { DataType result; if (size() == 0) { result = -std::numeric_limits<DataType>::max() < std::numeric_limits<DataType>::min() ? -std::numeric_limits<DataType>::max() : std::numeric_limits<DataType>::min(); } else { result = *std::max_element(begin(), begin() + numInternalElements()); } return result; } //------------------------------------------------------------------------------ // operator==(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator==(const Field<Dimension, DataType>& rhs) const { const auto n = this->size(); if (n != rhs.size()) return false; auto result = true; auto i = 0; while (i < (int)n and result) { result = (*this)(i) == rhs(i); } return result; } //------------------------------------------------------------------------------ // operator!=(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator!=(const Field<Dimension, DataType>& rhs) const { return !((*this) == rhs); } //------------------------------------------------------------------------------ // operator>(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator>(const Field<Dimension, DataType>& rhs) const { if (this->size() != rhs.size()) return false; bool result = true; const_iterator lhsItr = this->begin(); const_iterator rhsItr = rhs.begin(); while (lhsItr < this->end() && result) { result = *lhsItr > *rhsItr; ++lhsItr; ++rhsItr; } return result; } //------------------------------------------------------------------------------ // operator<(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator<(const Field<Dimension, DataType>& rhs) const { if (this->size() != rhs.size()) return false; bool result = true; const_iterator lhsItr = this->begin(); const_iterator rhsItr = rhs.begin(); while (lhsItr < this->end() && result) { result = *lhsItr < *rhsItr; ++lhsItr; ++rhsItr; } return result; } //------------------------------------------------------------------------------ // operator>=(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator>=(const Field<Dimension, DataType>& rhs) const { if (this->size() != rhs.size()) return false; bool result = true; const_iterator lhsItr = this->begin(); const_iterator rhsItr = rhs.begin(); while (lhsItr < this->end() && result) { result = *lhsItr >= *rhsItr; ++lhsItr; ++rhsItr; } return result; } //------------------------------------------------------------------------------ // operator<=(Field) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator<=(const Field<Dimension, DataType>& rhs) const { if (this->size() != rhs.size()) return false; bool result = true; const_iterator lhsItr = this->begin(); const_iterator rhsItr = rhs.begin(); while (lhsItr < this->end() && result) { result = *lhsItr <= *rhsItr; ++lhsItr; ++rhsItr; } return result; } //------------------------------------------------------------------------------ // operator==(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator==(const DataType& rhs) const { bool result = true; const_iterator lhsItr = this->begin(); while (lhsItr < this->end() && result) { result = *lhsItr == rhs; ++lhsItr; } return result; } //------------------------------------------------------------------------------ // operator!=(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator!=(const DataType& rhs) const { return !((*this) == rhs); } //------------------------------------------------------------------------------ // operator>(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator>(const DataType& rhs) const { bool result = true; const_iterator lhsItr = this->begin(); while (lhsItr < this->end() && result) { result = *lhsItr > rhs; ++lhsItr; } return result; } //------------------------------------------------------------------------------ // operator<(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator<(const DataType& rhs) const { bool result = true; const_iterator lhsItr = this->begin(); while (lhsItr < this->end() && result) { result = *lhsItr < rhs; ++lhsItr; } return result; } //------------------------------------------------------------------------------ // operator>=(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator>=(const DataType& rhs) const { bool result = true; const_iterator lhsItr = this->begin(); while (lhsItr < this->end() && result) { result = *lhsItr >= rhs; ++lhsItr; } return result; } //------------------------------------------------------------------------------ // operator<=(value) //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: operator<=(const DataType& rhs) const { bool result = true; const_iterator lhsItr = this->begin(); while (lhsItr < this->end() && result) { result = *lhsItr <= rhs; ++lhsItr; } return result; } //------------------------------------------------------------------------------ // Test if the field is valid. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>::valid() const { return mValid && this->nodeListPtr(); } //------------------------------------------------------------------------------ // Iterator pointing to the beginning of the field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::begin() { return mDataArray.begin(); } //------------------------------------------------------------------------------ // Iterator pointing to the end of the field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::end() { return mDataArray.end(); } //------------------------------------------------------------------------------ // Iterator pointing to the beginning of the internal field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::internalBegin() { return mDataArray.begin(); } //------------------------------------------------------------------------------ // Iterator pointing to the end of the internal field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::internalEnd() { CHECK(this->nodeList().firstGhostNode() >= 0 && this->nodeList().firstGhostNode() <= this->nodeList().numNodes()); return mDataArray.begin() + this->nodeList().firstGhostNode(); } //------------------------------------------------------------------------------ // Iterator pointing to the beginning of the ghost field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::ghostBegin() { return this->internalEnd(); } //------------------------------------------------------------------------------ // Iterator pointing to the end of the ghost field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::iterator Field<Dimension, DataType>::ghostEnd() { return mDataArray.end(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the beginning of the field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::begin() const { return mDataArray.begin(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the end of the field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::end() const { return mDataArray.end(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the beginning of the internal field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::internalBegin() const { return mDataArray.begin(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the end of the internal field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::internalEnd() const { REQUIRE(this->nodeList().firstGhostNode() >= 0 && this->nodeList().firstGhostNode() <= this->nodeList().numNodes()); return mDataArray.begin() + this->nodeList().firstGhostNode(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the beginning of the ghost field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::ghostBegin() const { return this->internalEnd(); } //------------------------------------------------------------------------------ // Const_iterator pointing to the end of the ghost field values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename Field<Dimension, DataType>::const_iterator Field<Dimension, DataType>::ghostEnd() const { return mDataArray.end(); } //------------------------------------------------------------------------------ // Index operators. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& Field<Dimension, DataType>:: operator[](const unsigned int index) { return mDataArray[index]; } template<typename Dimension, typename DataType> inline const DataType& Field<Dimension, DataType>:: operator[](const unsigned int index) const { return mDataArray[index]; } //------------------------------------------------------------------------------ // Set the NodeList with which this field is defined. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::setNodeList(const NodeList<Dimension>& nodeList) { unsigned oldSize = this->size(); this->setFieldBaseNodeList(nodeList); #ifdef WIN32 mDataArray.resize(nodeList.numNodes()+1); #else mDataArray.resize(nodeList.numNodes()); #endif if (this->size() > oldSize) { for (unsigned i = oldSize; i < this->size(); ++i) { (*this)(i) = DataTypeTraits<DataType>::zero(); } } mValid = true; } //------------------------------------------------------------------------------ // Resize the field to the given number of nodes. This operation ignores // the distinction between internal and ghost nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::resizeField(unsigned size) { REQUIRE(size == this->nodeList().numNodes()); unsigned oldSize = this->size(); #ifdef WIN32 mDataArray.resize(size+1); #else mDataArray.resize(size); #endif if (oldSize < size) { std::fill(mDataArray.begin() + oldSize, mDataArray.end(), DataTypeTraits<DataType>::zero()); } mValid = true; } //------------------------------------------------------------------------------ // Delete the given element id. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::deleteElement(int nodeID) { const unsigned originalSize = this->size(); CONTRACT_VAR(originalSize); REQUIRE(nodeID >= 0 && nodeID < (int)originalSize); mDataArray.erase(mDataArray.begin() + nodeID); ENSURE(mDataArray.size() == originalSize - 1); } //------------------------------------------------------------------------------ // Delete the given set of elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::deleteElements(const std::vector<int>& nodeIDs) { // The standalone method does the actual work. removeElements(mDataArray, nodeIDs); } //------------------------------------------------------------------------------ // Pack the given Field values by appending the elements decomposed into simple // Scalars onto the given array. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::vector<char> Field<Dimension, DataType>:: packValues(const std::vector<int>& nodeIDs) const { return packFieldValues(*this, nodeIDs); } //------------------------------------------------------------------------------ // Unpack the given buffer into the requested field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>:: unpackValues(const std::vector<int>& nodeIDs, const std::vector<char>& buffer) { unpackFieldValues(*this, nodeIDs, buffer); } //------------------------------------------------------------------------------ // Resize the field to the given number of internal nodes, preserving any ghost // values at the end. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::resizeFieldInternal(const unsigned size, const unsigned oldFirstGhostNode) { const unsigned currentSize = this->size(); const unsigned currentInternalSize = oldFirstGhostNode; const unsigned numGhostNodes = this->nodeList().numGhostNodes(); const unsigned newSize = size + numGhostNodes; REQUIRE(numGhostNodes == currentSize - oldFirstGhostNode); REQUIRE(newSize == this->nodeList().numNodes()); // If there is ghost data, we must preserve it. std::vector<DataType,DataAllocator<DataType>> oldGhostValues(numGhostNodes); if (numGhostNodes > 0) { for (auto i = 0u; i != numGhostNodes; ++i) { const int j = oldFirstGhostNode + i; CHECK(i >= 0 && i < numGhostNodes); CHECK(j >= 0 && j < (int)this->size()); oldGhostValues[i] = (*this)(j); } } // Resize the field data. #ifdef WIN32 mDataArray.resize(newSize+1); #else mDataArray.resize(newSize); #endif // Fill in any new internal values. if (newSize > currentSize) { CHECK(currentInternalSize < this->nodeList().firstGhostNode()); std::fill(mDataArray.begin() + currentInternalSize, mDataArray.begin() + this->nodeList().firstGhostNode(), DataTypeTraits<DataType>::zero()); } // Fill the ghost data back in. if (numGhostNodes > 0) { for (auto i = 0u; i != numGhostNodes; ++i) { const int j = this->nodeList().firstGhostNode() + i; CHECK(i >= 0 && i < oldGhostValues.size()); CHECK(j >= 0 && j < (int)this->size()); (*this)(j) = oldGhostValues[i]; } } mValid = true; } //------------------------------------------------------------------------------ // Resize the field to the given number of ghost nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>::resizeFieldGhost(const unsigned size) { const unsigned currentSize = this->size(); const unsigned numInternalNodes = this->nodeList().numInternalNodes(); const unsigned currentNumGhostNodes = currentSize - numInternalNodes; REQUIRE(currentNumGhostNodes >= 0); const unsigned newSize = numInternalNodes + size; REQUIRE(newSize == this->nodeList().numNodes()); // Resize the field data. #ifdef WIN32 mDataArray.resize(newSize+1); CHECK(this->size() == (newSize+1)); #else mDataArray.resize(newSize); CHECK(this->size() == (newSize)); #endif // Fill in any new ghost values. if (newSize > currentSize) { std::fill(mDataArray.begin() + numInternalNodes + currentNumGhostNodes, mDataArray.end(), DataTypeTraits<DataType>::zero()); } mValid = true; } //------------------------------------------------------------------------------ // Copy values between sets of indices. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>:: copyElements(const std::vector<int>& fromIndices, const std::vector<int>& toIndices) { REQUIRE(fromIndices.size() == toIndices.size()); REQUIRE(std::all_of(fromIndices.begin(), fromIndices.end(), [&](const int i) { return i >= 0 and i < (int)this->size(); })); REQUIRE(std::all_of(toIndices.begin(), toIndices.end(), [&](const int i) { return i >= 0 and i < (int)this->size(); })); const auto ni = fromIndices.size(); for (auto k = 0u; k < ni; ++k) (*this)(toIndices[k]) = (*this)(fromIndices[k]); } //------------------------------------------------------------------------------ // fixedSizeDataType //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool Field<Dimension, DataType>:: fixedSizeDataType() const { return DataTypeTraits<DataType>::fixedSize(); } //------------------------------------------------------------------------------ // numValsInDataType //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline int Field<Dimension, DataType>:: numValsInDataType() const { return DataTypeTraits<DataType>::numElements(DataType()); } //------------------------------------------------------------------------------ // sizeofDataType //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline int Field<Dimension, DataType>:: sizeofDataType() const { return sizeof(DataTypeTraits<DataType>::zero()); } //------------------------------------------------------------------------------ // computeCommBufferSize //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline int Field<Dimension, DataType>:: computeCommBufferSize(const std::vector<int>& packIndices, const int sendProc, const int recvProc) const { return computeBufferSize(*this, packIndices, sendProc, recvProc); } //------------------------------------------------------------------------------ // Pack the Field into a string. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::string Field<Dimension, DataType>:: string(const int /*precision*/) const { const int n = numInternalElements(); std::vector<int> indices; indices.reserve(n); for (int i = 0; i != n; ++i) indices.push_back(i); CHECK((int)indices.size() == n); const std::vector<char> packedValues = packFieldValues(*this, indices); return std::string(this->name()) + "|" + std::string(packedValues.begin(), packedValues.end()); } //------------------------------------------------------------------------------ // Unpack the values from a string into this Field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void Field<Dimension, DataType>:: string(const std::string& s) { const int n = numInternalElements(); std::vector<int> indices; indices.reserve(n); for (int i = 0; i != n; ++i) indices.push_back(i); CHECK((int)indices.size() == n); const size_t j = s.find("|"); CHECK(j != std::string::npos and j < s.size()); this->name(s.substr(0, j)); const std::vector<char> packedValues(s.begin() + j + 1, s.end()); unpackFieldValues(*this, indices, packedValues); } //------------------------------------------------------------------------------ // Construct std::vectors of pointers to the values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::vector<DataType> Field<Dimension, DataType>:: internalValues() const { std::vector<DataType> result; result.reserve(this->nodeList().numInternalNodes()); for (const_iterator itr = internalBegin(); itr != internalEnd(); ++itr) result.push_back(*itr); ENSURE(result.size() == this->nodeList().numInternalNodes()); return result; } template<typename Dimension, typename DataType> inline std::vector<DataType> Field<Dimension, DataType>:: ghostValues() const { std::vector<DataType> result; result.reserve(this->nodeList().numGhostNodes()); for (const_iterator itr = ghostBegin(); itr != ghostEnd(); ++itr) result.push_back(*itr); ENSURE(result.size() == this->nodeList().numGhostNodes()); return result; } template<typename Dimension, typename DataType> inline std::vector<DataType> Field<Dimension, DataType>:: allValues() const { std::vector<DataType> result; result.reserve(this->nodeList().numNodes()); for (const_iterator itr = begin(); itr != end(); ++itr) result.push_back(*itr); ENSURE(result.size() == this->nodeList().numNodes()); return result; } //****************************** Global Functions ****************************** //------------------------------------------------------------------------------ // Multiplication by another Field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType, typename OtherDataType> Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const Field<Dimension, DataType>& lhs, const Field<Dimension, OtherDataType>& rhs) { CHECK(lhs.valid() && rhs.valid()); CHECK(lhs.nodeList().numNodes() == rhs.nodeList().numNodes()); Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result("product", const_cast<Field<Dimension, DataType>&>(lhs).nodeList()); for (auto i = 0u; i < result.numElements(); ++i) { result(i) = lhs(i) * rhs(i); } return result; } //------------------------------------------------------------------------------ // Multiplication by a single value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType, typename OtherDataType> Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const Field<Dimension, DataType>& lhs, const OtherDataType& rhs) { CHECK(lhs.valid()); Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result("product", const_cast<Field<Dimension, DataType>&>(lhs).nodeList()); for (int i = 0; i < result.numElements(); ++i) { result(i) = lhs(i) * rhs; } return result; } template<typename Dimension, typename DataType, typename OtherDataType> Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const DataType& lhs, const Field<Dimension, OtherDataType>& rhs) { CHECK(rhs.valid()); Field<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result("product", const_cast<Field<Dimension, OtherDataType>&>(rhs).nodeList()); for (auto i = 0u; i < result.numElements(); ++i) { result(i) = lhs * rhs(i); } return result; } // //------------------------------------------------------------------------------ // // Absolute value. // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // abs(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::abs(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse cosine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // acos(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::acos(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse sine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // asin(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::asin(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse tangent // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // atan(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::atan(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse tangent2. // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // atan2(const Field<Dimension, typename Dimension::Scalar>& field1, // const Field<Dimension, typename Dimension::Scalar>& field2) { // typedef typename Dimension::Scalar Scalar; // CHECK(field1.valid() && field2.valid()); // CHECK(field1.nodeListPtr() == field2.nodeListPtr()); // Field<Dimension, Scalar> result(field1); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::atan2(field1(i), field2(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Ceiling -- smallest floating-point integer value not less than the argument. // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // ceil(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::ceil(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Cosine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // cos(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::cos(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Hyperbolic cosine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // cosh(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::cosh(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Exponential e^x // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // exp(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::exp(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // fabs -- same as abs, absolute value // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // fabs(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::abs(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Floor -- largest floating-point integer value not greater than the argument // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // floor(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::floor(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Natural logarithm // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // log(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::log(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Log base 10 // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // log10(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::log10(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // pow -- raise each element to an arbitrary power // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow(const Field<Dimension, typename Dimension::Scalar>& field, // const double exponent) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::pow(result(i), exponent); // } // return result; // } // //------------------------------------------------------------------------------ // // powN -- raise each element to the power N // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow2(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow2(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow3(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow3(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow4(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow4(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow5(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow5(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow6(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow6(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow7(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow7(result(i)); // } // return result; // } // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // pow8(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = FastMath::pow8(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Sine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // sin(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::sin(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Hyperbolic sine // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // sinh(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // result(i) = std::sinh(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Sqr -- square, same as pow2() // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // sqr(const Field<Dimension, typename Dimension::Scalar>& field) { // return field.pow2(); // } // //------------------------------------------------------------------------------ // // Sqrt // //------------------------------------------------------------------------------ // template<typename Dimension> // Field<Dimension, typename Dimension::Scalar> // sqrt(const Field<Dimension, typename Dimension::Scalar>& field) { // typedef typename Dimension::Scalar Scalar; // CHECK(field.valid()); // Field<Dimension, Scalar> result(field); // for (int i = 0; i < result.numElements(); ++i) { // CHECK(result(i) >= 0.0); // result(i) = std::sqrt(result(i)); // } // return result; // } // //------------------------------------------------------------------------------ // // Minimum // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // min(const Field<Dimension, DataType>& field1, // const Field<Dimension, DataType>& field2) { // CHECK(field1.valid() && field2.valid()); // CHECK(field1.numElements() == field2.numElements()); // CHECK(field1.nodeListPtr() == field2.nodeListPtr()); // Field<Dimension, DataType> result("min", const_cast<NodeList<Dimension>&>(field1.nodeList())); // for (int i = 0; i < field1.numElements(); ++i) { // result(i) = std::min(field1(i), field2(i)); // } // return result; // } // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // min(const DataType& value, // const Field<Dimension, DataType>& field) { // CHECK(field.valid()); // Field<Dimension, DataType> result("min", const_cast<NodeList<Dimension>&>(field.nodeList())); // for (int i = 0; i < field.numElements(); ++i) { // result(i) = std::min(value, field(i)); // } // return result; // } // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // min(const Field<Dimension, DataType>& field, // const DataType& value) { // CHECK(field.valid()); // Field<Dimension, DataType> result("min", const_cast<NodeList<Dimension>&>(field.nodeList())); // for (int i = 0; i < field.numElements(); ++i) { // result(i) = std::min(field(i), value); // } // return result; // } // //------------------------------------------------------------------------------ // // Maximum // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // max(const Field<Dimension, DataType>& field1, // const Field<Dimension, DataType>& field2) { // CHECK(field1.valid() && field2.valid()); // CHECK(field1.numElements() == field2.numElements()); // CHECK(field1.nodeListPtr() == field2.nodeListPtr()); // Field<Dimension, DataType> result("max", const_cast<NodeList<Dimension>&>(field1.nodeList())); // for (int i = 0; i < field1.numElements(); ++i) { // result(i) = std::max(field1(i), field2(i)); // } // return result; // } // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // max(const DataType& value, // const Field<Dimension, DataType>& field) { // CHECK(field.valid()); // Field<Dimension, DataType> result("max", const_cast<NodeList<Dimension>&>(field.nodeList())); // for (int i = 0; i < field.numElements(); ++i) { // result(i) = std::max(value, field(i)); // } // return result; // } // template<typename Dimension, typename DataType> // Field<Dimension, DataType> // max(const Field<Dimension, DataType>& field, // const DataType& value) { // CHECK(field.valid()); // Field<Dimension, DataType> result("max", const_cast<NodeList<Dimension>&>(field.nodeList())); // for (int i = 0; i < field.numElements(); ++i) { // result(i) = std::max(field(i), value); // } // return result; // } //------------------------------------------------------------------------------ // Input (istream) operator. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> std::istream& operator>>(std::istream& is, Field<Dimension, DataType>& field) { // Start by reading the number of elements. int numElementsInStream; is >> numElementsInStream; CHECK(numElementsInStream == (int)field.nodeList().numInternalNodes()); // Read in the elements. for (typename Field<Dimension, DataType>::iterator itr = field.internalBegin(); itr < field.internalEnd(); ++itr) { is >> *itr; } return is; } //------------------------------------------------------------------------------ // Output (ostream) operator. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> std::ostream& operator<<(std::ostream& os, const Field<Dimension, DataType>& field) { // Write the number of internal elements. os << field.nodeList().numInternalNodes() << " "; // Write the internal elements. for (typename Field<Dimension, DataType>::const_iterator itr = field.internalBegin(); itr < field.internalEnd(); ++itr) { os << *itr << " "; } // os << endl; return os; } //------------------------------------------------------------------------------ // getAxomType //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline axom::sidre::DataTypeId Field<Dimension, DataType>:: getAxomTypeID() const { return DataTypeTraits<DataType>::axomTypeID(); } } // namespace Spheral
35.943273
169
0.51139
[ "geometry", "vector" ]
2137d2247602a6436a121a52d8cfe88d97e15ee3
6,202
cc
C++
net/spdy/chromium/header_coalescer_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/spdy/chromium/header_coalescer_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/spdy/chromium/header_coalescer_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium 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 "net/spdy/chromium/header_coalescer.h" #include <vector> #include "net/log/test_net_log.h" #include "net/spdy/platform/api/spdy_string.h" #include "net/spdy/platform/api/spdy_string_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::ElementsAre; using ::testing::Pair; namespace net { namespace test { class HeaderCoalescerTest : public ::testing::Test { public: HeaderCoalescerTest() : header_coalescer_(net_log_.bound()) {} void ExpectEntry(SpdyStringPiece expected_header_name, SpdyStringPiece expected_header_value, SpdyStringPiece expected_error_message) { TestNetLogEntry::List entry_list; net_log_.GetEntries(&entry_list); ASSERT_EQ(1u, entry_list.size()); EXPECT_EQ(entry_list[0].type, NetLogEventType::HTTP2_SESSION_RECV_INVALID_HEADER); EXPECT_EQ(entry_list[0].source.id, net_log_.bound().source().id); std::string value; EXPECT_TRUE(entry_list[0].GetStringValue("header_name", &value)); EXPECT_EQ(expected_header_name, value); EXPECT_TRUE(entry_list[0].GetStringValue("header_value", &value)); EXPECT_EQ(expected_header_value, value); EXPECT_TRUE(entry_list[0].GetStringValue("error", &value)); EXPECT_EQ(expected_error_message, value); } protected: BoundTestNetLog net_log_; HeaderCoalescer header_coalescer_; }; TEST_F(HeaderCoalescerTest, CorrectHeaders) { header_coalescer_.OnHeader(":foo", "bar"); header_coalescer_.OnHeader("baz", "qux"); EXPECT_FALSE(header_coalescer_.error_seen()); SpdyHeaderBlock header_block = header_coalescer_.release_headers(); EXPECT_THAT(header_block, ElementsAre(Pair(":foo", "bar"), Pair("baz", "qux"))); } TEST_F(HeaderCoalescerTest, EmptyHeaderKey) { header_coalescer_.OnHeader("", "foo"); EXPECT_TRUE(header_coalescer_.error_seen()); ExpectEntry("", "foo", "Header name must not be empty."); } TEST_F(HeaderCoalescerTest, HeaderBlockTooLarge) { // 3 byte key, 256 * 1024 - 40 byte value, 32 byte overhead: // less than 256 * 1024 bytes in total. SpdyString data(256 * 1024 - 40, 'a'); header_coalescer_.OnHeader("foo", data); EXPECT_FALSE(header_coalescer_.error_seen()); // Another 3 + 4 + 32 bytes: too large. SpdyStringPiece header_value("\x1\x7F\x80\xFF"); header_coalescer_.OnHeader("bar", header_value); EXPECT_TRUE(header_coalescer_.error_seen()); ExpectEntry("bar", "%01%7F%80%FF", "Header list too large."); } TEST_F(HeaderCoalescerTest, PseudoHeadersMustNotFollowRegularHeaders) { header_coalescer_.OnHeader("foo", "bar"); EXPECT_FALSE(header_coalescer_.error_seen()); header_coalescer_.OnHeader(":baz", "qux"); EXPECT_TRUE(header_coalescer_.error_seen()); ExpectEntry(":baz", "qux", "Pseudo header must not follow regular headers."); } TEST_F(HeaderCoalescerTest, Append) { header_coalescer_.OnHeader("foo", "bar"); header_coalescer_.OnHeader("cookie", "baz"); header_coalescer_.OnHeader("foo", "quux"); header_coalescer_.OnHeader("cookie", "qux"); EXPECT_FALSE(header_coalescer_.error_seen()); SpdyHeaderBlock header_block = header_coalescer_.release_headers(); EXPECT_THAT(header_block, ElementsAre(Pair("foo", SpdyStringPiece("bar\0quux", 8)), Pair("cookie", "baz; qux"))); } TEST_F(HeaderCoalescerTest, CRLFInHeaderValue) { header_coalescer_.OnHeader("foo", "bar\r\nbaz"); EXPECT_TRUE(header_coalescer_.error_seen()); ExpectEntry("foo", "bar%0D%0Abaz", "Header value must not contain CR+LF."); } TEST_F(HeaderCoalescerTest, HeaderNameNotValid) { SpdyStringPiece header_name("\x1\x7F\x80\xFF"); header_coalescer_.OnHeader(header_name, "foo"); EXPECT_TRUE(header_coalescer_.error_seen()); ExpectEntry("%01%7F%80%FF", "foo", "Invalid character in header name."); } // RFC 7230 Section 3.2. Valid header name is defined as: // field-name = token // token = 1*tchar // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / // "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA TEST_F(HeaderCoalescerTest, HeaderNameValid) { SpdyStringPiece header_name( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-." "^_`|~"); header_coalescer_.OnHeader(header_name, "foo"); EXPECT_FALSE(header_coalescer_.error_seen()); SpdyHeaderBlock header_block = header_coalescer_.release_headers(); EXPECT_THAT(header_block, ElementsAre(Pair(header_name, "foo"))); } // RFC 7230 Section 3.2. Valid header value is defined as: // field-value = *( field-content / obs-fold ) // field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] // field-vchar = VCHAR / obs-text // // obs-fold = CRLF 1*( SP / HTAB ) // ; obsolete line folding // ; see Section 3.2.4 TEST_F(HeaderCoalescerTest, HeaderValueValid) { // Add two headers, one with an HTAB and one with a SP. std::vector<char> header_values[2]; char prefixes[] = {'\t', ' '}; for (int i = 0; i < 2; ++i) { header_values[i] = std::vector<char>(); header_values[i].push_back(prefixes[i]); // obs-text. From 0x80 to 0xff. for (int j = 0x80; j <= 0xff; ++j) { header_values[i].push_back(j); } // vchar for (int j = 0x21; j <= 0x7E; ++j) { header_values[i].push_back(j); } header_coalescer_.OnHeader( SpdyStringPrintf("%s_%d", "foo", i), SpdyStringPiece(header_values[i].data(), header_values[i].size())); EXPECT_FALSE(header_coalescer_.error_seen()); } SpdyHeaderBlock header_block = header_coalescer_.release_headers(); EXPECT_THAT( header_block, ElementsAre(Pair("foo_0", SpdyStringPiece(header_values[0].data(), header_values[0].size())), Pair("foo_1", SpdyStringPiece(header_values[1].data(), header_values[1].size())))); } } // namespace test } // namespace net
37.137725
80
0.676233
[ "vector" ]
213a9b093dbe84497b2e88087ea28cbaa0fccd00
1,144
cpp
C++
vnext/ReactWindowsCore/Modules/AppThemeModule.cpp
haseeAmarathunga/react-native-windows
b33ea7f0c1977bb089d995c37e41e88d1e770919
[ "MIT" ]
null
null
null
vnext/ReactWindowsCore/Modules/AppThemeModule.cpp
haseeAmarathunga/react-native-windows
b33ea7f0c1977bb089d995c37e41e88d1e770919
[ "MIT" ]
null
null
null
vnext/ReactWindowsCore/Modules/AppThemeModule.cpp
haseeAmarathunga/react-native-windows
b33ea7f0c1977bb089d995c37e41e88d1e770919
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "AppThemeModule.h" namespace react { namespace windows { // // AppTheme // AppTheme::AppTheme() = default; AppTheme::~AppTheme() = default; const std::string AppTheme::getCurrentTheme() { return AppTheme::light; } bool AppTheme::getIsHighContrast() { return false; } folly::dynamic AppTheme::getHighContrastColors() { return {}; } // // AppThemeModule // AppThemeModule::AppThemeModule(std::shared_ptr<AppTheme>&& appTheme) : m_appTheme(std::move(appTheme)) { } auto AppThemeModule::getConstants() -> std::map<std::string, folly::dynamic> { return { { "initialAppTheme", folly::dynamic { m_appTheme->getCurrentTheme() } }, { "initialHighContrast", folly::dynamic { m_appTheme->getIsHighContrast() }}, { "initialHighContrastColors", folly::dynamic {m_appTheme->getHighContrastColors()}} }; } auto AppThemeModule::getMethods() -> std::vector<facebook::xplat::module::CxxModule::Method> { return { }; } } } // namespace react::windows
20.428571
93
0.670455
[ "vector" ]
2147c5b3e206d7333a9c75e241995f31a9443ef8
585
cpp
C++
src/datasource.cpp
bensengupta/search
fa2e22b78f4b989d79f8087d4c357df831fceb0d
[ "MIT" ]
null
null
null
src/datasource.cpp
bensengupta/search
fa2e22b78f4b989d79f8087d4c357df831fceb0d
[ "MIT" ]
null
null
null
src/datasource.cpp
bensengupta/search
fa2e22b78f4b989d79f8087d4c357df831fceb0d
[ "MIT" ]
null
null
null
#include "../include/datasource.h" #include <fstream> #include <iostream> using namespace std; vector<Document> DataSource::getDocuments() { return {}; } FileDataSource::FileDataSource(string filename) { this->filename = filename; } vector<Document> FileDataSource::getDocuments() { ifstream in(filename); if (in.fail()) { cerr << "Error: Could not find file '" << filename << "'" << endl; exit(1); } vector<Document> docs{}; int i = 0; string line; while (getline(in, line)) { docs.push_back(Document(i++, line)); } in.close(); return docs; }
18.870968
78
0.644444
[ "vector" ]
214c02fac80e55bf8386f3e8202ed94e2e66f061
87,634
cpp
C++
code/appImmViewer/src/android/cpp/OvrApp.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
33
2021-09-16T18:37:08.000Z
2022-03-22T23:02:44.000Z
code/appImmViewer/src/android/cpp/OvrApp.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
5
2021-09-17T10:10:07.000Z
2022-03-28T12:33:29.000Z
code/appImmViewer/src/android/cpp/OvrApp.cpp
andybak/IMM
c725dcb28a1638dea726381a7189c3b031967d58
[ "Apache-2.0", "MIT" ]
5
2021-09-19T07:49:01.000Z
2021-12-12T21:25:35.000Z
#include "GlHelpers.h" #include "Haptics.h" #include "Log.h" #include "Events.h" //#include "Quillustration.h" #include "libImmPlayer/src/player.h" #include "libImmCore/src/libBasics/piTimer.h" #include "libImmCore/src/libBasics/piStr.h" #include "libImmCore/src/libMesh/piRenderMesh.h" #include "libImmCore/src/libSound/windows/piSoundEngineAudioSDKBackend.h" #include "../../viewer/viewer.h" #include "../../settings.h" #include <cstdio> #include <strings.h> #include <cstdlib> #include <cmath> #include <ctime> #include <unistd.h> #include <pthread.h> #include <sys/prctl.h> // for prctl( PR_SET_NAME ) #include <android/window.h> // for AWINDOW_FLAG_KEEP_SCREEN_ON #include <android/native_window_jni.h> // for native window JNI #include <android_native_app_glue.h> #include <algorithm> #include <utility> #include <EGL/egl.h> #include <EGL/eglext.h> #include <GLES3/gl3.h> #include <GLES3/gl3ext.h> #include <android/keycodes.h> #include <android/input.h> #include <VrApi_Types.h> #include <OVR_PlatformInitializeResult.h> #include <OVR_Requests_Entitlement.h> #include <OVR_Message.h> #include <OVR_Platform.h> #include <OVR_Platform_Internal.h> #include "VrApi.h" #include "VrApi_Helpers.h" #include "VrApi_SystemUtils.h" #include "VrApi_Input.h" #include "VrApi_Types.h" // region Config #define ENABLE_DEBUG_PANEL 1 #define ENABLE_DEBUG_VIEWPOINT_UI 0 static const char * APP_ID = "2515021945210953"; static const int CPU_LEVEL_MAX = 5; // Use CPU 5 during loading static const int GPU_LEVEL_MAX = 5; static const int CPU_LEVEL_DEFAULT = 2; static const int GPU_LEVEL_DEFAULT = 3; static const int NUM_MULTI_SAMPLES = 4; // Set these to override system defaults; static const int EYE_BUFFER_WIDTH = 0; //1216; static const int EYE_BUFFER_HEIGHT = 0; //1344; // Requested levels may change if we detect too many stale frames. int requestedCPULevel = CPU_LEVEL_DEFAULT; int requestedGPULevel = GPU_LEVEL_DEFAULT; int requestedEyeBufferWidth = 0; int requestedEyeBufferHeight = 0; static const int IMM_BYTES_THRESHOLD_FOR_STATIC = 50 * 1024 * 1024; // static and staticTexture have shown that they perform significantly better when rendering in mono. static ImmPlayer::StereoMode STEREO_MODE = ImmPlayer::StereoMode::None; typedef enum handID_t_ { HAND_ID_LEFT = 0, HAND_ID_RIGHT = 1, HAND_ID_COUNT = 2, } handID_t; typedef struct RemoteDevice_ { static constexpr uint32_t ID_NONE = ~(uint32_t)0; uint32_t mRemoteDeviceID = ID_NONE; uint32_t mButtonState = 0; handID_t mHandID = HAND_ID_COUNT; } RemoteDevice; RemoteDevice mRemoteDevices[handID_t::HAND_ID_COUNT]; // Enable to fix the view matrix for performance testing // #define PERFORMANCE_TESTING 1 // TODO: Remove. Likely do not need this anymore. static bool resetTracking = false; // Some older Quills need eye level origin static ovrTrackingTransform vrTrackingTransformLevel = VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_FLOOR_LEVEL; #define MULTI_THREADED 0 #define REDUCED_LATENCY 0 using namespace ImmImporter; using namespace ImmCore; using namespace ImmPlayer; using namespace ExePlayer; static const uint32_t RENDER_BUDGET_MICROSECONDS = 8000; static const double MIN_SPEED = 0.001; static const int JOYSTICK_ORIENTATION_SPEED = 1; static const ExePlayer::Settings::Rendering::Technique DEFAULT_RENDERING_TECHNIQUE = ExePlayer::Settings::Rendering::Technique::Pretessellated; // Back press unloads the current document and resets player state. Quit from the system UI will // lead to onDestroy and we'll release the Quill player. bool shutdownRequested = false; bool didProcessUnloadOnBackPress = false; bool isUserEntitled = false; short framesSinceStart = -1; // Wait at most 10 frames for a new document path before showing error. const int waitForDocFramesMax = 10; static std::string locale; // Add a simple message queue for notifying the render thread of Java main thread state updates. // Particularly we need to make sure that the quillPath doesn't change during the render loop // execution as this can lead to crashes. enum MessageType { Unknown = -1, LoadImmPath = 0, ErrorUnknown = 1, ErrorDisconnected = 2, UpdateMetadata = 4, UpdateViewpoints = 5, UpNextSelected = 6, }; struct Message { Message(MessageType t, std::string v) : type(t), value(std::move(v)) {} MessageType type = MessageType::Unknown; std::string value = ""; }; std::vector<Message> messageQueue; std::mutex messageQueueLock; void sendMessage(MessageType type, std::string message) { Message newMessage(type, message); messageQueueLock.lock(); messageQueue.push_back(newMessage); messageQueueLock.unlock(); } // endregion // region IMM State // IMM Player and dependencies struct AppImmPlayerState { std::string quillPath = ""; bool isDisconnected = false; bool loadNewDocument = false; ExePlayer::Settings::Rendering::Technique renderingTechnique = DEFAULT_RENDERING_TECHNIQUE; piCameraD playerCamera = piCameraD(); // Allow the eye buffer scale to be passed in from the intent extras for quality testing. float requestedEyeBufferScale = 1.0f; double playerSpeed = 0.01; bool isFirstFrame = true; bool buildFlavorHeadless = true; bool allowDevToolsInHeadless = false; double startTime = 0; double oldTime = 0; ovrPosef latestLeftControllerPose = ovrPosef(); ovrPosef latestRightControllerPose = ovrPosef(); piRasterState rasterState[2]; // Two for left and right controller rendering bool interactionOccurredLastFrame = false; int waitingHapticsCount = 0; std::string playerSpawnLocation = "Default"; ImmPlayer::Player::PerformanceInfo lastPerformanceInfo; uint64_t downloadedBytes = 0; bool pendingFoveationChange; int foveationLevel = 2; int confirmExitFrameCountdown = 0; bool hmdWorn = true; // Loading indicator ovrTextureSwapChain * loadingSwapChain = nullptr; int loadingSwapIndex = 0; uint64_t loadingStartFrame = 0; GLuint * loadingFbo = nullptr; struct TextTexture { enum Status { READY = 0, TEXTURE_UPDATED = 1, DATA_UPDATED =2 } metaStatus = READY; GLuint ID = 0; // real GL id so we can call GL commands from java GLuint width = 952; // must match aspect ratio of viewpoint UI panel GLuint height = 858; GLuint mipLevels = 5; piTexture texture; // piLibs texture so we can use with uiLib float metadataHeight = 0.0f; } textTexture; }; AppImmPlayerState immPlayerState; struct AppImmPlayer { piRenderer * glesRenderer = nullptr; piLog * pLog = nullptr; piTimer * pTimer = nullptr; piSoundEngineBackend * soundEngineBackend = nullptr; ExePlayer::Viewer * viewer = nullptr; bool initialized = false; }; AppImmPlayer immPlayer; void resetQuillPlayerState() { ALOGV("Reset player state"); immPlayerState.isFirstFrame = true; immPlayerState.quillPath.clear(); immPlayerState.isDisconnected = false; immPlayerState.playerCamera = piCameraD(); immPlayerState.playerSpeed = 0.01; immPlayerState.allowDevToolsInHeadless = false; immPlayerState.startTime = 0; immPlayerState.oldTime = 0; immPlayerState.latestLeftControllerPose = ovrPosef(); immPlayerState.latestRightControllerPose = ovrPosef(); immPlayerState.renderingTechnique = DEFAULT_RENDERING_TECHNIQUE; immPlayerState.interactionOccurredLastFrame = false; immPlayerState.playerSpawnLocation = "Default"; immPlayerState.waitingHapticsCount = 0; immPlayerState.confirmExitFrameCountdown = 0; vrapi_DestroyTextureSwapChain(immPlayerState.loadingSwapChain); immPlayerState.loadingSwapChain = nullptr; free(immPlayerState.loadingFbo); immPlayerState.loadingFbo = nullptr; } void resetQuillPlayerStateForNewDocument() { ALOGV("Reset player state for new document"); didProcessUnloadOnBackPress = false; immPlayerState.playerCamera = piCameraD(); immPlayerState.playerSpeed = 0.01; immPlayerState.allowDevToolsInHeadless = false; immPlayerState.startTime = 0; immPlayerState.oldTime = 0; immPlayerState.latestLeftControllerPose = ovrPosef(); immPlayerState.latestRightControllerPose = ovrPosef(); immPlayerState.interactionOccurredLastFrame = false; immPlayerState.waitingHapticsCount = 0; immPlayerState.confirmExitFrameCountdown = 0; immPlayerState.loadingSwapChain = nullptr; free(immPlayerState.loadingFbo); immPlayerState.loadingFbo = nullptr; } // Quill path may be included in the Java activity intent extra QUILL_PATH. // May be the path to the Quill authoring folder or to the .imm file. const char * getQuillPath() { return immPlayerState.quillPath.c_str(); } // endregion // region JNI Methods extern "C" { void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetAssetDirectory( JNIEnv * jni, jclass clazz, jstring assetDirectory) { const char* assetDirUtf = jni->GetStringUTFChars(assetDirectory, 0); ExePlayer::setAssetDirectory(assetDirUtf); ALOGV("nativeSetAssetDirectory %s", assetDirUtf); jni->ReleaseStringUTFChars(assetDirectory, assetDirUtf); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetLocale( JNIEnv * jni, jclass clazz, jstring userLocale) { const char* localeUtf = jni->GetStringUTFChars(userLocale, 0); locale = localeUtf; ALOGV("nativeSetLocale %s", localeUtf); jni->ReleaseStringUTFChars(userLocale, localeUtf); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSendMessage( JNIEnv * jni, jclass clazz, jstring jMessage, jint jMessageType) { const char* messageUtf = jni->GetStringUTFChars(jMessage, 0); ALOGV("nativeSendMessage %i %s", (int) jMessageType, messageUtf); sendMessage(static_cast<MessageType>(jMessageType), std::string(messageUtf)); jni->ReleaseStringUTFChars(jMessage, messageUtf); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetQuillRenderingTechnique( JNIEnv * jni, jclass clazz, jint renderingTechnique) { ALOGV("nativeSetQuillRenderingTechnique %d", renderingTechnique); immPlayerState.renderingTechnique = static_cast<ExePlayer::Settings::Rendering::Technique>(renderingTechnique); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetTrackingTransformLevel( JNIEnv * jni, jclass clazz, jstring jTrackingLevel) { const char* trackingLevelUtf = jni->GetStringUTFChars(jTrackingLevel, 0); ALOGV("nativeSetTrackingTransformLevel %s", trackingLevelUtf); bool isEyeLevel = strncasecmp(trackingLevelUtf, "eye", 3) == 0; vrTrackingTransformLevel = isEyeLevel ? VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_EYE_LEVEL : VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_FLOOR_LEVEL; jni->ReleaseStringUTFChars(jTrackingLevel, trackingLevelUtf); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetEyeBufferScale( JNIEnv *jni, jclass clazz, jfloat scaleFactor) { ALOGV("nativeSetEyeBufferScale %f", scaleFactor); immPlayerState.requestedEyeBufferScale = scaleFactor; } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetPlayerSpawnLocation( JNIEnv * jni, jclass clazz, jstring jSpawnLocation) { const char* spawnLocationUtf = jni->GetStringUTFChars(jSpawnLocation, 0); ALOGV("nativeSetPlayerSpawnLocation %s", spawnLocationUtf); immPlayerState.playerSpawnLocation = std::string(spawnLocationUtf); jni->ReleaseStringUTFChars(jSpawnLocation, spawnLocationUtf); } inline void assignJString(JNIEnv *jni, jstring newString, wchar_t **oldString) { if (*oldString != nullptr) { free(*oldString); *oldString = nullptr; } if (newString != nullptr) { const char *newStringUtf = jni->GetStringUTFChars(newString, 0); *oldString = pistr2ws(newStringUtf); jni->ReleaseStringUTFChars(newString, newStringUtf); } } void createTextTexture() { // Generate a GL texture to render the text in from the java side GL( glGenTextures(1, &immPlayerState.textTexture.ID) ); GL( glBindTexture(GL_TEXTURE_2D, immPlayerState.textTexture.ID) ); GL( glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8UI, immPlayerState.textTexture.width, immPlayerState.textTexture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, immPlayerState.textTexture.mipLevels) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) ); GL( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) ); GL( glGenerateMipmap(GL_TEXTURE_2D) ); // Create a piTexture wrapper so we can use it in the UILib immPlayerState.textTexture.texture = immPlayer.glesRenderer->CreateTextureFromID(immPlayerState.textTexture.ID, piRenderer::TextureFilter::MIPMAP); } void initTextTexture(ovrJava* java) { JNIEnv * env = java->Env; jclass activityClass = env->GetObjectClass(java->ActivityObject); jmethodID setTextureMethodId = env->GetMethodID(activityClass, "initTextTexture", "(III)V"); env->CallVoidMethod(java->ActivityObject, setTextureMethodId, immPlayerState.textTexture.ID, immPlayerState.textTexture.width, immPlayerState.textTexture.height); env->DeleteLocalRef(activityClass); } void updateTextTextureMetadata(ovrJava* java, const char* title, const char* artist, const char* date, const char* description) { JNIEnv * env = java->Env; jclass activityClass = env->GetObjectClass(java->ActivityObject); jmethodID updateTextureMethodId = env->GetMethodID(activityClass, "updateTextTextureMetadata", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)F"); auto p1 = env->NewStringUTF(title); auto p2 = env->NewStringUTF(artist); auto p3 = env->NewStringUTF(date); auto p4 = env->NewStringUTF(description); jfloat height = env->CallFloatMethod(java->ActivityObject, updateTextureMethodId, p1, p2, p3, p4 ); immPlayerState.textTexture.metadataHeight = (float)height; env->DeleteLocalRef(p1); env->DeleteLocalRef(p2); env->DeleteLocalRef(p3); env->DeleteLocalRef(p4); env->DeleteLocalRef(activityClass); } void destroyTextTexture() { GL( glDeleteTextures(1, &immPlayerState.textTexture.ID) ); } void Java_org_linuxfoundation_imm_player_MainActivity_nativeSetBuildFlavorHeadless( JNIEnv * jni, jclass clazz, jboolean jbuildFlavorHeadless) { immPlayerState.buildFlavorHeadless = jbuildFlavorHeadless; } } // extern "C" // fix from john pollard: issue recenter, wait a few frames, set vrapi_SetTrackingTransform void requestResetTracking() { resetTracking = true; } //============================== // WaitForDebuggerToAttach // // wait on the debugger... once it is attached, change waitForDebugger to false void WaitForDebuggerToAttach3() { ALOGV("Waiting for debugger to attach"); static volatile bool waitForDebugger = true; while (waitForDebugger) { // put your breakpoint on the sleep to wait usleep(100 * 1000); } } typedef struct { struct { mat4x4 mViewerToEye_Prj; } mEye[2]; vec2 mResolution; } DisplayRenderState; // slot 4 // When exiting via back press or home button press we need to clean up any per-document state as // the activity may be reused to load a new document. void unloadAndResetOnExit(ovrJava * java) { // Cancel pending downloads. /*if (immPlayerState.quillPath == "http" && java != nullptr) { cancelDownload(java); }*/ shutdownRequested = true; } bool loadQuillPath(const wchar_t * quillPath, ExePlayer::Settings::Rendering::Technique renderingTechnique) { if (quillPath == nullptr || wcslen(quillPath) == 0) { return false; } if (immPlayer.viewer == nullptr) { ALOGF("Could not load Quill path"); } ALOGV("loadQuillPath %ls", quillPath); immPlayer.glesRenderer->Report(); ExePlayer::Settings settings; settings.mPlayback.mLocation.mRotation = quatd(0, 0, 0, 1); settings.mPlayback.mLocation.mScale = 1; settings.mPlayback.mLocation.mFlip = flip3::N; settings.mPlayback.mLocation.mTranslation = vec3d(0, 0, 0); const wchar_t * spawnLocation = pistr2ws(immPlayerState.playerSpawnLocation.c_str()); settings.mPlayback.mPlayerSpawn.mLocation.InitCopyW(spawnLocation); free((void*)spawnLocation); settings.mRendering.mRenderingAPI = ExePlayer::Settings::Rendering::API::GLES; // Set the Quill file path in settings. settings.mFiles.mLoad.New(1, true); settings.mFiles.mLoad[0].InitCopyW(quillPath); // IMMs that will likely use 1.2GB+ in pretessellated should use Static to avoid memory issues. bool useStaticRender = immPlayerState.downloadedBytes > IMM_BYTES_THRESHOLD_FOR_STATIC; settings.mRendering.mRenderingTechnique = useStaticRender ? ExePlayer::Settings::Rendering::Technique::Static : renderingTechnique; immPlayerState.foveationLevel = 2; //useStaticRender ? 2 : 0; immPlayerState.pendingFoveationChange = true; wchar_t tmpFolder[1024]; swprintf(tmpFolder, 1023, L"%s/tmp", ExePlayer::getAssetDirectory()); bool success = immPlayer.viewer->Init( 0, immPlayer.glesRenderer, immPlayer.soundEngineBackend->GetEngine(), immPlayer.pLog, immPlayer.pTimer, STEREO_MODE, &settings); if (success) { immPlayer.initialized = true; } settings.mFiles.mLoad[0].End(); settings.mFiles.mLoad.End(); return success; } void handleMessageLoadImmPath(const Message & msg) { immPlayerState.quillPath = msg.value; immPlayerState.isDisconnected = msg.type == MessageType::ErrorDisconnected; const bool isDownload = immPlayerState.quillPath == "http"; ALOGV("handleMessageLoadImmPath %s %i", msg.value.c_str(), msg.type); // Quill Player was previously loading / rendering a document; unload it and prepare to load new // quill path. if (immPlayer.viewer != nullptr && !immPlayerState.quillPath.empty() && !shutdownRequested) { int docID = 0; if (!isDownload) { ALOGV(" unloading previous document..."); immPlayer.viewer->Unload(docID); } // Careful not to clear new document state set from intent extras. resetQuillPlayerStateForNewDocument(); requestResetTracking(); immPlayerState.loadNewDocument = true; } } void initQuillPlayer(const wchar_t * quillPath, Settings::Rendering::Technique renderingTechnique, ovrJava * java) { if (immPlayer.viewer != nullptr) { ALOGW("initQuillPlayer viewer not null"); return; } immPlayer.glesRenderer = piRenderer::Create(piRenderer::API::GLES); if (!immPlayer.glesRenderer) { ALOGF("Could not create piRenderer"); } wchar_t tmpFolder[1024]; swprintf(tmpFolder, 1023, L"%s/tmp", getAssetDirectory()); immPlayer.pLog = new piLog(); immPlayer.pTimer = new piTimer(); immPlayer.soundEngineBackend = piSoundEngineAudioSDKBackend::Create(immPlayer.pLog); //WaitForDebuggerToAttach3(); if (!immPlayer.glesRenderer->Initialize(0, nullptr, 1, false, false, nullptr, false, nullptr)) { ALOGF("Could not initialize piRenderer"); } /*immPlayer.shaderManager = new MngrShaders(); if (!immPlayer.shaderManager->Init(immPlayer.glesRenderer, immPlayer.pLog)) { ALOGF("Could not Init Shader Manager"); }*/ piSoundEngineBackend::Configuration config; config.mLowLatency = true; // enable android fast-path if (!immPlayer.soundEngineBackend->Init(nullptr, -1, &config)) { ALOGF("Can't init Audio360 soundEngineBackend"); } immPlayer.viewer = new Viewer(); // Setup analytics logging Viewer::OnDocumentStateChange logAnalyticsEvents = [](Player::LoadingState loadingState) { switch (loadingState) { case ImmPlayer::Player::LoadingState::Loaded: sendMessage(UpdateViewpoints, std::string("")); break; default: break; } }; immPlayer.viewer->ReplaceLoadingStateChangeListener(logAnalyticsEvents); if (quillPath != nullptr && !loadQuillPath(quillPath, renderingTechnique)) { ALOGW("Can't init Quill Viewer %ls", quillPath); } immPlayerState.rasterState[0] = immPlayer.glesRenderer->CreateRasterState(false, false, piRenderer::CullMode::BACK, true, false); // left controller: single sided, flip YES immPlayerState.rasterState[1] = immPlayer.glesRenderer->CreateRasterState(false, true, piRenderer::CullMode::BACK, true, false); // right controller: single sided, flip NO #ifdef LOCALIZED_TEXT createTextTexture(); initTextTexture(java); #endif } void destroyQuillPlayer() { ALOGW("destroyQuillPlayer"); if (immPlayer.viewer == nullptr) { ALOGW("destroyQuillPlayer quill already null"); return; } immPlayer.glesRenderer->DestroyRasterState(immPlayerState.rasterState[0]); immPlayer.glesRenderer->DestroyRasterState(immPlayerState.rasterState[1]); /*if (immPlayer.errorMessage != nullptr) { immPlayer.errorMessage->Destroy(immPlayer.glesRenderer); immPlayer.errorMessage->Deinit(true); delete immPlayer.errorMessage; immPlayer.errorMessage = nullptr; }*/ immPlayer.viewer->Deinit(); immPlayer.initialized = false; delete immPlayer.viewer; immPlayer.viewer = nullptr; immPlayer.soundEngineBackend->Deinit(); piSoundEngineAudioSDKBackend::Destroy(immPlayer.soundEngineBackend); immPlayer.soundEngineBackend = nullptr; #ifdef LOCALIZED_TEXT destroyTextTexture(); #endif immPlayer.glesRenderer->Deinitialize(); delete immPlayer.glesRenderer; immPlayer.glesRenderer = nullptr; immPlayer.pLog->End(); delete immPlayer.pLog; immPlayer.pLog = nullptr; immPlayer.pTimer->End(); delete immPlayer.pTimer; immPlayer.pTimer = nullptr; // Reset Quill Player state for each Quill launch resetQuillPlayerState(); } // endregion typedef struct { ovrFramebuffer FrameBuffer[VRAPI_FRAME_LAYER_EYE_MAX]; int NumBuffers; } ovrRenderer; static void ovrRenderer_Clear( ovrRenderer * renderer ) { ALOGV("ovrRenderer_Clear"); for ( int eye = 0; eye < VRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { ovrFramebuffer_Clear( &renderer->FrameBuffer[eye] ); } renderer->NumBuffers = VRAPI_FRAME_LAYER_EYE_MAX; } static void ovrRenderer_Create( ovrRenderer * renderer, const ovrJava * java, const bool useMultiview ) { renderer->NumBuffers = useMultiview ? 1 : VRAPI_FRAME_LAYER_EYE_MAX; // Use defaults to support next gen headsets correctly. int defaultWidth = vrapi_GetSystemPropertyInt( java, VRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_WIDTH ); int defaultHeight = vrapi_GetSystemPropertyInt( java, VRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_HEIGHT ); // Allow overriding eye buffer scale by compile time constants or by runtime state. requestedEyeBufferWidth = EYE_BUFFER_WIDTH != 0 ? EYE_BUFFER_WIDTH : defaultWidth; requestedEyeBufferHeight = EYE_BUFFER_HEIGHT != 0 ? EYE_BUFFER_HEIGHT : defaultHeight; int width = static_cast<int>(requestedEyeBufferWidth * immPlayerState.requestedEyeBufferScale); int height = static_cast<int>(requestedEyeBufferHeight * immPlayerState.requestedEyeBufferScale); ALOGV("ovrRenderer_Create... multiview %s eye buffer size: %ix%i", useMultiview ? "enabled" : "disabled", width, height); // Create the frame buffers. for ( int eye = 0; eye < renderer->NumBuffers; eye++ ) { ovrFramebuffer_Create( &renderer->FrameBuffer[eye], useMultiview, VRAPI_TEXTURE_FORMAT_8888_sRGB, width, height, NUM_MULTI_SAMPLES ); } } static void ovrRenderer_Destroy( ovrRenderer * renderer ) { for ( int eye = 0; eye < renderer->NumBuffers; eye++ ) { ovrFramebuffer_Destroy( &renderer->FrameBuffer[eye] ); } } static ovrLayerProjection2 ovrRenderer_RenderDownloadProgress( ovrRenderer * renderer, const ovrJava * java, const ovrTracking2 * tracking, ovrMobile * ovr, long long frameIndex ) { #if REDUCED_LATENCY // Update orientation, not position. ovrTracking2 updatedTracking = vrapi_GetPredictedTracking2( ovr, tracking->HeadPose.TimeInSeconds ); updatedTracking.HeadPose.Pose.Position = tracking->HeadPose.Pose.Position; #else ovrTracking2 updatedTracking = *tracking; #endif const double frameTime = vrapi_GetPredictedDisplayTime(ovr, frameIndex); ovrLayerProjection2 layer = vrapi_DefaultLayerProjection2(); layer.HeadPose = updatedTracking.HeadPose; for ( int eye = 0; eye < VRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { ovrFramebuffer * frameBuffer = &renderer->FrameBuffer[renderer->NumBuffers == 1 ? 0 : eye]; layer.Textures[eye].ColorSwapChain = frameBuffer->ColorTextureSwapChain; layer.Textures[eye].SwapChainIndex = frameBuffer->TextureSwapChainIndex; layer.Textures[eye].TexCoordsFromTanAngles = ovrMatrix4f_TanAngleMatrixFromProjection( &updatedTracking.Eye[eye].ProjectionMatrix ); } layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_CHROMATIC_ABERRATION_CORRECTION; //layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_INHIBIT_SRGB_FRAMEBUFFER; // Enable for PTW. //layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_POSITIONAL_TIME_WARP; // QuillPlayer needs world-to-head, head-to-left-eye, head-to-right-eye, projection-left-eye, projection-right-eye matrices. // world-to-head we can get from the head pose. The head-to-eye matrices we need to calculate from the view matrix. const mat4x4 rot = mat4x4::rotate(quat(&updatedTracking.HeadPose.Pose.Orientation.x)); const mat4x4 tra = mat4x4::translate(-updatedTracking.HeadPose.Pose.Position.x, -updatedTracking.HeadPose.Pose.Position.y, -updatedTracking.HeadPose.Pose.Position.z); const mat4x4d worldToHead = f2d(transpose(rot) * tra); const mat4x4 headToLEye = mat4x4(updatedTracking.Eye[0].ViewMatrix.M[0]) * d2f(invert(worldToHead)); const mat4x4 headToREye = mat4x4(updatedTracking.Eye[1].ViewMatrix.M[0]) * d2f(invert(worldToHead)); const mat4x4 projectionLEye = mat4x4(updatedTracking.Eye[0].ProjectionMatrix.M[0]); const mat4x4 projectionREye = mat4x4(updatedTracking.Eye[1].ProjectionMatrix.M[0]); // Render the eye images. If using multiview NumBuffers=1 and we'll simultaneously render to the 2D texture array layers. for ( int eye = 0; eye < renderer->NumBuffers; eye++ ) { // NOTE: In the non-mv case, latency can be further reduced by updating the sensor prediction // for each eye (updates orientation, not position) ovrFramebuffer *frameBuffer = &renderer->FrameBuffer[eye]; ovrFramebuffer_SetCurrent(frameBuffer); GL( glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ) ); GL(glEnable(GL_SCISSOR_TEST)); GL(glViewport(0, 0, frameBuffer->Width, frameBuffer->Height)); GL(glScissor(0, 0, frameBuffer->Width, frameBuffer->Height)); immPlayer.glesRenderer->SetState(piSTATE_DEPTH_CLAMP, true); immPlayer.glesRenderer->SetState(piSTATE_FRONT_FACE, true); immPlayer.glesRenderer->SetState(piSTATE_CULL_FACE, true); immPlayer.glesRenderer->SetState(piSTATE_ALPHA_TO_COVERAGE, false); immPlayer.glesRenderer->SetState(piSTATE_DEPTH_TEST, true); immPlayer.glesRenderer->SetState(piSTATE_BLEND, true); immPlayer.glesRenderer->SetBlending(0, piRenderer::BlendEquation::piBLEND_ADD, piRenderer::BlendOperations::piBLEND_SRC_ALPHA, piRenderer::BlendOperations::piBLEND_ONE_MINUS_SRC_ALPHA, piRenderer::BlendEquation::piBLEND_ADD, piRenderer::BlendOperations::piBLEND_SRC_ALPHA, piRenderer::BlendOperations::piBLEND_ONE_MINUS_SRC_ALPHA); GL( glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ); // Explicitly clear the border texels to black when GL_CLAMP_TO_BORDER is not available. if (!getGLExtensions().EXT_texture_border_clamp) { // Clear to fully opaque black. GL( glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ) ); // bottom GL( glScissor( 0, 0, frameBuffer->Width, 1 ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // top GL( glScissor( 0, frameBuffer->Height - 1, frameBuffer->Width, 1 ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // left GL( glScissor( 0, 0, 1, frameBuffer->Height ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // right GL( glScissor( frameBuffer->Width - 1, 0, 1, frameBuffer->Height ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); } ovrFramebuffer_Resolve( frameBuffer ); ovrFramebuffer_Advance( frameBuffer ); } ovrFramebuffer_SetNone(); return layer; } static ovrLayerProjection2 ovrRenderer_RenderFrame( ovrRenderer * renderer, ovrJava * java, const ovrTracking2 * tracking, ovrMobile * ovr, long long frameIndex ) { #if REDUCED_LATENCY // Update orientation, not position. ovrTracking2 updatedTracking = vrapi_GetPredictedTracking2( ovr, tracking->HeadPose.TimeInSeconds ); updatedTracking.HeadPose.Pose.Position = tracking->HeadPose.Pose.Position; #else ovrTracking2 updatedTracking = *tracking; #endif // Handle don & doff, do not render or play sounds while doffed if (vrapi_GetSystemStatusInt(java, VRAPI_SYS_STATUS_MOUNTED) == VRAPI_TRUE) { if (immPlayerState.hmdWorn==false) { ALOGV("donning headset"); immPlayerState.hmdWorn=true; if (immPlayer.viewer->IsPaused(0)) { immPlayer.viewer->Resume(0, immPlayer.pTimer->GetTimeTicks()); } resetTracking = true; } } else { if(immPlayerState.hmdWorn==true) { ALOGV("doffing headset"); immPlayerState.hmdWorn=false; if (!immPlayer.viewer->IsPaused(0)) { immPlayer.viewer->Pause(0, immPlayer.pTimer->GetTimeTicks()); } // we still need to render this frame to stop sounds } else { // do not render subsequent frames return vrapi_DefaultLayerBlackProjection2(); } } const double frameTime = vrapi_GetPredictedDisplayTime(ovr, frameIndex); if (resetTracking) { ALOGV( "resetting tracking to %s level", vrTrackingTransformLevel == VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_EYE_LEVEL ? "eye" : "floor"); vrapi_SetTrackingSpace(ovr, vrTrackingTransformLevel == VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_EYE_LEVEL ? VRAPI_TRACKING_SPACE_LOCAL : VRAPI_TRACKING_SPACE_LOCAL_FLOOR); resetTracking = false; } ovrLayerProjection2 layer = vrapi_DefaultLayerProjection2(); layer.HeadPose = updatedTracking.HeadPose; for ( int eye = 0; eye < VRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { ovrFramebuffer * frameBuffer = &renderer->FrameBuffer[renderer->NumBuffers == 1 ? 0 : eye]; layer.Textures[eye].ColorSwapChain = frameBuffer->ColorTextureSwapChain; layer.Textures[eye].SwapChainIndex = frameBuffer->TextureSwapChainIndex; layer.Textures[eye].TexCoordsFromTanAngles = ovrMatrix4f_TanAngleMatrixFromProjection( &updatedTracking.Eye[eye].ProjectionMatrix ); } layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_CHROMATIC_ABERRATION_CORRECTION; //layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_INHIBIT_SRGB_FRAMEBUFFER; // Enable for PTW. //layer.Header.Flags |= VRAPI_FRAME_LAYER_FLAG_POSITIONAL_TIME_WARP; // QuillPlayer needs world-to-head, head-to-left-eye, head-to-right-eye, projection-left-eye, projection-right-eye matrices. // world-to-head we can get from the head pose. The head-to-eye matrices we need to calculate from the view matrix. const mat4x4 rot = mat4x4::rotate(quat(&updatedTracking.HeadPose.Pose.Orientation.x)); mat4x4 tra = mat4x4::translate(-updatedTracking.HeadPose.Pose.Position.x, -updatedTracking.HeadPose.Pose.Position.y, -updatedTracking.HeadPose.Pose.Position.z); // Head mat4x4d worldToHead = f2d(transpose(rot) * tra); mat4x4d headToLEye = f2d(mat4x4(updatedTracking.Eye[0].ViewMatrix.M[0])) * invert(worldToHead); mat4x4d headToREye = f2d(mat4x4(updatedTracking.Eye[1].ViewMatrix.M[0])) * invert(worldToHead); mat4x4 projectionLEye = mat4x4(updatedTracking.Eye[0].ProjectionMatrix.M[0]); mat4x4 projectionREye = mat4x4(updatedTracking.Eye[1].ProjectionMatrix.M[0]); #if 0 // TODO build head projection matrix for both eyes float leftLeft, leftRight, leftUp, leftDown; ovrMatrix4f_ExtractFov(&updatedTracking.Eye[0].ProjectionMatrix, &leftLeft, &leftRight, &leftUp, &leftDown); float rightLeft, rightRight, rightUp, rightDown; ovrMatrix4f_ExtractFov(&updatedTracking.Eye[1].ProjectionMatrix, &rightLeft, &rightRight, &rightUp, &rightDown); const vec2 nearFar = getNearFar_FromPerspectiveMatrix(projectionLEye); mat4x4 projectionHead = mat4x4(ovrMatrix4f_CreateProjectionAsymmetricFov(leftLeft,rightRight,leftUp,leftDown,nearFar.x,nearFar.y).M[0]); #endif DisplayRenderState displayRenderState; // Render the eye images. If using multiview NumBuffers=1 and we'll simultaneously render to the 2D texture array layers. for ( int eye = 0; eye < renderer->NumBuffers; eye++ ) { // NOTE: In the non-mv case, latency can be further reduced by updating the sensor prediction // for each eye (updates orientation, not position) ovrFramebuffer *frameBuffer = &renderer->FrameBuffer[eye]; ovrFramebuffer_SetCurrent(frameBuffer); GL(glEnable(GL_SCISSOR_TEST)); GL(glDepthMask(GL_TRUE)); GL(glEnable(GL_DEPTH_TEST)); GL(glDepthFunc(GL_LEQUAL)); GL(glEnable(GL_CULL_FACE)); GL(glCullFace(GL_BACK)); GL(glViewport(0, 0, frameBuffer->Width, frameBuffer->Height)); GL(glScissor(0, 0, frameBuffer->Width, frameBuffer->Height)); const double time = immPlayer.pTimer->GetTime() - immPlayerState.startTime; const float dtime = float(time - immPlayerState.oldTime); immPlayerState.oldTime = time; const ivec2 resolution(EYE_BUFFER_WIDTH, EYE_BUFFER_HEIGHT); // TODO: populate controller and handle input directly in Viewer. // Can create multiple navigation models with a shared interface. piVRHMD::Controller controller; // For mono rendering, we'll just use the perf info from the left eye so we don't get // different values rendered because of asymmetric eye matrices. if (eye == 0) { immPlayerState.lastPerformanceInfo = immPlayer.viewer->GetPerformanceInfoForFrame(); } const trans3d &transWorldToHead = fromMatrix(worldToHead); if (STEREO_MODE == ImmPlayer::StereoMode::None) { ImmCore::mat4x4 viewer2eyeProjection = eye == 0 ? projectionLEye * d2f(headToLEye) : projectionREye * d2f(headToREye); #if defined(PERFORMANCE_TESTING) const trans3d transPlayerWorldToHead = fromMatrix(worldToHead) * fromMatrix(quillState.playerCamera.GetWorldToCamera()); #else const trans3d transPlayerWorldToHead = transWorldToHead * fromMatrix(immPlayerState.playerCamera.GetWorldToCamera()) ; #endif if (eye == 0) { immPlayer.viewer->GlobalWork(nullptr, true, transPlayerWorldToHead, &controller, nullptr, immPlayer.pLog, dtime, resolution, true, RENDER_BUDGET_MICROSECONDS, immPlayerState.isFirstFrame); } immPlayer.viewer->GlobalRender(transPlayerWorldToHead, viewer2eyeProjection); immPlayer.viewer->RenderMono(resolution, transPlayerWorldToHead, eye); } else { const trans3d transPlayerWorldToHead = transWorldToHead * fromMatrix(immPlayerState.playerCamera.GetWorldToCamera()); if (STEREO_MODE == ImmPlayer::StereoMode::Fallback) { mat4x4d headToEye = eye == 0 ? headToLEye : headToREye; mat4x4 eyeProjection = eye == 0 ? projectionLEye : projectionREye; if (eye == 0) { immPlayer.viewer->GlobalWork(nullptr, true, transPlayerWorldToHead, &controller, nullptr, immPlayer.pLog, dtime, resolution, true, RENDER_BUDGET_MICROSECONDS, immPlayerState.isFirstFrame); immPlayer.viewer->GlobalRender(transPlayerWorldToHead, projectionLEye); // TODO schevrel: this should be head projection } immPlayer.viewer->RenderStereoMultiPass(resolution, eye, headToEye, eyeProjection, transPlayerWorldToHead ); } else if (STEREO_MODE == ImmPlayer::StereoMode::Preferred) { immPlayer.viewer->GlobalWork(nullptr, true, transPlayerWorldToHead, &controller, nullptr, immPlayer.pLog, dtime, resolution, true, RENDER_BUDGET_MICROSECONDS, immPlayerState.isFirstFrame); immPlayer.viewer->GlobalRender(transPlayerWorldToHead, projectionLEye); // TODO schevrel: this should be head projection immPlayer.viewer->RenderStereoSinglePass(resolution, transPlayerWorldToHead, headToLEye, projectionLEye, headToREye, projectionREye, nullptr); } } // Explicitly clear the border texels to black when GL_CLAMP_TO_BORDER is not available. if (!getGLExtensions().EXT_texture_border_clamp) { // Clear to fully opaque black. GL( glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ) ); // bottom GL( glScissor( 0, 0, frameBuffer->Width, 1 ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // top GL( glScissor( 0, frameBuffer->Height - 1, frameBuffer->Width, 1 ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // left GL( glScissor( 0, 0, 1, frameBuffer->Height ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); // right GL( glScissor( frameBuffer->Width - 1, 0, 1, frameBuffer->Height ) ); GL( glClear( GL_COLOR_BUFFER_BIT ) ); } ovrFramebuffer_Resolve( frameBuffer ); ovrFramebuffer_Advance( frameBuffer ); } ovrFramebuffer_SetNone(); if (immPlayer.soundEngineBackend != nullptr) immPlayer.soundEngineBackend->Tick(); return layer; } static ovrLayerLoadingIcon2 ovrRenderer_RenderTimewarpLoadingIcon(const long long frameIndex) { // Show a loading icon until the file is loaded. ovrLayerLoadingIcon2 iconLayer = vrapi_DefaultLayerLoadingIcon2(); const int frameCount = 52; if (immPlayerState.loadingSwapChain == nullptr) { immPlayerState.loadingSwapChain = vrapi_CreateTextureSwapChain( VRAPI_TEXTURE_TYPE_2D, VRAPI_TEXTURE_FORMAT_8888, 64, 64, 1, true ); } const int length = vrapi_GetTextureSwapChainLength(immPlayerState.loadingSwapChain ); if (immPlayerState.loadingFbo == nullptr) { immPlayerState.loadingFbo = (GLuint*)malloc(length*sizeof(GLuint)); glGenFramebuffers(length, immPlayerState.loadingFbo ); } if (immPlayerState.loadingStartFrame == 0) { immPlayerState.loadingStartFrame = frameIndex; } iconLayer.ColorSwapChain = immPlayerState.loadingSwapChain; iconLayer.SpinSpeed = 0.0; iconLayer.SwapChainIndex = immPlayerState.loadingSwapIndex; iconLayer.SpinScale = 16.0f; return iconLayer; } // endregion // region ovrRenderThread (#if MULTI_THREADED) #if MULTI_THREADED typedef enum { RENDER_FRAME, RENDER_LOADING_ICON, RENDER_BLACK_FINAL } ovrRenderType; typedef struct { JavaVM * JavaVm; jobject ActivityObject; const ovrEgl * ShareEgl; pthread_t Thread; int Tid; bool UseMultiview; // Synchronization bool Exit; bool WorkAvailableFlag; bool WorkDoneFlag; pthread_cond_t WorkAvailableCondition; pthread_cond_t WorkDoneCondition; pthread_mutex_t Mutex; // Latched data for rendering. ovrMobile * Ovr; ovrRenderType RenderType; long long FrameIndex; double DisplayTime; int SwapInterval; ovrTracking2 Tracking; } ovrRenderThread; void * RenderThreadFunction( void * parm ) { ovrRenderThread * renderThread = (ovrRenderThread *)parm; renderThread->Tid = gettid(); ovrJava java; java.Vm = renderThread->JavaVm; (java.Vm)->AttachCurrentThread( &java.Env, NULL ); java.ActivityObject = renderThread->ActivityObject; // Note that AttachCurrentThread will reset the thread name. prctl( PR_SET_NAME, (long)"OVR::Renderer", 0, 0, 0 ); ovrEgl egl; ovrEgl_CreateContext( &egl, renderThread->ShareEgl ); ovrRenderer renderer; ovrRenderer_Create( &renderer, &java, renderThread->UseMultiview ); for( ; ; ) { // Signal work completed. pthread_mutex_lock( &renderThread->Mutex ); renderThread->WorkDoneFlag = true; pthread_cond_signal( &renderThread->WorkDoneCondition ); pthread_mutex_unlock( &renderThread->Mutex ); // Wait for work. pthread_mutex_lock( &renderThread->Mutex ); while ( !renderThread->WorkAvailableFlag ) { pthread_cond_wait( &renderThread->WorkAvailableCondition, &renderThread->Mutex ); } renderThread->WorkAvailableFlag = false; pthread_mutex_unlock( &renderThread->Mutex ); // Check for exit. if ( renderThread->Exit ) { break; } // Render. ovrLayer_Union2 layers[ovrMaxLayerCount] = {}; int layerCount = 0; int frameFlags = 0; if ( renderThread->RenderType == RENDER_FRAME ) { ovrLayerProjection2 layer; layer = ovrRenderer_RenderFrame( &renderer, &java, &renderThread->Tracking, renderThread->Ovr ); layers[layerCount++].Projection = layer; } else if ( renderThread->RenderType == RENDER_LOADING_ICON ) { ovrLayerProjection2 blackLayer = vrapi_DefaultLayerBlackProjection2(); layers[layerCount++].Projection = blackLayer; ovrLayerLoadingIcon2 iconLayer = vrapi_DefaultLayerLoadingIcon2(); layers[layerCount++].LoadingIcon = iconLayer; frameFlags |= VRAPI_FRAME_FLAG_FLUSH; } else if ( renderThread->RenderType == RENDER_BLACK_FINAL ) { ovrLayerProjection2 layer = vrapi_DefaultLayerBlackProjection2(); layers[layerCount++].Projection = layer; frameFlags |= VRAPI_FRAME_FLAG_FLUSH | VRAPI_FRAME_FLAG_FINAL; } const ovrLayerHeader2 * layerList[ovrMaxLayerCount] = {}; for ( int i = 0; i < layerCount; i++ ) { layerList[i] = &layers[i].Header; } ovrSubmitFrameDescription2 frameDesc = {}; frameDesc.Flags = frameFlags; frameDesc.SwapInterval = renderThread->SwapInterval; frameDesc.FrameIndex = renderThread->FrameIndex; frameDesc.DisplayTime = renderThread->DisplayTime; frameDesc.LayerCount = layerCount; frameDesc.Layers = layerList; vrapi_SubmitFrame2( renderThread->Ovr, &frameDesc ); } ovrRenderer_Destroy( &renderer ); ovrEgl_DestroyContext( &egl ); (java.Vm)->DetachCurrentThread(); return NULL; } static void ovrRenderThread_Clear( ovrRenderThread * renderThread ) { renderThread->JavaVm = NULL; renderThread->ActivityObject = NULL; renderThread->ShareEgl = NULL; renderThread->Thread = 0; renderThread->Tid = 0; renderThread->UseMultiview = false; renderThread->Exit = false; renderThread->WorkAvailableFlag = false; renderThread->WorkDoneFlag = false; renderThread->Ovr = NULL; renderThread->RenderType = RENDER_FRAME; renderThread->FrameIndex = 1; renderThread->DisplayTime = 0; renderThread->SwapInterval = 1; renderThread->Scene = NULL; } static void ovrRenderThread_Create( ovrRenderThread * renderThread, const ovrJava * java, const ovrEgl * shareEgl, const bool useMultiview ) { renderThread->JavaVm = java->Vm; renderThread->ActivityObject = java->ActivityObject; renderThread->ShareEgl = shareEgl; renderThread->Thread = 0; renderThread->Tid = 0; renderThread->UseMultiview = useMultiview; renderThread->Exit = false; renderThread->WorkAvailableFlag = false; renderThread->WorkDoneFlag = false; pthread_cond_init( &renderThread->WorkAvailableCondition, NULL ); pthread_cond_init( &renderThread->WorkDoneCondition, NULL ); pthread_mutex_init( &renderThread->Mutex, NULL ); const int createErr = pthread_create( &renderThread->Thread, NULL, RenderThreadFunction, renderThread ); if ( createErr != 0 ) { ALOGF( "pthread_create returned %i", createErr ); } } static void ovrRenderThread_Destroy( ovrRenderThread * renderThread ) { pthread_mutex_lock( &renderThread->Mutex ); renderThread->Exit = true; renderThread->WorkAvailableFlag = true; pthread_cond_signal( &renderThread->WorkAvailableCondition ); pthread_mutex_unlock( &renderThread->Mutex ); pthread_join( renderThread->Thread, NULL ); pthread_cond_destroy( &renderThread->WorkAvailableCondition ); pthread_cond_destroy( &renderThread->WorkDoneCondition ); pthread_mutex_destroy( &renderThread->Mutex ); } static void ovrRenderThread_Submit( ovrRenderThread * renderThread, ovrMobile * ovr, ovrRenderType type, long long frameIndex, double displayTime, int swapInterval, const ovrTracking2 * tracking ) { // Wait for the renderer thread to finish the last frame. pthread_mutex_lock( &renderThread->Mutex ); while ( !renderThread->WorkDoneFlag ) { pthread_cond_wait( &renderThread->WorkDoneCondition, &renderThread->Mutex ); } renderThread->WorkDoneFlag = false; // Latch the render data. renderThread->Ovr = ovr; renderThread->RenderType = type; renderThread->FrameIndex = frameIndex; renderThread->DisplayTime = displayTime; renderThread->SwapInterval = swapInterval; if ( tracking != NULL ) { renderThread->Tracking = *tracking; } // Signal work is available. renderThread->WorkAvailableFlag = true; pthread_cond_signal( &renderThread->WorkAvailableCondition ); pthread_mutex_unlock( &renderThread->Mutex ); } static void ovrRenderThread_Wait( ovrRenderThread * renderThread ) { // Wait for the renderer thread to finish the last frame. pthread_mutex_lock( &renderThread->Mutex ); while ( !renderThread->WorkDoneFlag ) { pthread_cond_wait( &renderThread->WorkDoneCondition, &renderThread->Mutex ); } pthread_mutex_unlock( &renderThread->Mutex ); } static int ovrRenderThread_GetTid( ovrRenderThread * renderThread ) { ovrRenderThread_Wait( renderThread ); return renderThread->Tid; } #endif // MULTI_THREADED // endregion // region ovrApp typedef struct { ovrJava Java; ovrEgl Egl; ANativeWindow * NativeWindow; bool Resumed; ovrMobile * Ovr; long long FrameIndex; double DisplayTime; int SwapInterval; ovrPerformanceParms PerformanceParms; bool BackButtonDownLastFrame; #if MULTI_THREADED ovrRenderThread RenderThread; #else ovrRenderer Renderer; #endif bool UseMultiview; } ovrApp; static void ovrApp_Clear( ovrApp * app ) { app->Java.Vm = NULL; app->Java.Env = NULL; app->Java.ActivityObject = NULL; app->NativeWindow = NULL; app->Resumed = false; app->Ovr = NULL; app->FrameIndex = 1; app->DisplayTime = 0; app->SwapInterval = 1; app->PerformanceParms = vrapi_DefaultPerformanceParms(); app->BackButtonDownLastFrame = false; app->UseMultiview = false; ovrEgl_Clear( &app->Egl ); #if MULTI_THREADED ovrRenderThread_Clear( &app->RenderThread ); #else ovrRenderer_Clear( &app->Renderer ); #endif } static void ovrApp_PushBlackFinal( ovrApp * app ) { #if MULTI_THREADED ovrRenderThread_Submit( &app->RenderThread, app->Ovr, RENDER_BLACK_FINAL, app->FrameIndex, app->DisplayTime, app->SwapInterval, NULL, NULL, NULL ); #else int frameFlags = 0; frameFlags |= VRAPI_FRAME_FLAG_FLUSH | VRAPI_FRAME_FLAG_FINAL; ovrLayerProjection2 layer = vrapi_DefaultLayerBlackProjection2(); const ovrLayerHeader2 * layers[] = { &layer.Header }; ovrSubmitFrameDescription2 frameDesc = {}; frameDesc.Flags = frameFlags; frameDesc.SwapInterval = 1; frameDesc.FrameIndex = app->FrameIndex; frameDesc.DisplayTime = app->DisplayTime; frameDesc.LayerCount = 1; frameDesc.Layers = layers; vrapi_SubmitFrame2( app->Ovr, &frameDesc ); #endif } static void ovrApp_HandleVrModeChanges( ovrApp * app ) { ALOGV( " vrapi_HandleVrModeChange()" ); if ( app->Resumed != false && app->NativeWindow != NULL ) { if ( app->Ovr == NULL ) { ovrModeParms parms = vrapi_DefaultModeParms( &app->Java ); // No need to reset the FLAG_FULLSCREEN window flag when using a View parms.Flags &= ~VRAPI_MODE_FLAG_RESET_WINDOW_FULLSCREEN; // We definitely want high quality sRGB filtering. // parms.Flags |= VRAPI_MODE_FLAG_FRONT_BUFFER_SRGB; // parms.Flags |= VRAPI_MODE_FLAG_FRONT_BUFFER_565; parms.Flags |= VRAPI_MODE_FLAG_NATIVE_WINDOW; parms.Display = (size_t)app->Egl.Display; parms.WindowSurface = (size_t)app->NativeWindow; parms.ShareContext = (size_t)app->Egl.Context; ALOGV( " eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) ); ALOGV( " vrapi_EnterVrMode()" ); app->Ovr = vrapi_EnterVrMode( &parms ); ALOGV( " eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) ); // If entering VR mode failed then the ANativeWindow was not valid. if ( app->Ovr == NULL ) { ALOGF( "Invalid ANativeWindow!" ); app->NativeWindow = NULL; } // Set performance parameters once we have entered VR mode and have a valid ovrMobile. if ( app->Ovr != NULL ) { vrapi_SetClockLevels( app->Ovr, app->PerformanceParms.CpuLevel, app->PerformanceParms.GpuLevel ); ALOGV( " vrapi_SetClockLevels( %d, %d )", app->PerformanceParms.CpuLevel, app->PerformanceParms.GpuLevel ); vrapi_SetPerfThread( app->Ovr, VRAPI_PERF_THREAD_TYPE_MAIN, app->PerformanceParms.MainThreadTid ); ALOGV( " vrapi_SetPerfThread( MAIN, %d )", app->PerformanceParms.MainThreadTid ); vrapi_SetPerfThread( app->Ovr, VRAPI_PERF_THREAD_TYPE_RENDERER, app->PerformanceParms.RenderThreadTid ); ALOGV( " vrapi_SetPerfThread( RENDERER, %d )", app->PerformanceParms.RenderThreadTid ); // Use fixed foveated rendering with TBR. vrapi_SetPropertyInt( &app->Java, VRAPI_FOVEATION_LEVEL, 2); // Use extra latency mode. vrapi_SetExtraLatencyMode( app->Ovr, VRAPI_EXTRA_LATENCY_MODE_ON ); } } requestResetTracking(); } else { if ( app->Ovr != NULL ) { #if MULTI_THREADED // Make sure the renderer thread is no longer using the ovrMobile. ovrRenderThread_Wait( &app->RenderThread ); #endif ALOGV( " eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) ); ALOGV( " vrapi_LeaveVrMode()" ); vrapi_LeaveVrMode( app->Ovr ); app->Ovr = NULL; ALOGV( " eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface( EGL_DRAW ) ); } } } static void ovrApp_HandleInput(ovrApp * app, ANativeActivity * activity) { if (shutdownRequested) { return; } bool backButtonDownThisFrame = false; vec3d moveDistance = vec3d(0.0, 0.0, 0.0); int orientationDelta = 0; bool enableDevTools = immPlayerState.allowDevToolsInHeadless || !immPlayerState.buildFlavorHeadless; bool gripTriggersAndJoystickButtonsPressed = true; bool gripTriggersAndJoystickButtonsPressedLastFrame = true; for (uint32_t deviceIndex = 0; ; deviceIndex++) { ovrInputCapabilityHeader capsHeader; ovrResult result = vrapi_EnumerateInputDevices( app->Ovr, deviceIndex, &capsHeader ); if ( result < 0 ) { break; } if ( capsHeader.Type == ovrControllerType_TrackedRemote ) { ovrInputStateTrackedRemote trackedRemoteState; trackedRemoteState.Header.ControllerType = ovrControllerType_TrackedRemote; result = vrapi_GetCurrentInputState( app->Ovr, capsHeader.DeviceID, &trackedRemoteState.Header ); if ( result != ovrSuccess ) { ALOGW("Error(%i): Failed to get input state for hand %i", result, deviceIndex); continue; } backButtonDownThisFrame |= ( ( trackedRemoteState.Buttons & ovrButton_B ) != 0 || ( trackedRemoteState.Buttons & ovrButton_Back ) != 0 ); ovrInputTrackedRemoteCapabilities remoteCapabilities; remoteCapabilities.Header = capsHeader; result = vrapi_GetInputDeviceCapabilities( app->Ovr, &remoteCapabilities.Header ); if ( result != ovrSuccess ) { ALOGW("Error(%i): Failed to get input device capabilities for hand %i", result, deviceIndex); continue; } // Compare with last frame's button state for this hand's controller. uint32_t buttonsPressed = trackedRemoteState.Buttons & ~mRemoteDevices[deviceIndex].mButtonState; uint32_t buttonsReleased = ~trackedRemoteState.Buttons & mRemoteDevices[deviceIndex].mButtonState; bool isLeftHand = (remoteCapabilities.ControllerCapabilities & ovrControllerCaps_LeftHand) != 0; bool isRightHand = (remoteCapabilities.ControllerCapabilities & ovrControllerCaps_RightHand) != 0; gripTriggersAndJoystickButtonsPressed &= (trackedRemoteState.Buttons & ovrButton_GripTrigger) != 0 && (trackedRemoteState.Buttons & ovrButton_Joystick) != 0; gripTriggersAndJoystickButtonsPressedLastFrame &= (mRemoteDevices[deviceIndex].mButtonState & ovrButton_GripTrigger) != 0 && (mRemoteDevices[deviceIndex].mButtonState & ovrButton_Joystick) != 0; if (mRemoteDevices[deviceIndex].mRemoteDeviceID == RemoteDevice::ID_NONE) { mRemoteDevices[deviceIndex].mRemoteDeviceID = capsHeader.DeviceID; mRemoteDevices[deviceIndex].mHandID = isLeftHand ? HAND_ID_LEFT : (isRightHand ? HAND_ID_RIGHT : HAND_ID_COUNT); } else if (mRemoteDevices[deviceIndex].mRemoteDeviceID != capsHeader.DeviceID) { ALOGW("Expected device ID %i for hand %i instead got %i", mRemoteDevices[deviceIndex].mRemoteDeviceID, deviceIndex, capsHeader.DeviceID); } ovrTracking remoteTracking; result = vrapi_GetInputTrackingState( app->Ovr, capsHeader.DeviceID, app->DisplayTime, &remoteTracking ); if ( result != ovrSuccess ) { ALOGW("Could not get input tracking state for device %i", capsHeader.DeviceID); } // Save the controller pose for rendering. if (isLeftHand) { immPlayerState.latestLeftControllerPose = remoteTracking.HeadPose.Pose; } else if (isRightHand) { immPlayerState.latestRightControllerPose = remoteTracking.HeadPose.Pose; } mRemoteDevices[deviceIndex].mButtonState = trackedRemoteState.Buttons; // Dual joystick based player movement. Right joystick handles forward/back with Y and // left/right with X. Left joystick handles up/down with Y. Left/Right joystick press to // decrease/increase speed respectively. if ( enableDevTools && (remoteCapabilities.ControllerCapabilities & ovrControllerCaps_HasJoystick) ) { if ( isLeftHand ) { if ( buttonsReleased & ovrButton_Joystick ) { immPlayerState.playerSpeed = std::max(immPlayerState.playerSpeed /= 2.0, MIN_SPEED); ALOGV("Reduced speed to %.4f", immPlayerState.playerSpeed); } if (trackedRemoteState.Joystick.x > 0.9) { orientationDelta = JOYSTICK_ORIENTATION_SPEED; } else if (trackedRemoteState.Joystick.x < -0.9) { orientationDelta = -JOYSTICK_ORIENTATION_SPEED; } else { // Only move vertically if no horizontal movement is detected. moveDistance.y += trackedRemoteState.Joystick.y; } } else if (isRightHand) { if ( buttonsReleased & ovrButton_Joystick ) { immPlayerState.playerSpeed *= 2.0; ALOGV("Increased speed to %.4f", immPlayerState.playerSpeed); } moveDistance.x += trackedRemoteState.Joystick.x; moveDistance.z -= trackedRemoteState.Joystick.y; } } if ( buttonsReleased & ovrButton_Y ) { ALOGV("Y button released"); } if ( buttonsReleased & ovrButton_GripTrigger ) { ALOGV(" %s Grip trigger released", isLeftHand ? "Left" : "Right"); } if (buttonsReleased & ovrButton_A ) { const int docId = 0; if (immPlayer.viewer != nullptr && immPlayer.viewer->IsDocumentLoaded(docId)) { const int documentId = 0; if (immPlayer.viewer->IsWaiting(documentId)) immPlayer.viewer->Continue(documentId); } } } } // Secret combo to allow joystick controls and performance panel in headless (production) Quill // Player build flavor. Left and Right grip triggers and joystick buttons all pressed at the // same time. if (immPlayerState.buildFlavorHeadless && !gripTriggersAndJoystickButtonsPressedLastFrame && gripTriggersAndJoystickButtonsPressed) { immPlayerState.allowDevToolsInHeadless = !immPlayerState.allowDevToolsInHeadless; ALOGV("%s dev tools", immPlayerState.allowDevToolsInHeadless ? "enabling" : "disabling"); if (!immPlayerState.allowDevToolsInHeadless) { immPlayerState.playerCamera = piCameraD(); } } const double predictedDisplayTime = vrapi_GetPredictedDisplayTime( app->Ovr, app->FrameIndex ); const ovrTracking2 tracking = vrapi_GetPredictedTracking2( app->Ovr, predictedDisplayTime ); mat3x3d orientation = mat3x3d::rotate(quatd(tracking.HeadPose.Pose.Orientation.x, tracking.HeadPose.Pose.Orientation.y, tracking.HeadPose.Pose.Orientation.z, tracking.HeadPose.Pose.Orientation.w)); immPlayerState.playerCamera.LocalMove(immPlayerState.playerSpeed * (orientation * moveDistance)); immPlayerState.playerCamera.RotateXY(static_cast<double>(orientationDelta) * M_PI / 180.0, 0); bool backButtonDownLastFrame = app->BackButtonDownLastFrame; app->BackButtonDownLastFrame = backButtonDownThisFrame; const int docID = 0; // The document can't process an unload command until loading stage is finished. So we'll wait // till load is completed to register the back press. bool isLoading = immPlayer.viewer != nullptr && immPlayer.viewer->IsDocumentLoading(docID); // If back button is pressed we need to wait one frame to issue the document unload. if ( backButtonDownLastFrame && !backButtonDownThisFrame && !isLoading) { bool shouldConfirmExit = immPlayer.viewer->IsDocumentLoaded(docID) && immPlayer.viewer->GetChapterCount(docID) > 1; if (shouldConfirmExit && immPlayerState.confirmExitFrameCountdown == 0) { // Show the confirm dialog for ~3 seconds immPlayerState.confirmExitFrameCountdown = 216; } else { ALOGV( "back button short press" ); ALOGV( "unloading document... shutdown next frame" ); unloadAndResetOnExit(&app->Java); } } } // endregion // region Android Native Activity void tryPauseQuillPlayer() { int docID = 0; if (immPlayer.viewer != nullptr && immPlayer.viewer->IsDocumentLoaded(docID) && !immPlayer.viewer->IsPaused(docID)) { ALOGV("pausing quill player"); immPlayer.viewer->Pause(docID, immPlayer.pTimer->GetTimeTicks()); } } void tryResumeQuillPlayer() { int docID = 0; if (immPlayer.viewer != nullptr && immPlayer.viewer->IsDocumentLoaded(docID) && !immPlayer.viewer->IsPaused(docID)) { ALOGV("resuming quill player"); immPlayer.viewer->Resume(docID, immPlayer.pTimer->GetTimeTicks()); } } /** * Process the next main command. */ static void app_handle_cmd( struct android_app * app, int32_t cmd ) { ovrApp * appState = (ovrApp *)app->userData; switch ( cmd ) { // There is no APP_CMD_CREATE. The ANativeActivity creates the // application thread from onCreate(). The application thread // then calls android_main(). case APP_CMD_START: { ALOGV( "onStart()" ); ALOGV( " APP_CMD_START" ); shutdownRequested = false; didProcessUnloadOnBackPress = false; framesSinceStart = -1; break; } case APP_CMD_RESUME: { ALOGV( "onResume()" ); ALOGV( " APP_CMD_RESUME" ); appState->Resumed = true; tryResumeQuillPlayer(); break; } case APP_CMD_PAUSE: { ALOGV( "onPause()" ); ALOGV( " APP_CMD_PAUSE" ); appState->Resumed = false; tryPauseQuillPlayer(); break; } case APP_CMD_STOP: { ALOGV( "onStop()" ); ALOGV( " APP_CMD_STOP" ); break; } case APP_CMD_DESTROY: { ALOGV( "onDestroy()" ); ALOGV( " APP_CMD_DESTROY" ); appState->NativeWindow = NULL; shutdownRequested = true; break; } case APP_CMD_INIT_WINDOW: { ALOGV( "surfaceCreated()" ); ALOGV( " APP_CMD_INIT_WINDOW" ); appState->NativeWindow = app->window; break; } case APP_CMD_TERM_WINDOW: { ALOGV( "surfaceDestroyed()" ); ALOGV( " APP_CMD_TERM_WINDOW" ); appState->NativeWindow = NULL; break; } } } static void ovrApp_PushBlackFinal( ovrApp * app ); void processOVRMessages(const android_app * app, ovrJava * java) { if (!immPlayerState.buildFlavorHeadless) return; ovrMessageHandle message; while ((message = ovr_PopMessage()) != nullptr) { switch (ovr_Message_GetType(message)) { case ovrMessage_User_GetAccessToken: if (!ovr_Message_IsError(message)) { ALOGV("Received access token."); //reportAccessToken(java, ovr_Message_GetString(message), 1); ovr_FreeMessage(message); } else { ovrErrorHandle pError = ovr_Message_GetError(message); ALOGE("Access token request failed: %s", ovr_Error_GetMessage(pError)); //reportAccessToken(java, nullptr, 0); ovr_FreeMessage(message); } break; #if !defined(DEBUG) case ovrMessage_Entitlement_GetIsViewerEntitled: if (!immPlayerState.buildFlavorHeadless || isUserEntitled) { return; } if (!ovr_Message_IsError(message)) { ALOGV("Entitlement check passed."); // User is entitled. Continue with normal game behaviour ovr_FreeMessage(message); isUserEntitled = true; } else { ALOGE("Entitlement check failed! Received Error checking if user is entitled: %s", ovr_Message_GetString(message)); ovr_FreeMessage(message); ANativeActivity_finish(app->activity); } break; #endif default: break; } } } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main( struct android_app * app ) { ALOGV( "----------------------------------------------------------------" ); ALOGV( "android_app_entry()" ); ALOGV( " android_main()" ); ANativeActivity_setWindowFlags( app->activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0 ); ovrJava java; java.Vm = app->activity->vm; (java.Vm)->AttachCurrentThread( &java.Env, NULL ); java.ActivityObject = app->activity->clazz; // Note that AttachCurrentThread will reset the thread name. prctl( PR_SET_NAME, (long)"OVR::Main", 0, 0, 0 ); const ovrInitParms initParms = vrapi_DefaultInitParms( &java ); int32_t initResult = vrapi_Initialize( &initParms ); if ( initResult != VRAPI_INITIALIZE_SUCCESS ) { // NOTE - Use _Exit, which doesn't call static destructors. Calling static dtor's can be highly // problematic. For example, if a dtor uses another resources that is also a static global, // that resource could be destructed already, causing a crash. This gets around that by not // calling dtor's at all. The OS will release all memory from the process anyhow. _Exit(0); } ovrApp appState; ovrApp_Clear( &appState ); appState.Java = java; //WaitForDebuggerToAttach3(); if (immPlayerState.buildFlavorHeadless) { // Not sure if we actually need to do this but VrShell and Venues is... // Disable FBNS. We don't use it and it's a huge battery drain // If the API isn't found in Horizon, it gracefully falls back to no ConfigOptions ovrKeyValuePair options[1]; options[0] = ovr_ConfigOption_CreateInternal(ovrConfigOption_DisableFbns, true); // Initialization call ovr_PlatformInitializeAndroidWithOptions(APP_ID, java.ActivityObject, java.Env, options, 1); ovr_User_GetAccessToken(); #if !defined(DEBUG) ALOGV("ovrApp_PerformEntitlementCheck"); ovr_Entitlement_GetIsViewerEntitled(); #endif } ovrEgl_CreateContext( &appState.Egl, NULL ); // enableDebugMessageCallback(); EglInitExtensions(); appState.UseMultiview = STEREO_MODE == ImmPlayer::StereoMode::Preferred && ( getGLExtensions().multi_view ); ALOGV( "AppState UseMultiview : %d", appState.UseMultiview ); appState.PerformanceParms = vrapi_DefaultPerformanceParms(); appState.PerformanceParms.CpuLevel = CPU_LEVEL_MAX; appState.PerformanceParms.GpuLevel = GPU_LEVEL_MAX; appState.PerformanceParms.MainThreadTid = gettid(); #if MULTI_THREADED ovrRenderThread_Create( &appState.RenderThread, &appState.Java, &appState.Egl, appState.UseMultiview ); // Also set the renderer thread to SCHED_FIFO. appState.PerformanceParms.RenderThreadTid = ovrRenderThread_GetTid( &appState.RenderThread ); #else ovrRenderer_Create( &appState.Renderer, &java, appState.UseMultiview ); #endif app->userData = &appState; app->onAppCmd = app_handle_cmd; while ( app->destroyRequested == 0 ) { // Read all pending events. for ( ; ; ) { int events; struct android_poll_source * source; const int timeoutMilliseconds = ( appState.Ovr == NULL && app->destroyRequested == 0 ) ? -1 : 0; if ( ALooper_pollAll( timeoutMilliseconds, NULL, &events, (void **)&source ) < 0 ) { break; } // Process this event. if ( source != NULL ) { source->process( app, source ); } ovrApp_HandleVrModeChanges( &appState ); } // TODO: make FFovR changes into a Message if (immPlayerState.pendingFoveationChange) { // Adopt requested foveation level for render strategy vrapi_SetPropertyInt(&appState.Java, VRAPI_FOVEATION_LEVEL, immPlayerState.foveationLevel); immPlayerState.pendingFoveationChange = false; } // Try again next frame if we can't acquire the lock. if (messageQueueLock.try_lock()) { auto msg = messageQueue.begin(); while (msg != messageQueue.end()) { switch (msg->type) { case ErrorDisconnected: case ErrorUnknown: case LoadImmPath: { handleMessageLoadImmPath(*msg); msg = messageQueue.erase(msg); break; } case UpdateMetadata: { if (immPlayerState.textTexture.metaStatus== AppImmPlayerState::TextTexture::Status::READY) { #ifdef LOCALIZED_TEXT char *title = piws2str(quillState.metadata.title); char *artist = piws2str(quillState.metadata.artist); char *date = piws2str(quillState.metadata.date); char *description = piws2str(quillState.metadata.description); updateTextTextureMetadata(&java, title, artist, date, description); if (title != nullptr) free(title); if (artist != nullptr) free(artist); if (date != nullptr) free(date); if (description != nullptr) free(description); #endif immPlayerState.textTexture.metaStatus = AppImmPlayerState::TextTexture::Status::TEXTURE_UPDATED; } ++msg; // this msg will be processed again in renderViewpointsUI and erased there break; } default: ++msg; break; } } messageQueueLock.unlock(); } // TODO: make eye buffer changes into a Message // We received a request to scale the eye buffers after having created them prior to entering the render loop. if (appState.Renderer.FrameBuffer[0].Width != static_cast<int>(requestedEyeBufferWidth * immPlayerState.requestedEyeBufferScale)) { #if MULTI_THREADED == 0 ovrRenderer_Destroy( &appState.Renderer ); ovrRenderer_Create( &appState.Renderer, &java, appState.UseMultiview ); #endif } int docID = 0; // Shutdown requested by a back button process last frame. When unloading completes, we // clean-up state and redirect if necessary. if (shutdownRequested) { const bool isUnloaded = immPlayer.viewer == nullptr || !immPlayer.initialized || immPlayer.viewer->GetDocumentLoadState(docID) == ImmPlayer::Player::LoadingState::Unloaded; if (!isUnloaded && (immPlayer.initialized && immPlayer.viewer->GetDocumentLoadState(docID) != ImmPlayer::Player::LoadingState::Unloading)) { if (immPlayer.viewer->GetDocumentLoadState(docID) == ImmPlayer::Player::LoadingState::Loaded) { /*registerEngagementEvent( &appState.Java, EngagementEvent::View, immPlayer.viewer->GetViewTimeInMs(), immPlayer.viewer->GetChapterViewCount());*/ } immPlayer.viewer->Unload(docID); } if (!didProcessUnloadOnBackPress && isUnloaded) { ALOGV( " completed document unload clearing state..." ); ALOGV( " ovrApp_PushBlackFinal()" ); ovrApp_PushBlackFinal( &appState ); resetQuillPlayerState(); // TODO: remove or rename this // This no longer deeplinks to tv but instead lets the OS hand focus back to the last activity/panelapp //deepLinkToTV(&appState.Java); // Finish the activity in order to cancel any in flight network requests ANativeActivity_finish(app->activity); didProcessUnloadOnBackPress = true; // Will be reset in activity onStart() for next document. } if (isUnloaded) { // Wait for destroy after finish. continue; } } ovrApp_HandleInput( &appState, app->activity ); if ( appState.Ovr == NULL) { continue; } const bool isDownloadingDocument = immPlayerState.quillPath == "http"; // Try to initialize the Quill player. if (immPlayer.viewer == nullptr) { // Quill path will be set to http while a download is pending on the Java side. When // the file has completed downloading and been copied to the data directory, the path // will be updated by QuillPlayerVrActivity. if (!isDownloadingDocument) { // For Oculus store build try to load: // 1) quill path in intent extra // 2) /sdcard/Oculus/quill/default.imm or /sdcard/Oculus/quill/default if present // 3) goro_the_beast embedded in APK const wchar_t *qPath = nullptr; bool shouldFree = false; if (immPlayerState.quillPath.empty()) { vrTrackingTransformLevel = VRAPI_TRACKING_TRANSFORM_SYSTEM_CENTER_EYE_LEVEL; FILE *fp = fopen("/sdcard/Oculus/quill/default.imm", "rb"); if (fp) { fclose(fp); qPath = L"/sdcard/Oculus/quill/default.imm"; ALOGV(" Loading Quill: default.imm from disk"); } else if ((fp = fopen("/sdcard/Oculus/quill/default", "rb"))) { fclose(fp); qPath = L"/sdcard/Oculus/quill/default"; ALOGV(" Loading Quill: default authoring folder from disk"); } } else { qPath = pistr2ws(getQuillPath()); ALOGV(" Loading quill from activity intent: %ls", qPath); shouldFree = true; } initQuillPlayer(qPath, immPlayerState.renderingTechnique, &appState.Java); if (shouldFree) { free((void *) qPath); } ALOGV(" Initialized Quill Viewer"); } else { // Initialize Quill Player without loading a document path. // Note we can't access any of the document state APIs until Player::Load has been // called to initialize the document. initQuillPlayer(nullptr, immPlayerState.renderingTechnique, &appState.Java); } } // Use the Quill Viewer interface to render the scene if ready. if (immPlayer.viewer != nullptr) { // This is the only place the frame index is incremented, right before // calling vrapi_GetPredictedDisplayTime(). appState.FrameIndex++; // Get the HMD pose, predicted for the middle of the time period during which // the new eye images will be displayed. The number of frames predicted ahead // depends on the pipeline depth of the engine and the synthesis rate. // The better the prediction, the less black will be pulled in at the edges. const double predictedDisplayTime = vrapi_GetPredictedDisplayTime( appState.Ovr, appState.FrameIndex ); const ovrTracking2 tracking = vrapi_GetPredictedTracking2( appState.Ovr, predictedDisplayTime ); appState.DisplayTime = predictedDisplayTime; #if MULTI_THREADED // Render the eye images on a separate thread. ovrRenderThread_Submit( &appState.RenderThread, appState.Ovr, RENDER_FRAME, appState.FrameIndex, appState.DisplayTime, appState.SwapInterval, &tracking ); #else // If we are switching to another Quill we need to wait one frame for the CPU/GPU unload. // Once unloaded, load the new Quill path. Wait for http imm download to complete. bool isReadyToLoadNewDoc = true; if (immPlayer.initialized) { isReadyToLoadNewDoc = immPlayer.viewer->GetDocumentLoadState(docID) == ImmPlayer::Player::LoadingState::Unloaded; } if (!isDownloadingDocument && immPlayerState.loadNewDocument && isReadyToLoadNewDoc) { immPlayer.viewer->Deinit(); // Reset the sound engine immPlayer.soundEngineBackend->Deinit(); piSoundEngineBackend::Configuration config; config.mLowLatency = true; // enable android fast-path if (!immPlayer.soundEngineBackend->Init(nullptr, -1, &config)) { ALOGF("Can't init Audio360 soundEngineBackend"); } wchar_t uiLibPath[1024]; swprintf(uiLibPath, 1023, L"%suiLib", getAssetDirectory()); ALOGV("previous document has unloaded... now loading new quill"); const wchar_t * qPath = pistr2ws(getQuillPath()); if (!loadQuillPath(qPath, immPlayerState.renderingTechnique)) { ALOGW("Can't init Quill Viewer %ls", qPath); } free((void *) qPath); immPlayerState.loadNewDocument = false; } ovrLayerProjection2 worldLayer; if (!isDownloadingDocument) { // When resuming an active Quill activity with no document loaded, if we've waited // enough frames without receiving a new document path we may want to show the error quill. bool mayShowErrorQuill = !shutdownRequested && framesSinceStart >= waitForDocFramesMax; if (!mayShowErrorQuill && !immPlayer.viewer->IsDocumentLoaded(docID)) { ++framesSinceStart; } // Show progress as soon as we start loading or downloading a quill. if (mayShowErrorQuill) { if (!immPlayer.viewer->IsDocumentLoading(docID) && !immPlayer.viewer->IsDocumentLoaded(docID) && immPlayerState.quillPath.empty()) { // We resumed the Quill Player activity without a start intent but the previous document // was unloaded. This can happen if the app was started directly from the launcher icon. ALOGV(" showing error quill due to empty quill path"); } else if (immPlayer.viewer->DidDocumentLoadFail(docID)) { ALOGV(" showing error quill because doc load failed"); } } if (immPlayer.viewer->IsDocumentLoaded(docID) && appState.PerformanceParms.CpuLevel != requestedCPULevel) { // After loading completes, update to default rendering levels and allow dynamic clocking to ramp. appState.PerformanceParms.CpuLevel = requestedCPULevel; appState.PerformanceParms.GpuLevel = requestedGPULevel; vrapi_SetClockLevels(appState.Ovr, appState.PerformanceParms.CpuLevel, appState.PerformanceParms.GpuLevel); ALOGV(" loading completed... vrapi_SetClockLevels( %d, %d )", appState.PerformanceParms.CpuLevel, appState.PerformanceParms.GpuLevel); } // Render eye images and setup the primary layer using ovrTracking2. worldLayer = ovrRenderer_RenderFrame(&appState.Renderer, &appState.Java, &tracking, appState.Ovr, appState.FrameIndex); } else { worldLayer = ovrRenderer_RenderDownloadProgress(&appState.Renderer, &appState.Java, &tracking, appState.Ovr, appState.FrameIndex); } // Don't submit the Quill frame unless the document is loaded or we're rendering the // progress component. if (immPlayer.viewer->IsDocumentLoading(docID) || isDownloadingDocument) { ovrLayerLoadingIcon2 loadingLayer = ovrRenderer_RenderTimewarpLoadingIcon( appState.FrameIndex); if (!isDownloadingDocument) { worldLayer = vrapi_DefaultLayerBlackProjection2(); } const ovrLayerHeader2 * layers[] = { &worldLayer.Header, &loadingLayer.Header }; ovrSubmitFrameDescription2 frameDesc = {}; frameDesc.Flags = VRAPI_FRAME_FLAG_FLUSH; frameDesc.SwapInterval = appState.SwapInterval; frameDesc.FrameIndex = appState.FrameIndex; frameDesc.DisplayTime = appState.DisplayTime; frameDesc.LayerCount = 2; frameDesc.Layers = layers; vrapi_SubmitFrame2(appState.Ovr, &frameDesc); } else if (immPlayer.viewer->IsDocumentLoaded(docID)) { const ovrLayerHeader2 * layers[] = { &worldLayer.Header }; ovrSubmitFrameDescription2 frameDesc = {}; frameDesc.Flags = 0; frameDesc.SwapInterval = appState.SwapInterval; frameDesc.FrameIndex = appState.FrameIndex; frameDesc.DisplayTime = appState.DisplayTime; frameDesc.LayerCount = 1; frameDesc.Layers = layers; // Hand over the eye images to the time warp. vrapi_SubmitFrame2(appState.Ovr, &frameDesc); } else { worldLayer = vrapi_DefaultLayerBlackProjection2(); const ovrLayerHeader2 * layers[] = { &worldLayer.Header }; ovrSubmitFrameDescription2 frameDesc = {}; frameDesc.Flags = VRAPI_FRAME_FLAG_FLUSH; frameDesc.SwapInterval = appState.SwapInterval; frameDesc.FrameIndex = appState.FrameIndex; frameDesc.DisplayTime = appState.DisplayTime; frameDesc.LayerCount = 1; frameDesc.Layers = layers; vrapi_SubmitFrame2(appState.Ovr, &frameDesc); } } #endif processOVRMessages(app, &appState.Java); } ALOGV("OVR app destroy requested"); if (immPlayer.viewer != nullptr) { int docID = 0; immPlayer.viewer->CancelLoading(docID); while(immPlayer.viewer->IsDocumentLoading(docID)) { ALOGV("Waiting for loading to stop"); sleep(1); } immPlayer.viewer->UnloadAllSync(); } destroyQuillPlayer(); #if MULTI_THREADED ovrRenderThread_Destroy( &appState.RenderThread ); #else ovrRenderer_Destroy( &appState.Renderer ); #endif ovrEgl_DestroyContext( &appState.Egl ); ALOGV("OVR app requested exit"); vrapi_Shutdown(); (java.Vm)->DetachCurrentThread(); } // endregion
37.773276
232
0.639409
[ "render", "vector" ]
214f3a4d4df36963c26a4d160de3979c713e0ca6
15,608
cpp
C++
admin/snapin/dfsadmin/dfsgui/pubprop.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/dfsadmin/dfsgui/pubprop.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/dfsadmin/dfsgui/pubprop.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Module Name: pubProp.cpp Abstract: --*/ #include "stdafx.h" #include "resource.h" #include "utils.h" #include "pubProp.h" #include "mvEdit.h" #include "dfshelp.h" #include "ldaputils.h" CPublishPropPage::CPublishPropPage() : m_lNotifyHandle(0), m_lNotifyParam(0), CQWizardPageImpl<CPublishPropPage>(false) { m_bPublish = FALSE; } CPublishPropPage::~CPublishPropPage() { // do not call MMCFreeNotifyHandle(m_lNotifyHandle); // // It should only be called once, and is already called // by the main property page } void CPublishPropPage::_Load() { HRESULT hr = S_OK; CComBSTR bstrUNCPath; do { if (!m_piDfsRoot) { hr = E_INVALIDARG; break; } DFS_TYPE lDfsType = DFS_TYPE_UNASSIGNED; hr = m_piDfsRoot->get_DfsType((long *)&lDfsType); BREAK_IF_FAILED(hr); if (lDfsType != DFS_TYPE_FTDFS) { CComBSTR bstrServerName, bstrShareName; hr = m_piDfsRoot->GetOneDfsHost(&bstrServerName, &bstrShareName); BREAK_IF_FAILED(hr); if (lstrlen(bstrShareName) > MAX_RDN_KEY_SIZE) { LoadStringFromResource(IDS_PUBPAGE_ERRMSG_64, &m_bstrError); return; } bstrUNCPath = _T("\\\\"); BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += bstrServerName; BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += _T("\\"); BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += bstrShareName; BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); hr = ReadSharePublishInfoOnSARoot( bstrServerName, bstrShareName, &m_bPublish, &m_bstrUNCPath, &m_bstrDescription, &m_bstrKeywords, &m_bstrManagedBy ); BREAK_IF_FAILED(hr); } else { CComBSTR bstrDomainName; hr = m_piDfsRoot->get_DomainName(&bstrDomainName); BREAK_IF_FAILED(hr); CComBSTR bstrDfsName; hr = m_piDfsRoot->get_DfsName(&bstrDfsName); BREAK_IF_FAILED(hr); bstrUNCPath = _T("\\\\"); BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += bstrDomainName; BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += _T("\\"); BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); bstrUNCPath += bstrDfsName; BREAK_OUTOFMEMORY_IF_NULL((BSTR)bstrUNCPath, &hr); hr = ReadSharePublishInfoOnFTRoot( bstrDomainName, bstrDfsName, &m_bPublish, &m_bstrUNCPath, &m_bstrDescription, &m_bstrKeywords, &m_bstrManagedBy ); BREAK_IF_FAILED(hr); } } while (0); if (FAILED(hr)) { _Reset(); GetMessage(&m_bstrError, hr, IDS_PUBPAGE_ERRMSG); } if (!m_bstrUNCPath || !*m_bstrUNCPath) m_bstrUNCPath = bstrUNCPath; } HRESULT CPublishPropPage::_Save( IN BOOL i_bPublish, IN BSTR i_bstrDescription, IN BSTR i_bstrKeywords, IN BSTR i_bstrManagedBy ) { RETURN_INVALIDARG_IF_NULL((IDfsRoot *)m_piDfsRoot); HRESULT hr = S_OK; do { if (m_bPublish == i_bPublish && PROPSTRNOCHNG((BSTR)m_bstrDescription, i_bstrDescription) && PROPSTRNOCHNG((BSTR)m_bstrKeywords, i_bstrKeywords) && PROPSTRNOCHNG((BSTR)m_bstrManagedBy, i_bstrManagedBy) ) break; // no change DFS_TYPE lDfsType = DFS_TYPE_UNASSIGNED; hr = m_piDfsRoot->get_DfsType((long *)&lDfsType); BREAK_IF_FAILED(hr); if (lDfsType != DFS_TYPE_FTDFS) { CComBSTR bstrServerName, bstrShareName; hr = m_piDfsRoot->GetOneDfsHost(&bstrServerName, &bstrShareName); BREAK_IF_FAILED(hr); hr = ModifySharePublishInfoOnSARoot( bstrServerName, bstrShareName, i_bPublish, m_bstrUNCPath, i_bstrDescription, i_bstrKeywords, i_bstrManagedBy ); if (S_OK == hr) { m_bPublish = i_bPublish; m_bstrDescription = i_bstrDescription; m_bstrKeywords = i_bstrKeywords; m_bstrManagedBy = i_bstrManagedBy; } else if (S_FALSE == hr) hr = S_OK; // ignore non-existing object BREAK_IF_FAILED(hr); } else { CComBSTR bstrDomainName; hr = m_piDfsRoot->get_DomainName(&bstrDomainName); BREAK_IF_FAILED(hr); CComBSTR bstrDfsName; hr = m_piDfsRoot->get_DfsName(&bstrDfsName); BREAK_IF_FAILED(hr); hr = ModifySharePublishInfoOnFTRoot( bstrDomainName, bstrDfsName, i_bPublish, m_bstrUNCPath, i_bstrDescription, i_bstrKeywords, i_bstrManagedBy ); if (S_OK == hr) { m_bPublish = i_bPublish; m_bstrDescription = i_bstrDescription; m_bstrKeywords = i_bstrKeywords; m_bstrManagedBy = i_bstrManagedBy; } BREAK_IF_FAILED(hr); } } while (0); return hr; } LRESULT CPublishPropPage::OnInitDialog( IN UINT i_uMsg, IN WPARAM i_wParam, LPARAM i_lParam, IN OUT BOOL& io_bHandled ) { CWaitCursor wait; _Load(); CheckDlgButton(IDC_PUBPROP_PUBLISH, (m_bPublish ? BST_CHECKED : BST_UNCHECKED)); ::EnableWindow(GetDlgItem(IDC_PUBPROP_UNCPATH_LABEL), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_UNCPATH), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION_LABEL), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_LABEL), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_EDIT), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY_LABEL), m_bPublish); ::EnableWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY), m_bPublish); SetDlgItemText(IDC_PUBPROP_ERROR, ((BSTR)m_bstrError) ? m_bstrError : _T("")); SetDlgItemText(IDC_PUBPROP_UNCPATH, ((BSTR)m_bstrUNCPath) ? m_bstrUNCPath : _T("")); SetDlgItemText(IDC_PUBPROP_DESCRIPTION, ((BSTR)m_bstrDescription) ? m_bstrDescription : _T("")); SetDlgItemText(IDC_PUBPROP_KEYWORDS, ((BSTR)m_bstrKeywords) ? m_bstrKeywords : _T("")); SetDlgItemText(IDC_PUBPROP_MANAGEDBY, ((BSTR)m_bstrManagedBy) ? m_bstrManagedBy : _T("")); if (!m_bstrError) { ::SendMessage(GetDlgItem(IDC_PUBPROP_DESCRIPTION), EM_LIMITTEXT, 1024, 0); // AD schema defines its upper to be 1024 MyShowWindow(GetDlgItem(IDC_PUBPROP_ERROR), FALSE); } else { MyShowWindow(GetDlgItem(IDC_PUBPROP_PUBLISH), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_UNCPATH), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_UNCPATH_LABEL), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION_LABEL), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_LABEL), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_EDIT), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY), FALSE); MyShowWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY_LABEL), FALSE); } return TRUE; // To let the dialg set the control } /*++ This function is called when a user clicks the ? in the top right of a property sheet and then clciks a control, or when they hit F1 in a control. --*/ LRESULT CPublishPropPage::OnCtxHelp( IN UINT i_uMsg, IN WPARAM i_wParam, IN LPARAM i_lParam, IN OUT BOOL& io_bHandled ) { LPHELPINFO lphi = (LPHELPINFO) i_lParam; if (!lphi || lphi->iContextType != HELPINFO_WINDOW || lphi->iCtrlId < 0) return FALSE; ::WinHelp((HWND)(lphi->hItemHandle), DFS_CTX_HELP_FILE, HELP_WM_HELP, (DWORD_PTR)(PVOID)g_aHelpIDs_IDD_PUBLISH_PROP); return TRUE; } /*++ This function handles "What's This" help when a user right clicks the control --*/ LRESULT CPublishPropPage::OnCtxMenuHelp( IN UINT i_uMsg, IN WPARAM i_wParam, IN LPARAM i_lParam, IN OUT BOOL& io_bHandled ) { ::WinHelp((HWND)i_wParam, DFS_CTX_HELP_FILE, HELP_CONTEXTMENU, (DWORD_PTR)(PVOID)g_aHelpIDs_IDD_PUBLISH_PROP); return TRUE; } void CPublishPropPage::_Reset() { m_bPublish = FALSE; m_bstrUNCPath.Empty(); m_bstrDescription.Empty(); m_bstrKeywords.Empty(); m_bstrManagedBy.Empty(); } HRESULT CPublishPropPage::Initialize( IN IDfsRoot* i_piDfsRoot ) { RETURN_INVALIDARG_IF_NULL(i_piDfsRoot); if ((IDfsRoot *)m_piDfsRoot) m_piDfsRoot.Release(); m_piDfsRoot = i_piDfsRoot; _Reset(); return S_OK; } LRESULT CPublishPropPage::OnApply() { CWaitCursor wait; HRESULT hr = S_OK; DWORD dwTextLength = 0; int idControl = 0; int idString = 0; BOOL bValidInput = FALSE; BOOL bPublish = IsDlgButtonChecked(IDC_PUBPROP_PUBLISH); CComBSTR bstrDescription; CComBSTR bstrKeywords; CComBSTR bstrManagedBy; do { idControl = IDC_PUBPROP_DESCRIPTION; hr = GetInputText(GetDlgItem(idControl), &bstrDescription, &dwTextLength); BREAK_IF_FAILED(hr); idControl = IDC_PUBPROP_KEYWORDS; hr = GetInputText(GetDlgItem(idControl), &bstrKeywords, &dwTextLength); BREAK_IF_FAILED(hr); idControl = IDC_PUBPROP_MANAGEDBY; hr = GetInputText(GetDlgItem(idControl), &bstrManagedBy, &dwTextLength); BREAK_IF_FAILED(hr); bValidInput = TRUE; } while (0); if (FAILED(hr)) { SetActivePropertyPage(GetParent(), m_hWnd); DisplayMessageBoxForHR(hr); ::SetFocus(GetDlgItem(idControl)); return FALSE; } else if (bValidInput) { hr = _Save(bPublish, bstrDescription, bstrKeywords, bstrManagedBy); if (FAILED(hr)) { SetActivePropertyPage(GetParent(), m_hWnd); if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr) DisplayMessageBox(::GetActiveWindow(), MB_OK, 0, IDS_FAILED_TO_PUBLISH_DFSROOT_BADUSER); else DisplayMessageBox(::GetActiveWindow(), MB_OK, hr, IDS_FAILED_TO_PUBLISH_DFSROOT, m_bstrUNCPath); return FALSE; } else if (S_FALSE == hr) // no dfs root object in the DS { SetActivePropertyPage(GetParent(), m_hWnd); DisplayMessageBox(::GetActiveWindow(), MB_OK, 0, IDS_FAILED_TO_PUBLISH_NOROOTOBJ); return FALSE; } ::SendMessage(GetParent(), PSM_UNCHANGED, (WPARAM)m_hWnd, 0); if (m_lNotifyHandle && m_lNotifyParam) MMCPropertyChangeNotify(m_lNotifyHandle, m_lNotifyParam); return TRUE; } else { SetActivePropertyPage(GetParent(), m_hWnd); if (idString) DisplayMessageBoxWithOK(idString); ::SetFocus(GetDlgItem(idControl)); return FALSE; } } LRESULT CPublishPropPage::OnPublish( IN WORD i_wNotifyCode, IN WORD i_wID, IN HWND i_hWndCtl, IN OUT BOOL& io_bHandled ) { if (BN_CLICKED == i_wNotifyCode) { ::SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0); BOOL bEnable = (BST_CHECKED == IsDlgButtonChecked(i_wID)); ::EnableWindow(GetDlgItem(IDC_PUBPROP_UNCPATH_LABEL), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_UNCPATH), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION_LABEL), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_DESCRIPTION), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_LABEL), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_KEYWORDS_EDIT), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY_LABEL), bEnable); ::EnableWindow(GetDlgItem(IDC_PUBPROP_MANAGEDBY), bEnable); } return TRUE; } LRESULT CPublishPropPage::OnDescription( IN WORD i_wNotifyCode, IN WORD i_wID, IN HWND i_hWndCtl, IN OUT BOOL& io_bHandled ) { if (EN_CHANGE == i_wNotifyCode) { ::SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0); } return TRUE; } LRESULT CPublishPropPage::OnEditKeywords( IN WORD i_wNotifyCode, IN WORD i_wID, IN HWND i_hWndCtl, IN OUT BOOL& io_bHandled ) { DWORD dwTextLength = 0; CComBSTR bstrKeywords; GetInputText(GetDlgItem(IDC_PUBPROP_KEYWORDS), &bstrKeywords, &dwTextLength); if (S_OK == InvokeMultiValuedStringEditDlg( &bstrKeywords, _T(";"), IDS_MVSTRINGEDIT_TITLE_KEYWORDS, IDS_MVSTRINGEDIT_TEXT_KEYWORDS, KEYTWORDS_UPPER_RANGER)) { SetDlgItemText(IDC_PUBPROP_KEYWORDS, bstrKeywords); ::SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0); } return TRUE; } LRESULT CPublishPropPage::OnManagedBy( IN WORD i_wNotifyCode, IN WORD i_wID, IN HWND i_hWndCtl, IN OUT BOOL& io_bHandled ) { if (EN_CHANGE == i_wNotifyCode) { ::SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0); } return TRUE; } LRESULT CPublishPropPage::OnParentClosing( IN UINT i_uMsg, IN WPARAM i_wParam, LPARAM i_lParam, IN OUT BOOL& io_bHandled ) { ::SendMessage(GetParent(), PSM_PRESSBUTTON, PSBTN_CANCEL, 0); return TRUE; } HRESULT CPublishPropPage::SetNotifyData( IN LONG_PTR i_lNotifyHandle, IN LPARAM i_lParam ) { m_lNotifyHandle = i_lNotifyHandle; m_lNotifyParam = i_lParam; return S_OK; }
31.153693
125
0.578165
[ "object" ]
2153ba9635f783f75e719ee3d922ef0a06168f86
3,584
cpp
C++
First round 2020/arcmatch/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
First round 2020/arcmatch/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
First round 2020/arcmatch/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <queue> #include <bits/stdc++.h> using namespace std; #define int long long ifstream fin("/tmp/arcmatch-sub3-attempt0.txt"); #define cin fin void colorGraph(vector<vector<int>> &graph, vector<int> &colors, int start) { queue<int> queue; queue.push(start); colors[start] = start; while (queue.size() != 0) { int cur = queue.front(); queue.pop(); for (int i = 0; i < graph[cur].size(); ++i) { if (colors[graph[cur][i]] == -1) { colors[graph[cur][i]] = !colors[cur]; queue.push(graph[cur][i]); } else if (colors[graph[cur][i]] == colors[cur]) { colors = {}; return; } } } } vector<vector<int>> arcmatch(vector<int> &input) { vector<vector<int>> E(input.size() / 2); vector<int> endPositions(input.size() / 2, -1); for (int j = 0; j < input.size(); ++j) { endPositions[input[j]] = j; } priority_queue<int> firstEnds; stack<int> starts; starts.push(-1); firstEnds.push(-1); firstEnds.push(-1); for (int i = 0; i < input.size(); ++i) { int cur = input[i]; while (starts.top() != -1 && endPositions[input[starts.top()]] >= i) { starts.pop(); } if (i == endPositions[cur]) { firstEnds.pop(); if (starts.top() != -1) { E[input[starts.top()]].push_back(cur); E[cur].push_back(input[starts.top()]); } } else { starts.push(i); int tmp = input.size() - firstEnds.top(); firstEnds.pop(); int tmp2 = input.size() - firstEnds.top(); int element1 = input[tmp]; int element2 = input[tmp]; if (tmp != input.size() + 1) { if (endPositions[cur] > tmp) { E[input[tmp]].push_back(cur); E[cur].push_back(input[tmp]); } } if (tmp2 != input.size() + 1) { if (endPositions[cur] > tmp2) { E[input[tmp2]].push_back(cur); E[cur].push_back(input[tmp2]); } } firstEnds.push(input.size() - tmp); firstEnds.push(input.size() - endPositions[cur]); } } return E; } signed main() { /* // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0);*/ int testCases; cin >> testCases; /* ofstream out("output.txt"); streambuf *coutbuf = cout.rdbuf(); cout.rdbuf(out.rdbuf());*/ for (int testCase = 0; testCase < testCases; ++testCase) { int n; cin >> n; vector<int> input(2 * n); vector<int> endPositions(n); for (int j = 0; j < input.size(); ++j) { cin >> input[j]; endPositions[input[j]] = j; } vector<vector<int>> E = arcmatch(input); vector<int> colors(n, -1); for (int i = 0; i < E.size(); ++i) { if (colors[i] == -1) { colorGraph(E, colors, i); if (colors.size() == 0) { break; } } } if (colors.size()) { cout << "Case #" << testCase << ": Possible\n"; } else { cout << "Case #" << testCase << ": Impossible\n"; } } }
25.971014
78
0.467913
[ "vector" ]
215b7099b759669fd202d4b0d01525124fe02c9b
34,977
cc
C++
gearsBridge/lshw/src/core/pci.cc
SSEHUB/spassMeter
f5071105fec6f5afbbd7426b8149b7973c1a5e55
[ "Apache-2.0" ]
1
2015-08-06T08:48:12.000Z
2015-08-06T08:48:12.000Z
gearsBridge/lshw/src/core/pci.cc
SSEHUB/spassMeter
f5071105fec6f5afbbd7426b8149b7973c1a5e55
[ "Apache-2.0" ]
1
2018-05-08T12:17:23.000Z
2018-05-09T12:03:13.000Z
gearsBridge/lshw/src/core/pci.cc
SSEHUB/spassMeter
f5071105fec6f5afbbd7426b8149b7973c1a5e55
[ "Apache-2.0" ]
3
2015-09-26T22:19:40.000Z
2018-08-27T05:36:34.000Z
#include "version.h" #include "config.h" #include "pci.h" #include "osutils.h" #include "options.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdint.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> __ID("@(#) $Id: pci.cc 2124 2009-10-06 09:11:49Z lyonel $"); #define PROC_BUS_PCI "/proc/bus/pci" #define SYS_BUS_PCI "/sys/bus/pci" #define PCIID_PATH "/usr/share/lshw/pci.ids:/usr/local/share/pci.ids:/usr/share/pci.ids:/etc/pci.ids:/usr/share/hwdata/pci.ids:/usr/share/misc/pci.ids" #define PCI_CLASS_REVISION 0x08 /* High 24 bits are class, low 8 revision */ #define PCI_VENDOR_ID 0x00 /* 16 bits */ #define PCI_DEVICE_ID 0x02 /* 16 bits */ #define PCI_COMMAND 0x04 /* 16 bits */ #define PCI_REVISION_ID 0x08 /* Revision ID */ #define PCI_CLASS_PROG 0x09 /* Reg. Level Programming Interface */ #define PCI_CLASS_DEVICE 0x0a /* Device class */ #define PCI_HEADER_TYPE 0x0e /* 8 bits */ #define PCI_HEADER_TYPE_NORMAL 0 #define PCI_HEADER_TYPE_BRIDGE 1 #define PCI_HEADER_TYPE_CARDBUS 2 #define PCI_PRIMARY_BUS 0x18 /* Primary bus number */ #define PCI_SECONDARY_BUS 0x19 /* Secondary bus number */ #define PCI_STATUS 0x06 /* 16 bits */ #define PCI_LATENCY_TIMER 0x0d /* 8 bits */ #define PCI_SEC_LATENCY_TIMER 0x1b /* Latency timer for secondary interface */ #define PCI_CB_LATENCY_TIMER 0x1b /* CardBus latency timer */ #define PCI_STATUS_66MHZ 0x20 /* Support 66 Mhz PCI 2.1 bus */ #define PCI_STATUS_CAP_LIST 0x10 /* Support Capability List */ #define PCI_COMMAND_IO 0x1 /* Enable response in I/O space */ #define PCI_COMMAND_MEMORY 0x2 /* Enable response in Memory space */ #define PCI_COMMAND_MASTER 0x4 /* Enable bus mastering */ #define PCI_COMMAND_SPECIAL 0x8 /* Enable response to special cycles */ #define PCI_COMMAND_INVALIDATE 0x10 /* Use memory write and invalidate */ #define PCI_COMMAND_VGA_PALETTE 0x20 /* Enable palette snooping */ #define PCI_COMMAND_PARITY 0x40 /* Enable parity checking */ #define PCI_COMMAND_WAIT 0x80 /* Enable address/data stepping */ #define PCI_COMMAND_SERR 0x100 /* Enable SERR */ #define PCI_COMMAND_FAST_BACK 0x200 /* Enable back-to-back writes */ #define PCI_MIN_GNT 0x3e /* 8 bits */ #define PCI_MAX_LAT 0x3f /* 8 bits */ #define PCI_CAPABILITY_LIST 0x34 /* Offset of first capability list entry */ #define PCI_CAP_LIST_ID 0 /* Capability ID */ #define PCI_CAP_ID_PM 0x01 /* Power Management */ #define PCI_CAP_ID_AGP 0x02 /* Accelerated Graphics Port */ #define PCI_CAP_ID_VPD 0x03 /* Vital Product Data */ #define PCI_CAP_ID_SLOTID 0x04 /* Slot Identification */ #define PCI_CAP_ID_MSI 0x05 /* Message Signalled Interrupts */ #define PCI_CAP_ID_CHSWP 0x06 /* CompactPCI HotSwap */ #define PCI_CAP_ID_PCIX 0x07 /* PCI-X */ #define PCI_CAP_ID_HT 0x08 /* HyperTransport */ #define PCI_CAP_ID_VNDR 0x09 /* Vendor specific */ #define PCI_CAP_ID_DBG 0x0A /* Debug port */ #define PCI_CAP_ID_CCRC 0x0B /* CompactPCI Central Resource Control */ #define PCI_CAP_ID_AGP3 0x0E /* AGP 8x */ #define PCI_CAP_ID_EXP 0x10 /* PCI Express */ #define PCI_CAP_ID_MSIX 0x11 /* MSI-X */ #define PCI_CAP_LIST_NEXT 1 /* Next capability in the list */ #define PCI_CAP_FLAGS 2 /* Capability defined flags (16 bits) */ #define PCI_CAP_SIZEOF 4 #define PCI_FIND_CAP_TTL 48 #define PCI_SID_ESR 2 /* Expansion Slot Register */ #define PCI_SID_ESR_NSLOTS 0x1f /* Number of expansion slots available */ /* * The PCI interface treats multi-function devices as independent * devices. The slot/function address of each device is encoded * in a single byte as follows: * * 7:3 = slot * 2:0 = function */ #define PCI_DEVFN(slot,func) ((((slot) & 0x1f) << 3) | ((func) & 0x07)) #define PCI_SLOT(devfn) (((devfn) >> 3) & 0x1f) #define PCI_FUNC(devfn) ((devfn) & 0x07) /* Device classes and subclasses */ #define PCI_CLASS_NOT_DEFINED 0x0000 #define PCI_CLASS_NOT_DEFINED_VGA 0x0001 #define PCI_BASE_CLASS_STORAGE 0x01 #define PCI_CLASS_STORAGE_SCSI 0x0100 #define PCI_CLASS_STORAGE_IDE 0x0101 #define PCI_CLASS_STORAGE_FLOPPY 0x0102 #define PCI_CLASS_STORAGE_IPI 0x0103 #define PCI_CLASS_STORAGE_RAID 0x0104 #define PCI_CLASS_STORAGE_OTHER 0x0180 #define PCI_BASE_CLASS_NETWORK 0x02 #define PCI_CLASS_NETWORK_ETHERNET 0x0200 #define PCI_CLASS_NETWORK_TOKEN_RING 0x0201 #define PCI_CLASS_NETWORK_FDDI 0x0202 #define PCI_CLASS_NETWORK_ATM 0x0203 #define PCI_CLASS_NETWORK_OTHER 0x0280 #define PCI_BASE_CLASS_DISPLAY 0x03 #define PCI_CLASS_DISPLAY_VGA 0x0300 #define PCI_CLASS_DISPLAY_XGA 0x0301 #define PCI_CLASS_DISPLAY_OTHER 0x0380 #define PCI_BASE_CLASS_MULTIMEDIA 0x04 #define PCI_CLASS_MULTIMEDIA_VIDEO 0x0400 #define PCI_CLASS_MULTIMEDIA_AUDIO 0x0401 #define PCI_CLASS_MULTIMEDIA_OTHER 0x0480 #define PCI_BASE_CLASS_MEMORY 0x05 #define PCI_CLASS_MEMORY_RAM 0x0500 #define PCI_CLASS_MEMORY_FLASH 0x0501 #define PCI_CLASS_MEMORY_OTHER 0x0580 #define PCI_BASE_CLASS_BRIDGE 0x06 #define PCI_CLASS_BRIDGE_HOST 0x0600 #define PCI_CLASS_BRIDGE_ISA 0x0601 #define PCI_CLASS_BRIDGE_EISA 0x0602 #define PCI_CLASS_BRIDGE_MC 0x0603 #define PCI_CLASS_BRIDGE_PCI 0x0604 #define PCI_CLASS_BRIDGE_PCMCIA 0x0605 #define PCI_CLASS_BRIDGE_NUBUS 0x0606 #define PCI_CLASS_BRIDGE_CARDBUS 0x0607 #define PCI_CLASS_BRIDGE_OTHER 0x0680 #define PCI_BASE_CLASS_COMMUNICATION 0x07 #define PCI_CLASS_COMMUNICATION_SERIAL 0x0700 #define PCI_CLASS_COMMUNICATION_PARALLEL 0x0701 #define PCI_CLASS_COMMUNICATION_MODEM 0x0703 #define PCI_CLASS_COMMUNICATION_OTHER 0x0780 #define PCI_BASE_CLASS_SYSTEM 0x08 #define PCI_CLASS_SYSTEM_PIC 0x0800 #define PCI_CLASS_SYSTEM_DMA 0x0801 #define PCI_CLASS_SYSTEM_TIMER 0x0802 #define PCI_CLASS_SYSTEM_RTC 0x0803 #define PCI_CLASS_SYSTEM_OTHER 0x0880 #define PCI_BASE_CLASS_INPUT 0x09 #define PCI_CLASS_INPUT_KEYBOARD 0x0900 #define PCI_CLASS_INPUT_PEN 0x0901 #define PCI_CLASS_INPUT_MOUSE 0x0902 #define PCI_CLASS_INPUT_OTHER 0x0980 #define PCI_BASE_CLASS_DOCKING 0x0a #define PCI_CLASS_DOCKING_GENERIC 0x0a00 #define PCI_CLASS_DOCKING_OTHER 0x0a01 #define PCI_BASE_CLASS_PROCESSOR 0x0b #define PCI_CLASS_PROCESSOR_386 0x0b00 #define PCI_CLASS_PROCESSOR_486 0x0b01 #define PCI_CLASS_PROCESSOR_PENTIUM 0x0b02 #define PCI_CLASS_PROCESSOR_ALPHA 0x0b10 #define PCI_CLASS_PROCESSOR_POWERPC 0x0b20 #define PCI_CLASS_PROCESSOR_CO 0x0b40 #define PCI_BASE_CLASS_SERIAL 0x0c #define PCI_CLASS_SERIAL_FIREWIRE 0x0c00 #define PCI_CLASS_SERIAL_ACCESS 0x0c01 #define PCI_CLASS_SERIAL_SSA 0x0c02 #define PCI_CLASS_SERIAL_USB 0x0c03 #define PCI_CLASS_SERIAL_FIBER 0x0c04 #define PCI_CLASS_OTHERS 0xff #define PCI_ADDR_MEM_MASK (~(pciaddr_t) 0xf) #define PCI_BASE_ADDRESS_0 0x10 /* 32 bits */ #define PCI_BASE_ADDRESS_SPACE 0x01 /* 0 = memory, 1 = I/O */ #define PCI_BASE_ADDRESS_SPACE_IO 0x01 #define PCI_BASE_ADDRESS_SPACE_MEMORY 0x00 #define PCI_BASE_ADDRESS_MEM_TYPE_MASK 0x06 #define PCI_BASE_ADDRESS_MEM_TYPE_32 0x00 /* 32 bit address */ #define PCI_BASE_ADDRESS_MEM_TYPE_1M 0x02 /* Below 1M [obsolete] */ #define PCI_BASE_ADDRESS_MEM_TYPE_64 0x04 /* 64 bit address */ #define PCI_BASE_ADDRESS_MEM_PREFETCH 0x08 /* prefetchable? */ #define PCI_BASE_ADDRESS_MEM_MASK (~0x0fUL) #define PCI_BASE_ADDRESS_IO_MASK (~0x03UL) #define PCI_SUBSYSTEM_VENDOR_ID 0x2c #define PCI_SUBSYSTEM_ID 0x2e #define PCI_CB_SUBSYSTEM_VENDOR_ID 0x40 #define PCI_CB_SUBSYSTEM_ID 0x42 bool pcidb_loaded = false; typedef unsigned long long pciaddr_t; typedef enum { pcidevice, pcisubdevice, pcisubsystem, pciclass, pcisubclass, pcivendor, pcisubvendor, pciprogif } catalog; struct pci_dev { u_int16_t domain; /* PCI domain (host bridge) */ u_int16_t bus; /* Higher byte can select host bridges */ u_int8_t dev, func; /* Device and function */ u_int16_t vendor_id, device_id; /* Identity of the device */ unsigned int irq; /* IRQ number */ pciaddr_t base_addr[6]; /* Base addresses */ pciaddr_t size[6]; /* Region sizes */ pciaddr_t rom_base_addr; /* Expansion ROM base address */ pciaddr_t rom_size; /* Expansion ROM size */ u_int8_t config[256]; /* non-root users can only use first 64 bytes */ }; struct pci_entry { long ids[4]; string description; pci_entry(const string & description, long u1 = -1, long u2 = -1, long u3 = -1, long u4 = -1); unsigned int matches(long u1 = -1, long u2 = -1, long u3 = -1, long u4 = -1); }; static vector < pci_entry > pci_devices; static vector < pci_entry > pci_classes; pci_entry::pci_entry(const string & d, long u1, long u2, long u3, long u4) { description = d; ids[0] = u1; ids[1] = u2; ids[2] = u3; ids[3] = u4; } unsigned int pci_entry::matches(long u1, long u2, long u3, long u4) { unsigned int result = 0; if (ids[0] == u1) { result++; if (ids[1] == u2) { result++; if (ids[2] == u3) { result++; if (ids[3] == u4) result++; } } } return result; } static bool find_best_match(vector < pci_entry > &list, pci_entry & result, long u1 = -1, long u2 = -1, long u3 = -1, long u4 = -1) { int lastmatch = -1; unsigned int lastscore = 0; for (unsigned int i = 0; i < list.size(); i++) { unsigned int currentscore = list[i].matches(u1, u2, u3, u4); if (currentscore > lastscore) { lastscore = currentscore; lastmatch = i; } } if (lastmatch >= 0) { result = list[lastmatch]; return true; } return false; } static const char *get_class_name(unsigned int c) { switch (c) { case PCI_CLASS_NOT_DEFINED_VGA: return "display"; case PCI_CLASS_STORAGE_SCSI: return "scsi"; case PCI_CLASS_STORAGE_IDE: return "ide"; case PCI_CLASS_BRIDGE_HOST: return "host"; case PCI_CLASS_BRIDGE_ISA: return "isa"; case PCI_CLASS_BRIDGE_EISA: return "eisa"; case PCI_CLASS_BRIDGE_MC: return "mc"; case PCI_CLASS_BRIDGE_PCI: return "pci"; case PCI_CLASS_BRIDGE_PCMCIA: return "pcmcia"; case PCI_CLASS_BRIDGE_NUBUS: return "nubus"; case PCI_CLASS_BRIDGE_CARDBUS: return "pcmcia"; case PCI_CLASS_SERIAL_FIREWIRE: return "firewire"; case PCI_CLASS_SERIAL_USB: return "usb"; case PCI_CLASS_SERIAL_FIBER: return "fiber"; } switch (c >> 8) { case PCI_BASE_CLASS_STORAGE: return "storage"; case PCI_BASE_CLASS_NETWORK: return "network"; case PCI_BASE_CLASS_DISPLAY: return "display"; case PCI_BASE_CLASS_MULTIMEDIA: return "multimedia"; case PCI_BASE_CLASS_MEMORY: return "memory"; case PCI_BASE_CLASS_BRIDGE: return "bridge"; case PCI_BASE_CLASS_COMMUNICATION: return "communication"; case PCI_BASE_CLASS_SYSTEM: return "generic"; case PCI_BASE_CLASS_INPUT: return "input"; case PCI_BASE_CLASS_DOCKING: return "docking"; case PCI_BASE_CLASS_PROCESSOR: return "processor"; case PCI_BASE_CLASS_SERIAL: return "serial"; } return "generic"; } static bool parse_pcidb(vector < string > &list) { long u[4]; string line = ""; catalog current_catalog = pcivendor; unsigned int level = 0; memset(u, 0, sizeof(u)); for (unsigned int i = 0; i < list.size(); i++) { line = hw::strip(list[i]); // ignore empty or commented-out lines if (line.length() == 0 || line[0] == '#') continue; level = 0; while ((level < list[i].length()) && (list[i][level] == '\t')) level++; switch (level) { case 0: if ((line[0] == 'C') && (line.length() > 1) && (line[1] == ' ')) { current_catalog = pciclass; line = line.substr(2); // get rid of 'C ' if ((line.length() < 3) || (line[2] != ' ')) return false; if (sscanf(line.c_str(), "%lx", &u[0]) != 1) return false; line = line.substr(3); line = hw::strip(line); } else { current_catalog = pcivendor; if ((line.length() < 5) || (line[4] != ' ')) return false; if (sscanf(line.c_str(), "%lx", &u[0]) != 1) return false; line = line.substr(5); line = hw::strip(line); } u[1] = u[2] = u[3] = -1; break; case 1: if ((current_catalog == pciclass) || (current_catalog == pcisubclass) || (current_catalog == pciprogif)) { current_catalog = pcisubclass; if ((line.length() < 3) || (line[2] != ' ')) return false; if (sscanf(line.c_str(), "%lx", &u[1]) != 1) return false; line = line.substr(3); line = hw::strip(line); } else { current_catalog = pcidevice; if ((line.length() < 5) || (line[4] != ' ')) return false; if (sscanf(line.c_str(), "%lx", &u[1]) != 1) return false; line = line.substr(5); line = hw::strip(line); } u[2] = u[3] = -1; break; case 2: if ((current_catalog != pcidevice) && (current_catalog != pcisubvendor) && (current_catalog != pcisubclass) && (current_catalog != pciprogif)) return false; if ((current_catalog == pcisubclass) || (current_catalog == pciprogif)) { current_catalog = pciprogif; if ((line.length() < 3) || (line[2] != ' ')) return false; if (sscanf(line.c_str(), "%lx", &u[2]) != 1) return false; u[3] = -1; line = line.substr(2); line = hw::strip(line); } else { current_catalog = pcisubvendor; if ((line.length() < 10) || (line[4] != ' ') || (line[9] != ' ')) return false; if (sscanf(line.c_str(), "%lx%lx", &u[2], &u[3]) != 2) return false; line = line.substr(9); line = hw::strip(line); } break; default: return false; } //printf("%04x %04x %04x %04x %s\n", u[0], u[1], u[2], u[3], line.c_str()); if ((current_catalog == pciclass) || (current_catalog == pcisubclass) || (current_catalog == pciprogif)) { pci_classes.push_back(pci_entry(line, u[0], u[1], u[2], u[3])); } else { pci_devices.push_back(pci_entry(line, u[0], u[1], u[2], u[3])); } } return true; } static bool load_pcidb() { vector < string > lines; vector < string > filenames; splitlines(PCIID_PATH, filenames, ':'); for (int i = filenames.size() - 1; i >= 0; i--) { lines.clear(); if (loadfile(filenames[i], lines)) parse_pcidb(lines); } if (lines.size() == 0) return false; return true; } static string get_class_description(long c, long pi = -1) { pci_entry result(""); if (find_best_match(pci_classes, result, c >> 8, c & 0xff, pi)) return result.description; else return ""; } static string get_device_description(long u1, long u2 = -1, long u3 = -1, long u4 = -1) { pci_entry result(""); if (find_best_match(pci_devices, result, u1, u2, u3, u4)) return result.description; else return ""; } static u_int32_t get_conf_long(struct pci_dev d, unsigned int pos) { if (pos > sizeof(d.config)) return 0; return d.config[pos] | (d.config[pos + 1] << 8) | (d.config[pos + 2] << 16) | (d.config[pos + 3] << 24); } static u_int16_t get_conf_word(struct pci_dev d, unsigned int pos) { if (pos > sizeof(d.config)) return 0; return d.config[pos] | (d.config[pos + 1] << 8); } static u_int8_t get_conf_byte(struct pci_dev d, unsigned int pos) { if (pos > sizeof(d.config)) return 0; return d.config[pos]; } static string pci_bushandle(u_int8_t bus, u_int16_t domain = 0) { char buffer[20]; if(domain == (u_int16_t)(-1)) snprintf(buffer, sizeof(buffer), "%02x", bus); else snprintf(buffer, sizeof(buffer), "%04x:%02x", domain, bus); return "PCIBUS:" + string(buffer); } static string pci_handle(u_int16_t bus, u_int8_t dev, u_int8_t fct, u_int16_t domain = 0) { char buffer[30]; if(domain == (u_int16_t)(-1)) snprintf(buffer, sizeof(buffer), "PCI:%02x:%02x.%x", bus, dev, fct); else snprintf(buffer, sizeof(buffer), "PCI:%04x:%02x:%02x.%x", domain, bus, dev, fct); return string(buffer); } static bool scan_resources(hwNode & n, struct pci_dev &d) { u_int16_t cmd = get_conf_word(d, PCI_COMMAND); n.setWidth(32); for (int i = 0; i < 6; i++) { u_int32_t flg = get_conf_long(d, PCI_BASE_ADDRESS_0 + 4 * i); u_int32_t pos = d.base_addr[i]; u_int32_t len = d.size[i]; if (flg == 0xffffffff) flg = 0; if (!pos && !flg && !len) continue; if (pos && !flg) /* Reported by the OS, but not by the device */ { //printf("[virtual] "); flg = pos; } if (flg & PCI_BASE_ADDRESS_SPACE_IO) { u_int32_t a = pos & PCI_BASE_ADDRESS_IO_MASK; if ((a != 0) && (cmd & PCI_COMMAND_IO) != 0) n.addResource(hw::resource::ioport(a, a + len - 1)); } else // resource is memory { int t = flg & PCI_BASE_ADDRESS_MEM_TYPE_MASK; u_int64_t a = pos & PCI_ADDR_MEM_MASK; u_int64_t z = 0; if (t == PCI_BASE_ADDRESS_MEM_TYPE_64) { n.setWidth(64); if (i < 5) { i++; z = get_conf_long(d, PCI_BASE_ADDRESS_0 + 4 * i); a += z << 4; } } if (a) n.addResource(hw::resource::iomem(a, a + len - 1)); } } return true; } static bool scan_capabilities(hwNode & n, struct pci_dev &d) { unsigned int where = get_conf_byte(d, PCI_CAPABILITY_LIST) & ~3; string buffer; unsigned int ttl = PCI_FIND_CAP_TTL; while(where && ttl--) { unsigned int id, next, cap; id = get_conf_byte(d, where + PCI_CAP_LIST_ID); next = get_conf_byte(d, where + PCI_CAP_LIST_NEXT) & ~3; cap = get_conf_word(d, where + PCI_CAP_FLAGS); if(!id || id == 0xff) return false; switch(id) { case PCI_CAP_ID_PM: n.addCapability("pm", "Power Management"); break; case PCI_CAP_ID_AGP: n.addCapability("agp", "AGP"); buffer = hw::asString((cap >> 4) & 0x0f) + "." + hw::asString(cap & 0x0f); n.addCapability("agp-"+buffer, "AGP "+buffer); break; case PCI_CAP_ID_VPD: n.addCapability("vpd", "Vital Product Data"); break; case PCI_CAP_ID_SLOTID: n.addCapability("slotid", "Slot Identification"); n.setSlot(hw::asString(cap & PCI_SID_ESR_NSLOTS)+", chassis "+hw::asString(cap>>8)); break; case PCI_CAP_ID_MSI: n.addCapability("msi", "Message Signalled Interrupts"); break; case PCI_CAP_ID_CHSWP: n.addCapability("hotswap", "Hot-swap"); break; case PCI_CAP_ID_PCIX: n.addCapability("pcix", "PCI-X"); break; case PCI_CAP_ID_HT: n.addCapability("ht", "HyperTransport"); break; case PCI_CAP_ID_DBG: n.addCapability("debug", "Debug port"); break; case PCI_CAP_ID_CCRC: n.addCapability("ccrc", "CompactPCI Central Resource Control"); break; case PCI_CAP_ID_AGP3: n.addCapability("agp8x", "AGP 8x"); break; case PCI_CAP_ID_EXP: n.addCapability("pciexpress", _("PCI Express")); break; case PCI_CAP_ID_MSIX: n.addCapability("msix", "MSI-X"); break; } where = next; } return true; } static void addHints(hwNode & n, long _vendor, long _device, long _subvendor, long _subdevice, long _class) { n.addHint("pci.vendor", _vendor); n.addHint("pci.device", _device); if(_subvendor && (_subvendor != 0xffff)) { n.addHint("pci.subvendor", _subvendor); n.addHint("pci.subdevice", _subdevice); } n.addHint("pci.class", _class); } static hwNode *scan_pci_dev(struct pci_dev &d, hwNode & n) { hwNode *result = NULL; hwNode *core = n.getChild("core"); if (!core) { n.addChild(hwNode("core", hw::bus)); core = n.getChild("core"); } if(!pcidb_loaded) pcidb_loaded = load_pcidb(); d.vendor_id = get_conf_word(d, PCI_VENDOR_ID); d.device_id = get_conf_word(d, PCI_DEVICE_ID); u_int16_t dclass = get_conf_word(d, PCI_CLASS_DEVICE); u_int16_t cmd = get_conf_word(d, PCI_COMMAND); u_int16_t status = get_conf_word(d, PCI_STATUS); u_int8_t latency = get_conf_byte(d, PCI_LATENCY_TIMER); u_int8_t min_gnt = get_conf_byte(d, PCI_MIN_GNT); u_int8_t max_lat = get_conf_byte(d, PCI_MAX_LAT); u_int8_t progif = get_conf_byte(d, PCI_CLASS_PROG); u_int8_t rev = get_conf_byte(d, PCI_REVISION_ID); u_int8_t htype = get_conf_byte(d, PCI_HEADER_TYPE) & 0x7f; u_int16_t subsys_v = 0, subsys_d = 0; char revision[10]; snprintf(revision, sizeof(revision), "%02x", rev); string moredescription = get_class_description(dclass, progif); switch (htype) { case PCI_HEADER_TYPE_NORMAL: subsys_v = get_conf_word(d, PCI_SUBSYSTEM_VENDOR_ID); subsys_d = get_conf_word(d, PCI_SUBSYSTEM_ID); break; case PCI_HEADER_TYPE_BRIDGE: subsys_v = subsys_d = 0; latency = get_conf_byte(d, PCI_SEC_LATENCY_TIMER); break; case PCI_HEADER_TYPE_CARDBUS: subsys_v = get_conf_word(d, PCI_CB_SUBSYSTEM_VENDOR_ID); subsys_d = get_conf_word(d, PCI_CB_SUBSYSTEM_ID); latency = get_conf_byte(d, PCI_CB_LATENCY_TIMER); break; } if (dclass == PCI_CLASS_BRIDGE_HOST) { hwNode host("pci", hw::bridge); host.setDescription(get_class_description(dclass, progif)); host.setVendor(get_device_description(d.vendor_id)+(enabled("output:numeric")?" ["+tohex(d.vendor_id)+"]":"")); host.setProduct(get_device_description(d.vendor_id, d.device_id)+(enabled("output:numeric")?" ["+tohex(d.vendor_id)+":"+tohex(d.device_id)+"]":"")); host.setHandle(pci_bushandle(d.bus, d.domain)); host.setVersion(revision); addHints(host, d.vendor_id, d.device_id, subsys_v, subsys_d, dclass); host.claim(); if(latency) host.setConfig("latency", latency); if (d.size[0] > 0) host.setPhysId(0x100 + d.domain); if (moredescription != "" && moredescription != host.getDescription()) { host.addCapability(moredescription); host.setDescription(host.getDescription() + " (" + moredescription + ")"); } if (status & PCI_STATUS_66MHZ) host.setClock(66000000UL); // 66MHz else host.setClock(33000000UL); // 33MHz scan_resources(host, d); if (core) result = core->addChild(host); else result = n.addChild(host); } else { hw::hwClass deviceclass = hw::generic; string devicename = "generic"; string deviceicon = ""; switch (dclass >> 8) { case PCI_BASE_CLASS_STORAGE: deviceclass = hw::storage; deviceicon = "disc"; if(dclass == PCI_CLASS_STORAGE_SCSI) deviceicon = "scsi"; if(dclass == PCI_CLASS_STORAGE_RAID) deviceicon = "raid"; break; case PCI_BASE_CLASS_NETWORK: deviceclass = hw::network; deviceicon = "network"; break; case PCI_BASE_CLASS_MEMORY: deviceclass = hw::memory; deviceicon = "memory"; break; case PCI_BASE_CLASS_BRIDGE: deviceclass = hw::bridge; break; case PCI_BASE_CLASS_MULTIMEDIA: deviceclass = hw::multimedia; if(dclass == PCI_CLASS_MULTIMEDIA_AUDIO) deviceicon = "audio"; break; case PCI_BASE_CLASS_DISPLAY: deviceclass = hw::display; deviceicon = "display"; break; case PCI_BASE_CLASS_COMMUNICATION: deviceclass = hw::communication; if(dclass == PCI_CLASS_COMMUNICATION_SERIAL) deviceicon = "serial"; if(dclass == PCI_CLASS_COMMUNICATION_PARALLEL) deviceicon = "parallel"; if(dclass == PCI_CLASS_COMMUNICATION_MODEM) deviceicon = "modem"; break; case PCI_BASE_CLASS_SYSTEM: deviceclass = hw::generic; break; case PCI_BASE_CLASS_INPUT: deviceclass = hw::input; break; case PCI_BASE_CLASS_PROCESSOR: deviceclass = hw::processor; break; case PCI_BASE_CLASS_SERIAL: deviceclass = hw::bus; if(dclass == PCI_CLASS_SERIAL_USB) deviceicon = "usb"; if(dclass == PCI_CLASS_SERIAL_FIREWIRE) deviceicon = "firewire"; break; } devicename = get_class_name(dclass); hwNode *device = new hwNode(devicename, deviceclass); if (device) { if(deviceicon != "") device->addHint("icon", deviceicon); addHints(*device, d.vendor_id, d.device_id, subsys_v, subsys_d, dclass); if (deviceclass == hw::bridge || deviceclass == hw::storage) device->addCapability(devicename); if(device->isCapable("isa") || device->isCapable("pci") || device->isCapable("agp")) device->claim(); scan_resources(*device, d); scan_capabilities(*device, d); if (deviceclass == hw::display) for (int j = 0; j < 6; j++) if ((d.size[j] != 0xffffffff) && (d.size[j] > device->getSize())) device->setSize(d.size[j]); if (dclass == PCI_CLASS_BRIDGE_PCI) { device->setHandle(pci_bushandle(get_conf_byte(d, PCI_SECONDARY_BUS), d.domain)); device->claim(); } else { char irq[10]; snprintf(irq, sizeof(irq), "%d", d.irq); device->setHandle(pci_handle(d.bus, d.dev, d.func, d.domain)); device->setConfig("latency", latency); if(max_lat) device->setConfig("maxlatency", max_lat); if(min_gnt) device->setConfig("mingnt", min_gnt); if (d.irq != 0) { //device->setConfig("irq", irq); device->addResource(hw::resource::irq(d.irq)); } } device->setDescription(get_class_description(dclass)); if (moredescription != "" && moredescription != device->getDescription()) { device->addCapability(moredescription); } device->setVendor(get_device_description(d.vendor_id)+(enabled("output:numeric")?" ["+tohex(d.vendor_id)+"]":"")); device->setVersion(revision); device->setProduct(get_device_description(d.vendor_id, d.device_id)+(enabled("output:numeric")?" ["+tohex(d.vendor_id)+":"+tohex(d.device_id)+"]":"")); if (cmd & PCI_COMMAND_MASTER) device->addCapability("bus master", "bus mastering"); if (cmd & PCI_COMMAND_VGA_PALETTE) device->addCapability("VGA palette", "VGA palette"); if (status & PCI_STATUS_CAP_LIST) device->addCapability("cap list", "PCI capabilities listing"); if (status & PCI_STATUS_66MHZ) device->setClock(66000000UL); // 66MHz else device->setClock(33000000UL); // 33MHz device->setPhysId(d.dev, d.func); hwNode *bus = NULL; bus = n.findChildByHandle(pci_bushandle(d.bus, d.domain)); device->describeCapability("vga", "VGA graphical framebuffer"); device->describeCapability("pcmcia", "PC-Card (PCMCIA)"); device->describeCapability("generic", "Generic interface"); device->describeCapability("ohci", "Open Host Controller Interface"); device->describeCapability("uhci", "Universal Host Controller Interface (USB1)"); device->describeCapability("ehci", "Enhanced Host Controller Interface (USB2)"); if (bus) result = bus->addChild(*device); else { if (core) result = core->addChild(*device); else result = n.addChild(*device); } delete device; } } return result; } bool scan_pci_legacy(hwNode & n) { FILE *f; hwNode *core = n.getChild("core"); if (!core) { n.addChild(hwNode("core", hw::bus)); core = n.getChild("core"); } if(!pcidb_loaded) pcidb_loaded = load_pcidb(); f = fopen(PROC_BUS_PCI "/devices", "r"); if (f) { char buf[512]; while (fgets(buf, sizeof(buf) - 1, f)) { unsigned int dfn, vend, cnt; struct pci_dev d; int fd = -1; string devicepath = ""; char devicename[20]; char businfo[20]; char driver[50]; hwNode *device = NULL; memset(&d, 0, sizeof(d)); memset(driver, 0, sizeof(driver)); cnt = sscanf(buf, "%x %x %x %llx %llx %llx %llx %llx %llx %llx %llx %llx %llx %llx %llx %llx %llx %[ -z]s", &dfn, &vend, &d.irq, &d.base_addr[0], &d.base_addr[1], &d.base_addr[2], &d.base_addr[3], &d.base_addr[4], &d.base_addr[5], &d.rom_base_addr, &d.size[0], &d.size[1], &d.size[2], &d.size[3], &d.size[4], &d.size[5], &d.rom_size, driver); if (cnt != 9 && cnt != 10 && cnt != 17 && cnt != 18) break; d.bus = dfn >> 8; d.dev = PCI_SLOT(dfn & 0xff); d.func = PCI_FUNC(dfn & 0xff); d.vendor_id = vend >> 16; d.device_id = vend & 0xffff; snprintf(devicename, sizeof(devicename), "%02x/%02x.%x", d.bus, d.dev, d.func); devicepath = string(PROC_BUS_PCI) + "/" + string(devicename); snprintf(businfo, sizeof(businfo), "%02x:%02x.%x", d.bus, d.dev, d.func); fd = open(devicepath.c_str(), O_RDONLY); if (fd >= 0) { if(read(fd, d.config, sizeof(d.config)) != sizeof(d.config)) memset(&d.config, 0, sizeof(d.config)); close(fd); } device = scan_pci_dev(d, n); if(device) { device->setBusInfo(businfo); } } fclose(f); } return false; } bool scan_pci(hwNode & n) { bool result = false; dirent **devices = NULL; int count = 0; hwNode *core = n.getChild("core"); if (!core) { n.addChild(hwNode("core", hw::bus)); core = n.getChild("core"); } pcidb_loaded = load_pcidb(); if(!pushd(SYS_BUS_PCI"/devices")) return false; count = scandir(".", &devices, selectlink, alphasort); if(count>=0) { int i = 0; for(i=0; i<count; i++) if(matches(devices[i]->d_name, "^[[:xdigit:]]+:[[:xdigit:]]+:[[:xdigit:]]+\\.[[:xdigit:]]+$")) { string devicepath = string(devices[i]->d_name)+"/config"; struct pci_dev d; int fd = open(devicepath.c_str(), O_RDONLY); if (fd >= 0) { memset(&d, 0, sizeof(d)); if(read(fd, d.config, 64) == 64) { if(read(fd, d.config+64, sizeof(d.config)-64) != sizeof(d.config)-64) memset(d.config+64, 0, sizeof(d.config)-64); } close(fd); } sscanf(devices[i]->d_name, "%hx:%hx:%hhx.%hhx", &d.domain, &d.bus, &d.dev, &d.func); hwNode *device = scan_pci_dev(d, n); if(device) { string resourcename = string(devices[i]->d_name)+"/resource"; device->setBusInfo(devices[i]->d_name); if(exists(string(devices[i]->d_name)+"/driver")) { string drivername = readlink(string(devices[i]->d_name)+"/driver"); string modulename = readlink(string(devices[i]->d_name)+"/driver/module"); device->setConfig("driver", basename(drivername.c_str())); if(exists(modulename)) device->setConfig("module", basename(modulename.c_str())); if(exists(string(devices[i]->d_name)+"/rom")) { device->addCapability("rom", "extension ROM"); } if(exists(string(devices[i]->d_name)+"/irq")) { long irq = get_number(string(devices[i]->d_name)+"/irq", -1); if(irq>=0) device->addResource(hw::resource::irq(irq)); } device->claim(); } if(exists(resourcename)) { FILE*resource = fopen(resourcename.c_str(), "r"); if(resource) { while(!feof(resource)) { uint64_t start, end, flags; start = end = flags = 0; if(fscanf(resource, "%llx %llx %llx", &start, &end, &flags) != 3) break; if(flags & 0x101) device->addResource(hw::resource::ioport(start, end)); else if(flags & 0x100) device->addResource(hw::resource::iomem(start, end)); else if(flags & 0x200) device->addResource(hw::resource::mem(start, end, flags & 0x1000)); } fclose(resource); } } result = true; } free(devices[i]); } free(devices); } popd(); return result; }
29.367758
161
0.585499
[ "vector" ]
215f2ea6cdd6b88662c4fc1b15d44b6b7f31015d
1,126
cpp
C++
src/ListBaton.cpp
ntbosscher/node-serialport
54ca999ffd92be7196613ac78f38745a10ef52d5
[ "MIT" ]
null
null
null
src/ListBaton.cpp
ntbosscher/node-serialport
54ca999ffd92be7196613ac78f38745a10ef52d5
[ "MIT" ]
null
null
null
src/ListBaton.cpp
ntbosscher/node-serialport
54ca999ffd92be7196613ac78f38745a10ef52d5
[ "MIT" ]
null
null
null
#include "./ListBaton.h" #include <nan.h> v8::Local<v8::Value> ListBaton::getReturnValue() { v8::Local<v8::Array> results = Nan::New<v8::Array>(); int i = 0; for (std::list<unique_ptr<ListResultItem>>::iterator it = this->results.begin(); it != this->results.end(); ++it, i++) { v8::Local<v8::Object> item = Nan::New<v8::Object>(); setIfNotEmpty(item, "path", (*it)->path.c_str()); setIfNotEmpty(item, "manufacturer", (*it)->manufacturer.c_str()); setIfNotEmpty(item, "serialNumber", (*it)->serialNumber.c_str()); setIfNotEmpty(item, "pnpId", (*it)->pnpId.c_str()); setIfNotEmpty(item, "locationId", (*it)->locationId.c_str()); setIfNotEmpty(item, "vendorId", (*it)->vendorId.c_str()); setIfNotEmpty(item, "productId", (*it)->productId.c_str()); Nan::Set(results, i, item); } // cleanup list this->results.clear(); return results; } NAN_METHOD(List) { V8ArgDecoder args(&info); auto cb = args.takeFunction(); if(args.hasError()) return; ListBaton *baton = new ListBaton(cb); baton->start(); }
28.15
122
0.600355
[ "object" ]
21620355e99ce190e6a49c725eeba055f8ab3096
17,996
cpp
C++
SMB3_v2_C++/assets/classes/scene/ScenePlay.cpp
Izay0i/SuperMarioBros3
46d254aa1ae4396175145d9743932c5c4fbf1763
[ "MIT" ]
1
2020-11-09T09:08:02.000Z
2020-11-09T09:08:02.000Z
SMB3_v2_C++/assets/classes/scene/ScenePlay.cpp
Izay0i/SuperMarioBros3
46d254aa1ae4396175145d9743932c5c4fbf1763
[ "MIT" ]
null
null
null
SMB3_v2_C++/assets/classes/scene/ScenePlay.cpp
Izay0i/SuperMarioBros3
46d254aa1ae4396175145d9743932c5c4fbf1763
[ "MIT" ]
null
null
null
#include <random> #include "../Game.h" #include "../SceneManager.h" #include "Scene.h" #include "ScenePlay.h" #include "../EntityList.h" #include "../audio/AudioService.h" ScenePlay::ScenePlay(SceneType sceneID, std::string path) : Scene(sceneID, path) { _hurryUpTime = 3000; _pitch = 1.0f; } ScenePlay::~ScenePlay() {} bool ScenePlay::IsInHurry() const { return _hurryUpStart != 0; } void ScenePlay::StartHurryingUpTimer() { _hurryUpStart = static_cast<DWORD>(GetTickCount64()); } void ScenePlay::HandleStates() { _player->HandleStates(); } void ScenePlay::OnKeyUp(int keyCode) { _player->OnKeyUpGame(keyCode); } void ScenePlay::OnKeyDown(int keyCode) { switch (keyCode) { case DIK_1: _player->SetHealth(1); break; case DIK_2: if (_player->GetHealth() == 1) { _player->SetPosition({ _player->GetPosition().x, _player->GetPosition().y - _player->GetBoxHeight(1) }); } _player->SetHealth(2); break; case DIK_3: if (_player->GetHealth() == 1) { _player->SetPosition({ _player->GetPosition().x, _player->GetPosition().y - _player->GetBoxHeight(1) }); } _player->SetHealth(3); break; case DIK_4: if (_player->GetHealth() == 1) { _player->SetPosition({ _player->GetPosition().x, _player->GetPosition().y - _player->GetBoxHeight(1) }); } _player->SetHealth(4); break; } _player->OnKeyDownGame(keyCode); } void ScenePlay::LoadScene() { Scene::LoadScene(); AudioService::GetAudio().PlayAudio(static_cast<AudioType>(_currentThemeID), true); } void ScenePlay::UpdateCameraPosition() { unsigned int index = _player->WentIntoPipe(); RECTF cameraBound = _cameraInstance->GetCameraBound(index); _player->SetUpVector(_cameraInstance->GetUpVector(index)); D3DXVECTOR2 cameraPosition = _cameraInstance->GetPosition(); if (!_player->TriggeredStageEnd() && !_player->IsInPipe()) { if (_player->GetPosition().x < cameraPosition.x) { _player->SetPosition({ cameraPosition.x, _player->GetPosition().y }); } else if (_player->GetPosition().x + _player->GetBoxWidth() > _sceneWidth) { _player->SetPosition({ _sceneWidth - _player->GetBoxWidth(), _player->GetPosition().y }); } if (_player->GetPosition().y < cameraBound.top) { _player->SetPosition({ _player->GetPosition().x, cameraPosition.y }); } } cameraPosition = _player->GetPosition(); if (!_player->lockCameraXAxis) { cameraPosition.x -= Game::GetInstance()->GetWindowWidth() / 2.25f; } if (cameraPosition.x < cameraBound.left) { cameraPosition.x = cameraBound.left; } else if (cameraPosition.x + Game::GetInstance()->GetWindowWidth() > cameraBound.right) { cameraPosition.x = cameraBound.right - Game::GetInstance()->GetWindowWidth(); } cameraPosition.y -= Game::GetInstance()->GetWindowHeight() / 2.25f; if (_player->WentIntoPipe() || _player->IsFlying() || _player->GetPosition().y < _sceneHeight * _lockValue) { if (cameraPosition.y < cameraBound.top) { cameraPosition.y = cameraBound.top; } else if (cameraPosition.y + Game::GetInstance()->GetWindowHeight() > cameraBound.bottom) { cameraPosition.y = cameraBound.bottom - Game::GetInstance()->GetWindowHeight(); } } else { cameraPosition.y = cameraBound.bottom - Game::GetInstance()->GetWindowHeight(); } _cameraInstance->SetPosition(cameraPosition); } void ScenePlay::Update(DWORD deltaTime) { if (_player == nullptr) { char debug[100]; sprintf_s(debug, "[SCENE] No player loaded in, scene ID: %d\n", _sceneID); OutputDebugStringA(debug); return; } if (_player->GetHealth() > 0 && !_player->TriggeredStageEnd()) { if (_sceneTime > 0 && GetTickCount64() % 1000 == 0) { --_sceneTime; } } if ((_sceneTime == 0 && !_player->TriggeredStageEnd() && _player->GetHealth() != 0) || _player->GetPosition().y > _sceneHeight) { if (_player->GetHealth() != 0) { _player->SetHealth(1); _player->TakeDamage(); } } //---------------------------------------------------------------------------- //SOUNDS //---------------------------------------------------------------------------- if (_sceneTime == _NEAR_TIME_LIMIT && !_isInHurry) { _isInHurry = true; _hurryUp = true; StartHurryingUpTimer(); AudioService::GetAudio().StopAll(); AudioService::GetAudio().PlayAudio(AudioType::AUDIO_TYPE_STAGE_HURRY); } if (_isInHurry && _hurryUp) { _hurryUp = false; _pitch = 1.04f; } if (IsInHurry() && GetTickCount64() - _hurryUpStart > _hurryUpTime) { _hurryUpStart = 0; AudioService::GetAudio().PlayAudio(static_cast<AudioType>(_currentThemeID), true, _pitch); } if (_player->IsInPipe()) { if (_player->WentIntoPipe() && !_isInSecret) { _isInSecret = true; AudioService::GetAudio().StopAudio(static_cast<AudioType>(_currentThemeID)); AudioService::GetAudio().PlayAudio(static_cast<AudioType>(_GetNextThemeID()), true, _pitch); } else if (!_player->WentIntoPipe() && _isInSecret) { _isInSecret = false; AudioService::GetAudio().StopAudio(static_cast<AudioType>(_currentThemeID)); AudioService::GetAudio().PlayAudio(static_cast<AudioType>(_GetNextThemeID()), true, _pitch); } } //---------------------------------------------------------------------------- //SOUNDS //---------------------------------------------------------------------------- if (_player->GetHealth() == 0 || _player->IsInvulnerable()) { _player->Update(deltaTime, &_entities, &_tiles, _grid); } else if (_player->GetHealth() > 0 && !_player->IsInvulnerable()) { //Range-based loop, for_each, iterators will all be invalidated if an element is either removed or inserted //And the container has to do a reallocation for (unsigned int i = 0; i < _entities.size(); ++i) { Entity* entity = _entities.at(i); entity->SetActive(_IsEntityInViewport(entity, _cameraInstance->GetViewport())); entity->Update(deltaTime, &_entities, &_tiles, _grid); //Entities events switch (entity->GetObjectType()) { case GameObject::GameObjectType::GAMEOBJECT_TYPE_PARAGOOMBA: { Paragoomba* paragoomba = dynamic_cast<Paragoomba*>(entity); if (paragoomba->IsWalking() && paragoomba->GetHealth() == 2) { //Mario is on the right side if (paragoomba->GetPosition().x - _player->GetPosition().x < 0.0f) { paragoomba->SetNormal({ -1.0f, 0.0f }); } else { paragoomba->SetNormal({ 1.0f, 0.0f }); } } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_KOOPA: case GameObject::GameObjectType::GAMEOBJECT_TYPE_PARAKOOPA: { Koopa* koopa = dynamic_cast<Koopa*>(entity); if (koopa->GetHealth() == 2) { //Mario is on the right side if (koopa->GetPosition().x - _player->GetPosition().x < 0.0f) { koopa->SetNormal({ -1.0f, 0.0f }); } else { koopa->SetNormal({ 1.0f, 0.0f }); } } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_PIRANHAPLANT: case GameObject::GameObjectType::GAMEOBJECT_TYPE_VENUSPLANT: { PiranaPlant* piranaPlant = dynamic_cast<PiranaPlant*>(entity); piranaPlant->ComparePlayerPosToSelf(_player->GetPosition()); //Mario is on the right side if (piranaPlant->GetPosition().x - _player->GetPosition().x < 0.0f) { piranaPlant->SetScale({ -1.0f, piranaPlant->GetScale().y }); } else { piranaPlant->SetScale({ 1.0f, piranaPlant->GetScale().y }); } //Mario is below if (piranaPlant->GetPosition().y - _player->GetPosition().y < 0.0f) { piranaPlant->SetNormal({ -1.0f, piranaPlant->GetNormal().y }); } else { piranaPlant->SetNormal({ 1.0f, piranaPlant->GetNormal().y }); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_DRYBONES: { DryBones* dryBones = dynamic_cast<DryBones*>(entity); if (dryBones->GetHealth() == 2) { //Mario is on the right side if (dryBones->GetPosition().x - _player->GetPosition().x < 0.0f) { dryBones->SetScale({ -1.0f, dryBones->GetScale().y }); } else { dryBones->SetScale({ 1.0f, dryBones->GetScale().y }); } } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_TAIL: { const float OFFSET = 4.0f; Tail* tail = dynamic_cast<Tail*>(entity); tail->SetPosition({ _player->GetPosition().x, _player->IsAttacking() ? _player->GetPosition().y + OFFSET : 0.0f } ); } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_REDMUSHROOM: case GameObject::GameObjectType::GAMEOBJECT_TYPE_GREENMUSHROOM: { Mushroom* mushroom = dynamic_cast<Mushroom*>(entity); if (mushroom->IsEmerging()) { //Mario is on the right side if (mushroom->GetPosition().x - _player->GetPosition().x < 0.0f) { mushroom->SetNormal({ 1.0f, 1.0f }); } else { mushroom->SetNormal({ -1.0f, 1.0f }); } } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_ORB: { const std::vector<D3DXCOLOR> colors = { D3DXCOLOR(70 / 255.0f, 199 / 255.0f, 78 / 255.0f, 1.0f), //green D3DXCOLOR(142 / 255.0f, 145 / 255.0f, 255 / 255.0f, 1.0f), //purple D3DXCOLOR(255 / 255.0f, 136 / 255.0f, 122 / 255.0f, 1.0f), //orange D3DXCOLOR(255 / 255.0f, 204 / 255.0f, 198 / 255.0f, 1.0f), //peach }; Orb* orb = dynamic_cast<Orb*>(entity); if (orb->tookDamage) { std::random_device device; std::mt19937 rng(device()); std::uniform_int_distribution<std::mt19937::result_type> dist(0, colors.size() - 1); _backgroundColor = colors.at(dist(rng)); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_QUESTIONBLOCK: { QuestionBlock* questionBlock = dynamic_cast<QuestionBlock*>(entity); if (questionBlock->tookDamage) { AddEntityToScene(questionBlock->SpawnItem(_player->GetHealth())); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_SHINYBRICK: { ShinyBrick* shinyBrick = dynamic_cast<ShinyBrick*>(entity); if (shinyBrick->tookDamage) { AddEntityToScene(shinyBrick->SpawnItem()); } else if (shinyBrick->GetHealth() == -1) { const float BOUNCE_SPEED_0 = 0.28f; const float BOUNCE_SPEED_1 = 0.18f; const float RUN_SPEED = 0.08f; const float OFFSET = 10.0f; //Top left auto debris = shinyBrick->SpawnDebris(); debris->SetVelocity({ -RUN_SPEED, -BOUNCE_SPEED_0 }); AddEntityToScene(debris); //Top right debris = shinyBrick->SpawnDebris(); debris->SetScale({ -1.0f, 1.0f }); debris->SetVelocity({ RUN_SPEED, -BOUNCE_SPEED_0 }); AddEntityToScene(debris); //Bottom left debris = shinyBrick->SpawnDebris(); debris->SetVelocity({ -RUN_SPEED, -BOUNCE_SPEED_1 }); debris->SetPosition({ debris->GetPosition().x, debris->GetPosition().y + OFFSET }); AddEntityToScene(debris); //Bottom right debris = shinyBrick->SpawnDebris(); debris->SetScale({ -1.0f, 1.0f }); debris->SetVelocity({ RUN_SPEED, -BOUNCE_SPEED_1 }); debris->SetPosition({ debris->GetPosition().x, debris->GetPosition().y + OFFSET }); AddEntityToScene(debris); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_PBLOCK: { PBlock* pBlock = dynamic_cast<PBlock*>(entity); if (pBlock->IsActivated() && pBlock->tookDamage) { AudioService::GetAudio().StopAudio(static_cast<AudioType>(_currentThemeID)); AudioService::GetAudio().PlayAudio(AudioType::AUDIO_TYPE_STAGE_PCOIN); } else if (pBlock->hasEnded) { pBlock->hasEnded = false; AudioService::GetAudio().StopAudio(AudioType::AUDIO_TYPE_STAGE_PCOIN); AudioService::GetAudio().PlayAudio(static_cast<AudioType>(_currentThemeID), true, _pitch); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_FORTRESSBOSS: { FortressBoss* fortressBoss = dynamic_cast<FortressBoss*>(entity); if (fortressBoss->GetHealth() > 0) { //Mario is on the right side if (fortressBoss->GetPosition().x - _player->GetPosition().x < 0.0f) { fortressBoss->SetNormal({ 1.0f, 1.0f }); } else { fortressBoss->SetNormal({ -1.0f, 1.0f }); } } if (fortressBoss->GetHealth() <= 0 && !fortressBoss->IsInvulnerable()) { const float BOUNCE_SPEED = 0.04f; auto orb = fortressBoss->SpawnOrb(); orb->SetVelocity({ 0.0f, -BOUNCE_SPEED }); AddEntityToScene(orb); const float OFFSET = 8.0f; // * // * * //* o * // * * // * auto effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ 0.0f, -1.0f }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ -1.0f, -1.0f }); effect->SetPosition({ effect->GetPosition().x + OFFSET, effect->GetPosition().y + OFFSET }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ 1.0f, -1.0f }); effect->SetPosition({ effect->GetPosition().x - OFFSET, effect->GetPosition().y + OFFSET }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ -1.0f, 0.0f }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ 1.0f, 0.0f }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ -1.0f, 1.0f }); effect->SetPosition({ effect->GetPosition().x + OFFSET, effect->GetPosition().y - OFFSET }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ 1.0f, 1.0f }); effect->SetPosition({ effect->GetPosition().x - OFFSET, effect->GetPosition().y - OFFSET }); AddEntityToScene(effect); effect = fortressBoss->SpawnOrbEffect(); effect->SetNormal({ 0.0f, 1.0f }); AddEntityToScene(effect); fortressBoss->SetPosition({ fortressBoss->GetPosition().x, static_cast<float>(_sceneHeight) }); } } break; case GameObject::GameObjectType::GAMEOBJECT_TYPE_TRIGGER: { Trigger* trigger = dynamic_cast<Trigger*>(entity); if (trigger->triggered) { trigger->triggered = false; _currentThemeID = static_cast<unsigned int>(AudioType::AUDIO_TYPE_BATTLE_MINIBOSS); } } break; } if (entity->tookDamage) { _scorePopUp->GetEntity(entity); _scorePopUp->SetPosition(entity->GetPosition()); _scorePopUp->StartFloatTimer(); entity->tookDamage = false; } if (_grid != nullptr) { Cell* newCell = _grid->GetCell(entity->GetPosition()); if (newCell != entity->ownerCell) { _grid->RemoveEntity(entity); _grid->AddEntity(entity, newCell); } } //I manage to bring down the time complexity from O(n^3) to O(n^2) //Reason is how the grid system handles removal //Instead of using std::erase(std::remove()) which takes O(n) //I use vector swap & pop //Since vector insertion and removal from the front and back is constant time O(1) //But I can't remove this bottom line here to bring it down to O(n) //For some reason the particles won't render if I try to remove them outside of the loop //Faster machines may handle O(n^2) complexity but slower ones will definitely have some trouble if (!_IsEntityAliveAndIB(entity)) { if (_grid != nullptr) { _grid->RemoveEntity(entity); } _removedEntities.emplace_back(entity); _entities.erase(std::remove(_entities.begin(), _entities.end(), entity), _entities.end()); } } std::sort(_entities.begin(), _entities.end(), Entity::CompareRenderPriority); } UpdateCameraPosition(); _scorePopUp->Update(deltaTime); const float HUD_OFFSET_X = 134.0f; const float HUD_OFFSET_Y = 161.0f; _hud->Update(_sceneTime); _hud->SetPosition({ floor(_cameraInstance->GetPosition().x) + HUD_OFFSET_X, floor(_cameraInstance->GetPosition().y) + HUD_OFFSET_Y } ); _background->Update(); if (_player->TriggeredStageEnd() || _player->GetHealth() == 0 || _sceneTime == 0) { //Warp back to map if (!IsTransitioningToScene()) { StartToSceneTimer(); _player->GetSceneRemainingTime(_sceneTime); _sceneTime = 0; } if (IsTransitioningToScene() && GetTickCount64() - _toSceneStart > _toSceneTime) { _toSceneStart = 0; SceneManager::GetInstance()->ChangeScene(static_cast<unsigned int>(SceneType::SCENE_TYPE_MAP)); } } } void ScenePlay::Render() { _background->Render(); for (unsigned int i = 0; i < _entities.size(); ++i) { Entity* entity = _entities.at(i); if (entity->IsActive()) { entity->Render(); } } _scorePopUp->Render(); _hud->Render(); } void ScenePlay::Release() { char debug[100]; sprintf_s(debug, "[SCENE] Unloading scene with ID: %d\n", _sceneID); OutputDebugStringA(debug); AudioService::GetAudio().StopAll(); _background->Release(); delete _background; _hud->Release(); delete _hud; _scorePopUp->Release(); delete _scorePopUp; if (_grid != nullptr) { _grid->Release(); delete _grid; } for (auto& tile : _tiles) { tile->Release(); delete tile; } _tiles.clear(); for (unsigned int i = 0; i < _removedEntities.size(); ++i) { _removedEntities.at(i)->Release(); delete _removedEntities.at(i); } _removedEntities.clear(); for (unsigned int i = 0; i < _entities.size(); ++i) { _entities.at(i)->Release(); delete _entities.at(i); } _entities.clear(); for (auto& texture : _textureMap) { texture.second->Release(); delete texture.second; } _textureMap.clear(); if (_cameraInstance != nullptr) { _cameraInstance->Release(); } sprintf_s(debug, "[SCENE] Unloaded scene with ID: %d\n", _sceneID); OutputDebugStringA(debug); }
31.907801
110
0.634308
[ "render", "vector" ]
2167b05d3c4679256335107fb29fa6de6ef02449
802
cc
C++
core/core.cc
theanarkh/No.js
0a1a72ada412a46de8994691b9b490092e515157
[ "MIT" ]
42
2021-06-09T02:25:35.000Z
2022-02-16T06:12:44.000Z
core/core.cc
tangkepeng/No.js
5569dec2d416118cc33b1209c9d4569e51094921
[ "MIT" ]
null
null
null
core/core.cc
tangkepeng/No.js
5569dec2d416118cc33b1209c9d4569e51094921
[ "MIT" ]
2
2021-09-19T02:24:21.000Z
2021-10-07T13:28:42.000Z
#include "core.h" void No::Core::register_builtins(Isolate * isolate, Local<Object> No) { Local<Object> target = Object::New(isolate); FS::Init(isolate, target); TCP::Init(isolate, target); Process::Init(isolate, target); Console::Init(isolate, target); IO::Init(isolate, target); Net::Init(isolate, target); UDP::Init(isolate, target); UNIX_DOMAIN::Init(isolate, target); Signal::Init(isolate, target); Timer::Init(isolate, target); Inotify::Init(isolate, target); Loader::Init(isolate, target); Util::Init(isolate, target); VM::Init(isolate, target); HTTP::Init(isolate, target); setObjectValue(isolate, No, "buildin", target); } void No::Core::Run(io_uring_info * io_uring_data) { io_uring::RunIOUring(io_uring_data); }
32.08
71
0.663342
[ "object" ]
216e6e304e1163eeb453b59188eecda675233b3f
50,781
cpp
C++
VulkanBunnyMark/base/VulkanFramework.cpp
re-esper/BunnyMarkGame
43a570dd2ecf9fd35e834208e3b440216d0d1455
[ "MIT" ]
7
2020-01-09T01:59:59.000Z
2020-09-05T15:15:46.000Z
VulkanBunnyMark/base/VulkanFramework.cpp
re-esper/BunnyMarkGame
43a570dd2ecf9fd35e834208e3b440216d0d1455
[ "MIT" ]
null
null
null
VulkanBunnyMark/base/VulkanFramework.cpp
re-esper/BunnyMarkGame
43a570dd2ecf9fd35e834208e3b440216d0d1455
[ "MIT" ]
null
null
null
/* * Vulkan Example base class * * Copyright (C) by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "VulkanFramework.h" std::vector<const char*> VulkanFramework::args; VkResult VulkanFramework::createInstance(bool enableValidation) { settings.validation = enableValidation; // Validation can also be forced via a define #if defined(_VALIDATION) settings.validation = true; #endif VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO }; appInfo.pApplicationName = name.c_str(); appInfo.pEngineName = name.c_str(); appInfo.apiVersion = apiVersion; std::vector<const char*> instanceExtensions = { VK_KHR_SURFACE_EXTENSION_NAME }; // Enable surface extensions depending on os #if defined(_WIN32) instanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); #elif defined(VK_USE_PLATFORM_ANDROID_KHR) instanceExtensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME); #elif defined(VK_USE_PLATFORM_IOS_MVK) instanceExtensions.push_back(VK_MVK_IOS_SURFACE_EXTENSION_NAME); #elif defined(VK_USE_PLATFORM_MACOS_MVK) instanceExtensions.push_back(VK_MVK_MACOS_SURFACE_EXTENSION_NAME); #endif if (enabledInstanceExtensions.size() > 0) { for (auto enabledExtension : enabledInstanceExtensions) { instanceExtensions.push_back(enabledExtension); } } VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO }; instanceCreateInfo.pApplicationInfo = &appInfo; if (instanceExtensions.size() > 0) { if (settings.validation) { instanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } instanceCreateInfo.enabledExtensionCount = (uint32_t)instanceExtensions.size(); instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data(); } if (settings.validation) { // The VK_LAYER_KHRONOS_validation contains all current validation functionality. // Note that on Android this layer requires at least NDK r20 const char* validationLayerName = "VK_LAYER_KHRONOS_validation"; // Check if this layer is available at instance level uint32_t instanceLayerCount; vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr); std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerCount); vkEnumerateInstanceLayerProperties(&instanceLayerCount, instanceLayerProperties.data()); bool validationLayerPresent = false; for (VkLayerProperties layer : instanceLayerProperties) { if (strcmp(layer.layerName, validationLayerName) == 0) { validationLayerPresent = true; break; } } if (validationLayerPresent) { instanceCreateInfo.ppEnabledLayerNames = &validationLayerName; instanceCreateInfo.enabledLayerCount = 1; } else { std::cerr << "Validation layer VK_LAYER_KHRONOS_validation not present, validation is disabled"; } } return vkCreateInstance(&instanceCreateInfo, nullptr, &instance); } std::string VulkanFramework::getWindowTitle() { std::string device(deviceProperties.deviceName); std::string windowTitle; windowTitle = title + " - " + device; if (!settings.overlay) { windowTitle += " - " + std::to_string(frameCounter) + " fps"; } return windowTitle; } #if !(defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)) // iOS & macOS: VulkanFramework::getAssetPath() implemented externally to allow access to Objective-C components const std::string VulkanFramework::getAssetPath() { #if defined(VK_USE_PLATFORM_ANDROID_KHR) return ""; #else return "./../data/"; #endif } #endif void VulkanFramework::createCommandBuffers() { // Create one command buffer for each swap chain image and reuse for rendering drawCmdBuffers.resize(swapChain.imageCount); drawCmdBuffersValid.resize(swapChain.imageCount, false); VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo( cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, static_cast<uint32_t>(drawCmdBuffers.size()) ); VK_CHECK(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, drawCmdBuffers.data())); } void VulkanFramework::destroyCommandBuffers() { vkFreeCommandBuffers(device, cmdPool, static_cast<uint32_t>(drawCmdBuffers.size()), drawCmdBuffers.data()); } void VulkanFramework::invalidateCommandBuffers() { std::fill(drawCmdBuffersValid.begin(), drawCmdBuffersValid.end(), false); } VkCommandBuffer VulkanFramework::createCommandBuffer(VkCommandBufferLevel level, bool begin) { VkCommandBuffer cmdBuffer; VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, level, 1); VK_CHECK(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &cmdBuffer)); // If requested, also start the new command buffer if (begin) { VkCommandBufferBeginInfo cmdBufInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; VK_CHECK(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo)); } return cmdBuffer; } void VulkanFramework::flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free) { if (commandBuffer == VK_NULL_HANDLE) { return; } VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkQueueWaitIdle(queue)); if (free) { vkFreeCommandBuffers(device, cmdPool, 1, &commandBuffer); } } void VulkanFramework::createPipelineCache() { VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; VK_CHECK(vkCreatePipelineCache(device, &pipelineCacheCreateInfo, nullptr, &pipelineCache)); } void VulkanFramework::prepare() { initSwapchain(); createCommandPool(); setupSwapChain(); createCommandBuffers(); createSynchronizationPrimitives(); setupDepthStencil(); setupRenderPass(); createPipelineCache(); setupFrameBuffer(); if (settings.overlay) { UIOverlay.device = vulkanDevice; UIOverlay.queue = queue; UIOverlay.shaders = { loadShader(getAssetPath() + "shaders/base/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), loadShader(getAssetPath() + "shaders/base/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT), }; UIOverlay.prepareResources(); UIOverlay.preparePipeline(pipelineCache, renderPass); } } VkPipelineShaderStageCreateInfo VulkanFramework::loadShader(std::string fileName, VkShaderStageFlagBits stage) { VkPipelineShaderStageCreateInfo shaderStage = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO }; shaderStage.stage = stage; #if defined(VK_USE_PLATFORM_ANDROID_KHR) shaderStage.module = vks::tools::loadShader(androidApp->activity->assetManager, fileName.c_str(), device); #else shaderStage.module = vks::tools::loadShader(fileName.c_str(), device); #endif shaderStage.pName = "main"; // todo : make param assert(shaderStage.module != VK_NULL_HANDLE); shaderModules.push_back(shaderStage.module); return shaderStage; } void VulkanFramework::renderFrame() { auto tStart = std::chrono::high_resolution_clock::now(); if (viewUpdated) { viewUpdated = false; viewChanged(); } render(); frameCounter++; auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); frameDeltaTime = (float)tDiff / 1000.0f; camera.update(frameDeltaTime); if (camera.moving()) { viewUpdated = true; } // Convert to clamped timer value if (!paused) { timer += timerSpeed * frameDeltaTime; if (timer > 1.0) timer -= 1.0f; } float fpsTimer = (float)(std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count()); if (fpsTimer > 1000.0f) { lastFPS = static_cast<uint32_t>((float)frameCounter * (1000.0f / fpsTimer)); #if defined(_WIN32) if (!settings.overlay) { std::string windowTitle = getWindowTitle(); SetWindowText(window, windowTitle.c_str()); } #endif frameCounter = 0; lastTimestamp = tEnd; } // TODO: Cap UI overlay update rates updateOverlay(); } void VulkanFramework::renderLoop() { destWidth = width; destHeight = height; lastTimestamp = std::chrono::high_resolution_clock::now(); #if defined(_WIN32) MSG msg = { 0 }; while (WM_QUIT != msg.message) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { renderFrame(); } } #elif defined(VK_USE_PLATFORM_ANDROID_KHR) while (1) { int ident; int events; struct android_poll_source* source; bool destroy = false; focused = true; while ((ident = ALooper_pollAll(focused ? 0 : -1, NULL, &events, (void**)&source)) >= 0) { if (source != NULL) { source->process(androidApp, source); } if (androidApp->destroyRequested != 0) { LOGD("Android app destroy requested"); destroy = true; break; } } // App destruction requested // Exit loop, example will be destroyed in application main if (destroy) { ANativeActivity_finish(androidApp->activity); break; } // Render frame if (prepared) { auto tStart = std::chrono::high_resolution_clock::now(); render(); frameCounter++; auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); frameDeltaTime = tDiff / 1000.0f; camera.update(frameDeltaTime); // Convert to clamped timer value if (!paused) { timer += timerSpeed * frameDeltaTime; if (timer > 1.0) { timer -= 1.0f; } } float fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count(); if (fpsTimer > 1000.0f) { lastFPS = (float)frameCounter * (1000.0f / fpsTimer); frameCounter = 0; lastTimestamp = tEnd; } // TODO: Cap UI overlay update rates/only issue when update requested updateOverlay(); bool updateView = false; // Check touch state (for movement) if (touchDown) { touchTimer += frameDeltaTime; } if (touchTimer >= 1.0) { camera.keys.up = true; viewChanged(); } // Check gamepad state const float deadZone = 0.0015f; // todo : check if gamepad is present // todo : time based and relative axis positions if (camera.type != Camera::CameraType::firstperson) { // Rotate if (std::abs(gamePadState.axisLeft.x) > deadZone) { rotation.y += gamePadState.axisLeft.x * 0.5f * rotationSpeed; camera.rotate(glm::vec3(0.0f, gamePadState.axisLeft.x * 0.5f, 0.0f)); updateView = true; } if (std::abs(gamePadState.axisLeft.y) > deadZone) { rotation.x -= gamePadState.axisLeft.y * 0.5f * rotationSpeed; camera.rotate(glm::vec3(gamePadState.axisLeft.y * 0.5f, 0.0f, 0.0f)); updateView = true; } // Zoom if (std::abs(gamePadState.axisRight.y) > deadZone) { zoom -= gamePadState.axisRight.y * 0.01f * zoomSpeed; updateView = true; } if (updateView) { viewChanged(); } } else { updateView = camera.updatePad(gamePadState.axisLeft, gamePadState.axisRight, frameDeltaTime); if (updateView) { viewChanged(); } } } } #endif // Flush device to make sure all resources can be freed if (device != VK_NULL_HANDLE) { vkDeviceWaitIdle(device); } } void VulkanFramework::updateOverlay() { if (!settings.overlay) return; ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)width, (float)height); io.DeltaTime = frameDeltaTime; io.MousePos = ImVec2(mousePos.x, mousePos.y); io.MouseDown[0] = mouseButtons.left; io.MouseDown[1] = mouseButtons.right; ImGui::NewFrame(); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::SetNextWindowPos(ImVec2(10, 10)); ImGui::SetNextWindowSize(ImVec2(0, 0), ImGuiSetCond_FirstUseEver); ImGui::Begin(title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::TextUnformatted(deviceProperties.deviceName); ImGui::Text("%.2f ms/frame (%.1d fps)", (1000.0f / lastFPS), lastFPS); #if defined(VK_USE_PLATFORM_ANDROID_KHR) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 5.0f * UIOverlay.scale)); #endif ImGui::PushItemWidth(110.0f * UIOverlay.scale); onUpdateUIOverlay(&UIOverlay); ImGui::PopItemWidth(); #if defined(VK_USE_PLATFORM_ANDROID_KHR) ImGui::PopStyleVar(); #endif ImGui::End(); ImGui::PopStyleVar(); ImGui::Render(); if (UIOverlay.update() || UIOverlay.updated) { invalidateCommandBuffers(); UIOverlay.updated = false; } #if defined(VK_USE_PLATFORM_ANDROID_KHR) if (mouseButtons.left) { mouseButtons.left = false; } #endif } void VulkanFramework::drawUI(const VkCommandBuffer commandBuffer) { if (settings.overlay) { const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); UIOverlay.draw(commandBuffer); } } void VulkanFramework::prepareFrame() { // Acquire the next image from the swap chain VkResult result = swapChain.acquireNextImage(semaphores.presentComplete, &currentBuffer); // Recreate the swapchain if it's no longer compatible with the surface (OUT_OF_DATE) or no longer optimal for presentation (SUBOPTIMAL) if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR)) { windowResize(); } else { VK_CHECK(result); } } void VulkanFramework::submitFrame() { // Present the current buffer to the swap chain // Pass the semaphore signaled by the command buffer submission from the submit info as the wait semaphore for swap chain presentation // This ensures that the image is not presented to the windowing system until all commands have been submitted VkResult result = swapChain.queuePresent(queue, currentBuffer, semaphores.renderComplete); if (!((result == VK_SUCCESS) || (result == VK_SUBOPTIMAL_KHR))) { if (result == VK_ERROR_OUT_OF_DATE_KHR) { // Swap chain is no longer compatible with the surface and needs to be recreated windowResize(); return; } else { VK_CHECK(result); } } } VulkanFramework::VulkanFramework(bool enableValidation) { #if !defined(VK_USE_PLATFORM_ANDROID_KHR) // Check for a valid asset path struct stat info; if (stat(getAssetPath().c_str(), &info) != 0) { #if defined(_WIN32) std::string msg = "Could not locate asset path in \"" + getAssetPath() + "\" !"; MessageBox(NULL, msg.c_str(), "Fatal error", MB_OK | MB_ICONERROR); #else std::cerr << "Error: Could not find asset path in " << getAssetPath() << std::endl; #endif exit(-1); } #endif settings.validation = enableValidation; char* numConvPtr; // Parse command line arguments for (size_t i = 0; i < args.size(); i++) { if (args[i] == std::string("-validation")) { settings.validation = true; } if (args[i] == std::string("-vsync")) { settings.vsync = true; } if ((args[i] == std::string("-f")) || (args[i] == std::string("--fullscreen"))) { settings.fullscreen = true; } if ((args[i] == std::string("-w")) || (args[i] == std::string("-width"))) { uint32_t w = strtol(args[i + 1], &numConvPtr, 10); if (numConvPtr != args[i + 1]) { width = w; }; } if ((args[i] == std::string("-h")) || (args[i] == std::string("-height"))) { uint32_t h = strtol(args[i + 1], &numConvPtr, 10); if (numConvPtr != args[i + 1]) { height = h; }; } } VK_CHECK(volkInitialize()); #if defined(_WIN32) // Enable console if validation is active // Debug message callback will output to it if (this->settings.validation) { setupConsole("Vulkan validation output"); } setupDPIAwareness(); #endif } VulkanFramework::~VulkanFramework() { // Clean up Vulkan resources swapChain.cleanup(); if (descriptorPool != VK_NULL_HANDLE) { vkDestroyDescriptorPool(device, descriptorPool, nullptr); } destroyCommandBuffers(); vkDestroyRenderPass(device, renderPass, nullptr); for (uint32_t i = 0; i < frameBuffers.size(); i++) { vkDestroyFramebuffer(device, frameBuffers[i], nullptr); } for (auto& shaderModule : shaderModules) { vkDestroyShaderModule(device, shaderModule, nullptr); } vkDestroyImageView(device, depthStencil.view, nullptr); vkDestroyImage(device, depthStencil.image, nullptr); vkFreeMemory(device, depthStencil.mem, nullptr); vkDestroyPipelineCache(device, pipelineCache, nullptr); vkDestroyCommandPool(device, cmdPool, nullptr); vkDestroySemaphore(device, semaphores.presentComplete, nullptr); vkDestroySemaphore(device, semaphores.renderComplete, nullptr); for (auto& fence : waitFences) { vkDestroyFence(device, fence, nullptr); } if (settings.overlay) { UIOverlay.freeResources(); } delete vulkanDevice; if (settings.validation) { vks::debug::freeDebugCallback(instance); } vkDestroyInstance(instance, nullptr); // todo : android cleanup (if required) } bool VulkanFramework::initVulkan() { VkResult err; // Vulkan instance err = createInstance(settings.validation); if (err) { vks::tools::exitFatal("Could not create Vulkan instance : \n" + vks::tools::errorString(err), err); return false; } volkLoadInstance(instance); // If requested, we enable the default validation layers for debugging if (settings.validation) { // The report flags determine what type of messages for the layers will be displayed // For validating (debugging) an appplication the error and warning bits should suffice VkDebugReportFlagsEXT debugReportFlags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; // Additional flags include performance info, loader and layer debug messages, etc. vks::debug::setupDebugging(instance, debugReportFlags, VK_NULL_HANDLE); } // Physical device uint32_t gpuCount = 0; // Get number of available physical devices VK_CHECK(vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr)); assert(gpuCount > 0); // Enumerate devices std::vector<VkPhysicalDevice> physicalDevices(gpuCount); err = vkEnumeratePhysicalDevices(instance, &gpuCount, physicalDevices.data()); if (err) { vks::tools::exitFatal("Could not enumerate physical devices : \n" + vks::tools::errorString(err), err); return false; } // GPU selection // Select physical device to be used for the Vulkan example // Defaults to the first device unless specified by command line uint32_t selectedDevice = 0; #if !defined(VK_USE_PLATFORM_ANDROID_KHR) // GPU selection via command line argument for (size_t i = 0; i < args.size(); i++) { // Select GPU if ((args[i] == std::string("-g")) || (args[i] == std::string("-gpu"))) { char* endptr; uint32_t index = strtol(args[i + 1], &endptr, 10); if (endptr != args[i + 1]) { if (index > gpuCount - 1) { std::cerr << "Selected device index " << index << " is out of range, reverting to device 0 (use -listgpus to show available Vulkan devices)" << std::endl; } else { std::cout << "Selected Vulkan device " << index << std::endl; selectedDevice = index; } }; break; } // List available GPUs if (args[i] == std::string("-listgpus")) { uint32_t gpuCount = 0; VK_CHECK(vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr)); if (gpuCount == 0) { std::cerr << "No Vulkan devices found!" << std::endl; } else { // Enumerate devices std::cout << "Available Vulkan devices" << std::endl; std::vector<VkPhysicalDevice> devices(gpuCount); VK_CHECK(vkEnumeratePhysicalDevices(instance, &gpuCount, devices.data())); for (uint32_t i = 0; i < gpuCount; i++) { VkPhysicalDeviceProperties deviceProperties; vkGetPhysicalDeviceProperties(devices[i], &deviceProperties); std::cout << "Device [" << i << "] : " << deviceProperties.deviceName << std::endl; std::cout << " Type: " << vks::tools::physicalDeviceTypeString(deviceProperties.deviceType) << std::endl; std::cout << " API: " << (deviceProperties.apiVersion >> 22) << "." << ((deviceProperties.apiVersion >> 12) & 0x3ff) << "." << (deviceProperties.apiVersion & 0xfff) << std::endl; } } } } #endif physicalDevice = physicalDevices[selectedDevice]; // Store properties (including limits), features and memory properties of the phyiscal device (so that examples can check against them) vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties); vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures); vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties); // Derived examples can override this to set actual features (based on above readings) to enable for logical device creation getEnabledFeatures(); // Vulkan device creation // This is handled by a separate class that gets a logical device representation // and encapsulates functions related to a device vulkanDevice = new vks::VulkanDevice(physicalDevice); VkResult res = vulkanDevice->createLogicalDevice(enabledFeatures, enabledDeviceExtensions, deviceCreatepNextChain, true, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT); if (res != VK_SUCCESS) { vks::tools::exitFatal("Could not create Vulkan device: \n" + vks::tools::errorString(res), res); return false; } device = vulkanDevice->device; if (vulkanDevice->enableDebugMarkers) { vks::debugmarker::setup(device); } // Get a graphics queue from the device vkGetDeviceQueue(device, vulkanDevice->queueFamilyIndices.graphics, 0, &queue); // Find a suitable depth format VkBool32 validDepthFormat = vks::tools::getSupportedDepthFormat(physicalDevice, &depthFormat); assert(validDepthFormat); // Create synchronization objects VkSemaphoreCreateInfo semaphoreCreateInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; // Ensures that the image is displayed before we start submitting new commands to the queue VK_CHECK(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete)); // Ensures that the image is not presented until all commands have been sumbitted and executed VK_CHECK(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete)); // Set up submit info structure // Semaphores will stay the same during application lifetime // Command buffer submission info is set by each example VkSubmitInfo sinfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; sinfo.pWaitDstStageMask = &submitPipelineStages; sinfo.waitSemaphoreCount = 1; sinfo.pWaitSemaphores = &semaphores.presentComplete; sinfo.signalSemaphoreCount = 1; sinfo.pSignalSemaphores = &semaphores.renderComplete; submitInfo = sinfo; #if defined(VK_USE_PLATFORM_ANDROID_KHR) // Get Android device name and manufacturer (to display along GPU name) androidProduct = ""; char prop[PROP_VALUE_MAX + 1]; int len = __system_property_get("ro.product.manufacturer", prop); if (len > 0) { androidProduct += std::string(prop) + " "; }; len = __system_property_get("ro.product.model", prop); if (len > 0) { androidProduct += std::string(prop); }; LOGD("androidProduct = %s", androidProduct.c_str()); #endif return true; } #if defined(_WIN32) // Win32 : Sets up a console window and redirects standard output to it void VulkanFramework::setupConsole(std::string title) { AllocConsole(); AttachConsole(GetCurrentProcessId()); FILE* stream; freopen_s(&stream, "CONOUT$", "w+", stdout); freopen_s(&stream, "CONOUT$", "w+", stderr); SetConsoleTitle(TEXT(title.c_str())); } void VulkanFramework::setupDPIAwareness() { typedef HRESULT*(__stdcall * SetProcessDpiAwarenessFunc)(PROCESS_DPI_AWARENESS); HMODULE shCore = LoadLibraryA("Shcore.dll"); if (shCore) { SetProcessDpiAwarenessFunc setProcessDpiAwareness = (SetProcessDpiAwarenessFunc)GetProcAddress(shCore, "SetProcessDpiAwareness"); if (setProcessDpiAwareness != nullptr) { setProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); } FreeLibrary(shCore); } } HWND VulkanFramework::setupWindow(HINSTANCE hinstance, WNDPROC wndproc) { windowInstance = hinstance; WNDCLASSEX wndClass; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = wndproc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hinstance; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = name.c_str(); wndClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); if (!RegisterClassEx(&wndClass)) { std::cout << "Could not register window class!\n"; fflush(stdout); exit(1); } int screenWidth = GetSystemMetrics(SM_CXSCREEN); int screenHeight = GetSystemMetrics(SM_CYSCREEN); if (settings.fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = screenWidth; dmScreenSettings.dmPelsHeight = screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if ((width != (uint32_t)screenWidth) && (height != (uint32_t)screenHeight)) { if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { if (MessageBox(NULL, "Fullscreen Mode not supported!\n Switch to window mode?", "Error", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { settings.fullscreen = false; } else { return nullptr; } } } } DWORD dwExStyle; DWORD dwStyle; if (settings.fullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; } RECT windowRect; windowRect.left = 0L; windowRect.top = 0L; windowRect.right = settings.fullscreen ? (long)screenWidth : (long)width; windowRect.bottom = settings.fullscreen ? (long)screenHeight : (long)height; AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); std::string windowTitle = getWindowTitle(); window = CreateWindowEx(0, name.c_str(), windowTitle.c_str(), dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, NULL, hinstance, NULL); if (!settings.fullscreen) { // Center on screen uint32_t x = (GetSystemMetrics(SM_CXSCREEN) - windowRect.right) / 2; uint32_t y = (GetSystemMetrics(SM_CYSCREEN) - windowRect.bottom) / 2; SetWindowPos(window, 0, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } if (!window) { printf("Could not create window!\n"); fflush(stdout); return nullptr; exit(1); } ShowWindow(window, SW_SHOW); SetForegroundWindow(window); SetFocus(window); return window; } void VulkanFramework::handleMessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: prepared = false; DestroyWindow(hWnd); PostQuitMessage(0); break; case WM_PAINT: ValidateRect(window, NULL); break; case WM_KEYDOWN: switch (wParam) { case KEY_P: paused = !paused; break; case KEY_F1: if (settings.overlay) { UIOverlay.visible = !UIOverlay.visible; } break; case KEY_ESCAPE: PostQuitMessage(0); break; } if (camera.firstperson) { switch (wParam) { case KEY_W: camera.keys.up = true; break; case KEY_S: camera.keys.down = true; break; case KEY_A: camera.keys.left = true; break; case KEY_D: camera.keys.right = true; break; } } keyPressed((uint32_t)wParam); break; case WM_KEYUP: if (camera.firstperson) { switch (wParam) { case KEY_W: camera.keys.up = false; break; case KEY_S: camera.keys.down = false; break; case KEY_A: camera.keys.left = false; break; case KEY_D: camera.keys.right = false; break; } } break; case WM_LBUTTONDOWN: mousePos = glm::vec2((float)LOWORD(lParam), (float)HIWORD(lParam)); mouseButtons.left = true; break; case WM_RBUTTONDOWN: mousePos = glm::vec2((float)LOWORD(lParam), (float)HIWORD(lParam)); mouseButtons.right = true; break; case WM_MBUTTONDOWN: mousePos = glm::vec2((float)LOWORD(lParam), (float)HIWORD(lParam)); mouseButtons.middle = true; break; case WM_LBUTTONUP: mouseButtons.left = false; break; case WM_RBUTTONUP: mouseButtons.right = false; break; case WM_MBUTTONUP: mouseButtons.middle = false; break; case WM_MOUSEWHEEL: { short wheelDelta = GET_WHEEL_DELTA_WPARAM(wParam); zoom += (float)wheelDelta * 0.005f * zoomSpeed; camera.translate(glm::vec3(0.0f, 0.0f, (float)wheelDelta * 0.005f * zoomSpeed)); viewUpdated = true; break; } case WM_MOUSEMOVE: { handleMouseMove(LOWORD(lParam), HIWORD(lParam)); break; } case WM_SIZE: if ((prepared) && (wParam != SIZE_MINIMIZED)) { if ((resizing) || ((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))) { destWidth = LOWORD(lParam); destHeight = HIWORD(lParam); windowResize(); } } break; case WM_ENTERSIZEMOVE: resizing = true; break; case WM_EXITSIZEMOVE: resizing = false; break; } } #elif defined(VK_USE_PLATFORM_ANDROID_KHR) int32_t VulkanFramework::handleAppInput(struct android_app* app, AInputEvent* event) { VulkanFramework* vulkanApp = reinterpret_cast<VulkanFramework*>(app->userData); if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { int32_t eventSource = AInputEvent_getSource(event); switch (eventSource) { case AINPUT_SOURCE_JOYSTICK: { // Left thumbstick vulkanApp->gamePadState.axisLeft.x = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_X, 0); vulkanApp->gamePadState.axisLeft.y = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_Y, 0); // Right thumbstick vulkanApp->gamePadState.axisRight.x = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_Z, 0); vulkanApp->gamePadState.axisRight.y = AMotionEvent_getAxisValue(event, AMOTION_EVENT_AXIS_RZ, 0); break; } case AINPUT_SOURCE_TOUCHSCREEN: { int32_t action = AMotionEvent_getAction(event); switch (action) { case AMOTION_EVENT_ACTION_UP: { vulkanApp->lastTapTime = AMotionEvent_getEventTime(event); vulkanApp->touchPos.x = AMotionEvent_getX(event, 0); vulkanApp->touchPos.y = AMotionEvent_getY(event, 0); vulkanApp->touchTimer = 0.0; vulkanApp->touchDown = false; vulkanApp->camera.keys.up = false; // Detect single tap int64_t eventTime = AMotionEvent_getEventTime(event); int64_t downTime = AMotionEvent_getDownTime(event); if (eventTime - downTime <= vks::android::TAP_TIMEOUT) { float deadZone = (160.f / vks::android::screenDensity) * vks::android::TAP_SLOP * vks::android::TAP_SLOP; float x = AMotionEvent_getX(event, 0) - vulkanApp->touchPos.x; float y = AMotionEvent_getY(event, 0) - vulkanApp->touchPos.y; if ((x * x + y * y) < deadZone) { vulkanApp->mouseButtons.left = true; } }; return 1; break; } case AMOTION_EVENT_ACTION_DOWN: { // Detect double tap int64_t eventTime = AMotionEvent_getEventTime(event); if (eventTime - vulkanApp->lastTapTime <= vks::android::DOUBLE_TAP_TIMEOUT) { float deadZone = (160.f / vks::android::screenDensity) * vks::android::DOUBLE_TAP_SLOP * vks::android::DOUBLE_TAP_SLOP; float x = AMotionEvent_getX(event, 0) - vulkanApp->touchPos.x; float y = AMotionEvent_getY(event, 0) - vulkanApp->touchPos.y; if ((x * x + y * y) < deadZone) { vulkanApp->keyPressed(TOUCH_DOUBLE_TAP); vulkanApp->touchDown = false; } } else { vulkanApp->touchDown = true; } vulkanApp->touchPos.x = AMotionEvent_getX(event, 0); vulkanApp->touchPos.y = AMotionEvent_getY(event, 0); vulkanApp->mousePos.x = AMotionEvent_getX(event, 0); vulkanApp->mousePos.y = AMotionEvent_getY(event, 0); break; } case AMOTION_EVENT_ACTION_MOVE: { bool handled = false; if (vulkanApp->settings.overlay) { ImGuiIO& io = ImGui::GetIO(); handled = io.WantCaptureMouse; } if (!handled) { int32_t eventX = AMotionEvent_getX(event, 0); int32_t eventY = AMotionEvent_getY(event, 0); float deltaX = (float)(vulkanApp->touchPos.y - eventY) * vulkanApp->rotationSpeed * 0.5f; float deltaY = (float)(vulkanApp->touchPos.x - eventX) * vulkanApp->rotationSpeed * 0.5f; vulkanApp->camera.rotate(glm::vec3(deltaX, 0.0f, 0.0f)); vulkanApp->camera.rotate(glm::vec3(0.0f, -deltaY, 0.0f)); vulkanApp->rotation.x += deltaX; vulkanApp->rotation.y -= deltaY; vulkanApp->viewChanged(); vulkanApp->touchPos.x = eventX; vulkanApp->touchPos.y = eventY; } break; } default: return 1; break; } } return 1; } } if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { int32_t keyCode = AKeyEvent_getKeyCode((const AInputEvent*)event); int32_t action = AKeyEvent_getAction((const AInputEvent*)event); int32_t button = 0; if (action == AKEY_EVENT_ACTION_UP) return 0; switch (keyCode) { case AKEYCODE_BUTTON_A: vulkanApp->keyPressed(GAMEPAD_BUTTON_A); break; case AKEYCODE_BUTTON_B: vulkanApp->keyPressed(GAMEPAD_BUTTON_B); break; case AKEYCODE_BUTTON_X: vulkanApp->keyPressed(GAMEPAD_BUTTON_X); break; case AKEYCODE_BUTTON_Y: vulkanApp->keyPressed(GAMEPAD_BUTTON_Y); break; case AKEYCODE_BUTTON_L1: vulkanApp->keyPressed(GAMEPAD_BUTTON_L1); break; case AKEYCODE_BUTTON_R1: vulkanApp->keyPressed(GAMEPAD_BUTTON_R1); break; case AKEYCODE_BUTTON_START: vulkanApp->paused = !vulkanApp->paused; break; }; LOGD("Button %d pressed", keyCode); } return 0; } void VulkanFramework::handleAppCommand(android_app* app, int32_t cmd) { assert(app->userData != NULL); VulkanFramework* vulkanApp = reinterpret_cast<VulkanFramework*>(app->userData); switch (cmd) { case APP_CMD_SAVE_STATE: LOGD("APP_CMD_SAVE_STATE"); /* vulkanApp->app->savedState = malloc(sizeof(struct saved_state)); *((struct saved_state*)vulkanApp->app->savedState) = vulkanApp->state; vulkanApp->app->savedStateSize = sizeof(struct saved_state); */ break; case APP_CMD_INIT_WINDOW: LOGD("APP_CMD_INIT_WINDOW"); if (androidApp->window != NULL) { if (vulkanApp->initVulkan()) { vulkanApp->prepare(); assert(vulkanApp->prepared); } else { LOGE("Could not initialize Vulkan, exiting!"); androidApp->destroyRequested = 1; } } else { LOGE("No window assigned!"); } break; case APP_CMD_LOST_FOCUS: LOGD("APP_CMD_LOST_FOCUS"); vulkanApp->focused = false; break; case APP_CMD_GAINED_FOCUS: LOGD("APP_CMD_GAINED_FOCUS"); vulkanApp->focused = true; break; case APP_CMD_TERM_WINDOW: // Window is hidden or closed, clean up resources LOGD("APP_CMD_TERM_WINDOW"); if (vulkanApp->prepared) { vulkanApp->swapChain.cleanup(); } break; } } #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)) void* VulkanFramework::setupWindow(void* view) { this->view = view; return view; } #endif void VulkanFramework::createSynchronizationPrimitives() { // Wait fences to sync command buffer access VkFenceCreateInfo fenceCreateInfo = vks::initializers::fenceCreateInfo(VK_FENCE_CREATE_SIGNALED_BIT); waitFences.resize(drawCmdBuffers.size()); for (auto& fence : waitFences) { VK_CHECK(vkCreateFence(device, &fenceCreateInfo, nullptr, &fence)); } } void VulkanFramework::createCommandPool() { VkCommandPoolCreateInfo cmdPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO }; cmdPoolInfo.queueFamilyIndex = swapChain.queueNodeIndex; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VK_CHECK(vkCreateCommandPool(device, &cmdPoolInfo, nullptr, &cmdPool)); } void VulkanFramework::setupDepthStencil() { VkImageCreateInfo imageCI = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; imageCI.imageType = VK_IMAGE_TYPE_2D; imageCI.format = depthFormat; imageCI.extent = { width, height, 1 }; imageCI.mipLevels = 1; imageCI.arrayLayers = 1; imageCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCI.tiling = VK_IMAGE_TILING_OPTIMAL; imageCI.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; VK_CHECK(vkCreateImage(device, &imageCI, nullptr, &depthStencil.image)); VkMemoryRequirements memReqs{}; vkGetImageMemoryRequirements(device, depthStencil.image, &memReqs); VkMemoryAllocateInfo memAllloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; memAllloc.allocationSize = memReqs.size; memAllloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK(vkAllocateMemory(device, &memAllloc, nullptr, &depthStencil.mem)); VK_CHECK(vkBindImageMemory(device, depthStencil.image, depthStencil.mem, 0)); VkImageViewCreateInfo imageViewCI = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; imageViewCI.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCI.image = depthStencil.image; imageViewCI.format = depthFormat; imageViewCI.subresourceRange.baseMipLevel = 0; imageViewCI.subresourceRange.levelCount = 1; imageViewCI.subresourceRange.baseArrayLayer = 0; imageViewCI.subresourceRange.layerCount = 1; imageViewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; // Stencil aspect should only be set on depth + stencil formats (VK_FORMAT_D16_UNORM_S8_UINT..VK_FORMAT_D32_SFLOAT_S8_UINT if (depthFormat >= VK_FORMAT_D16_UNORM_S8_UINT) { imageViewCI.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } VK_CHECK(vkCreateImageView(device, &imageViewCI, nullptr, &depthStencil.view)); } void VulkanFramework::setupFrameBuffer() { VkImageView attachments[2]; // Depth/Stencil attachment is the same for all frame buffers attachments[1] = depthStencil.view; VkFramebufferCreateInfo frameBufferCreateInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; frameBufferCreateInfo.renderPass = renderPass; frameBufferCreateInfo.attachmentCount = 2; frameBufferCreateInfo.pAttachments = attachments; frameBufferCreateInfo.width = width; frameBufferCreateInfo.height = height; frameBufferCreateInfo.layers = 1; // Create frame buffers for every swap chain image frameBuffers.resize(swapChain.imageCount); for (uint32_t i = 0; i < frameBuffers.size(); i++) { attachments[0] = swapChain.buffers[i].view; VK_CHECK(vkCreateFramebuffer(device, &frameBufferCreateInfo, nullptr, &frameBuffers[i])); } } void VulkanFramework::setupRenderPass() { std::array<VkAttachmentDescription, 2> attachments = {}; // Color attachment attachments[0].format = swapChain.colorFormat; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Depth attachment attachments[1].format = depthFormat; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = {}; colorReference.attachment = 0; colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference = {}; depthReference.attachment = 1; depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; subpassDescription.pDepthStencilAttachment = &depthReference; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; subpassDescription.pResolveAttachments = nullptr; // Subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); renderPassInfo.pAttachments = attachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpassDescription; renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); VK_CHECK(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass)); } void VulkanFramework::getEnabledFeatures() { // Can be overriden in derived class } void VulkanFramework::windowResize() { if (!prepared) return; prepared = false; // Ensure all operations on the device have been finished before destroying resources vkDeviceWaitIdle(device); // Recreate swap chain width = destWidth; height = destHeight; setupSwapChain(); // Recreate the frame buffers vkDestroyImageView(device, depthStencil.view, nullptr); vkDestroyImage(device, depthStencil.image, nullptr); vkFreeMemory(device, depthStencil.mem, nullptr); setupDepthStencil(); for (uint32_t i = 0; i < frameBuffers.size(); i++) { vkDestroyFramebuffer(device, frameBuffers[i], nullptr); } setupFrameBuffer(); if ((width > 0.0f) && (height > 0.0f)) { if (settings.overlay) { UIOverlay.resize(width, height); } } // Command buffers need to be recreated as they may store // references to the recreated frame buffer destroyCommandBuffers(); createCommandBuffers(); invalidateCommandBuffers(); vkDeviceWaitIdle(device); if ((width > 0.0f) && (height > 0.0f)) { camera.updateAspectRatio((float)width / (float)height); } // Notify derived class windowResized(); viewChanged(); prepared = true; } void VulkanFramework::handleMouseMove(int32_t x, int32_t y) { int32_t dx = (int32_t)mousePos.x - x; int32_t dy = (int32_t)mousePos.y - y; bool handled = false; if (settings.overlay) { ImGuiIO& io = ImGui::GetIO(); handled = io.WantCaptureMouse; } mouseMoved((float)x, (float)y, handled); if (handled) { mousePos = glm::vec2((float)x, (float)y); return; } if (mouseButtons.left) { rotation.x += dy * 1.25f * rotationSpeed; rotation.y -= dx * 1.25f * rotationSpeed; camera.rotate(glm::vec3(dy * camera.rotationSpeed, -dx * camera.rotationSpeed, 0.0f)); viewUpdated = true; } if (mouseButtons.right) { zoom += dy * .005f * zoomSpeed; camera.translate(glm::vec3(-0.0f, 0.0f, dy * .005f * zoomSpeed)); viewUpdated = true; } if (mouseButtons.middle) { cameraPos.x -= dx * 0.01f; cameraPos.y -= dy * 0.01f; camera.translate(glm::vec3(-dx * 0.01f, -dy * 0.01f, 0.0f)); viewUpdated = true; } mousePos = glm::vec2((float)x, (float)y); } void VulkanFramework::initSwapchain() { #if defined(_WIN32) swapChain.initialize(windowInstance, window, instance, physicalDevice, device); #elif defined(VK_USE_PLATFORM_ANDROID_KHR) swapChain.initialize(androidApp->window, instance, physicalDevice, device); #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)) swapChain.initialize(view, instance, physicalDevice, device); #endif } void VulkanFramework::setupSwapChain() { swapChain.create(&width, &height, settings.vsync); }
36.559395
198
0.64725
[ "render", "vector", "model" ]
217c58e224a8237ee1dbe7d0b7095195f43be962
13,183
cpp
C++
cpp/src/cylon/net/ops/gather.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
229
2020-07-01T14:05:10.000Z
2022-03-25T12:26:58.000Z
cpp/src/cylon/net/ops/gather.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
261
2020-06-30T23:23:15.000Z
2022-03-16T09:55:40.000Z
cpp/src/cylon/net/ops/gather.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
36
2020-06-30T23:14:52.000Z
2022-03-03T02:37:09.000Z
/* * 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. */ #include <mpi.h> #include <arrow/result.h> #include <cylon/net/mpi/mpi_operations.hpp> #include <cylon/util/macros.hpp> #include <numeric> std::vector<int32_t> totalBufferSizes(const std::vector<int32_t> &all_buffer_sizes, int num_buffers, int world_size) { std::vector<int32_t> total_buffer_sizes(num_buffers, 0); for (int w = 0; w < world_size; w++) { for (int i = 0; i < num_buffers; i++) { total_buffer_sizes[i] += all_buffer_sizes[w * num_buffers + i]; } } return total_buffer_sizes; } std::vector<int32_t> receiveCounts(const std::vector<int32_t> &all_buffer_sizes, int receiveNo, int num_buffers, int world_size) { std::vector<int32_t> receive_counts(world_size, 0); for (int i = 0; i < world_size; ++i) { receive_counts[i] = all_buffer_sizes[i * num_buffers + receiveNo]; } return receive_counts; } std::vector<int32_t> displacementsPerBuffer(const std::vector<int32_t> &all_buffer_sizes, int receiveNo, int num_buffers, int world_size) { std::vector<int32_t> disp_array(world_size, 0); disp_array[0] = 0; for (int i = 0; i < world_size - 1; ++i) { disp_array[i + 1] = disp_array[i] + all_buffer_sizes[i * num_buffers + receiveNo]; } return disp_array; } cylon::Status cylon::mpi::Gather(const std::shared_ptr<cylon::TableSerializer> &serializer, int gather_root, bool gather_from_root, const std::shared_ptr<cylon::Allocator> &allocator, std::vector<int32_t> &all_buffer_sizes, std::vector<std::shared_ptr<cylon::Buffer>> &receive_buffers, std::vector<std::vector<int32_t>> &displacements, const std::shared_ptr<cylon::CylonContext> &ctx ) { // first gather table buffer sizes std::vector<int32_t> local_buffer_sizes; if (AmIRoot(gather_root, ctx) && !gather_from_root) { local_buffer_sizes = serializer->getEmptyTableBufferSizes(); } else { local_buffer_sizes = serializer->getBufferSizes(); } int32_t num_buffers = local_buffer_sizes.size(); // gather size buffers if (AmIRoot(gather_root, ctx)) { all_buffer_sizes.resize(ctx->GetWorldSize() * num_buffers); } int status = MPI_Gather(local_buffer_sizes.data(), num_buffers, MPI_INT32_T, all_buffer_sizes.data(), num_buffers, MPI_INT32_T, gather_root, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Gather failed!"); } std::vector<int32_t> total_buffer_sizes; if (AmIRoot(gather_root, ctx)) { totalBufferSizes(all_buffer_sizes, num_buffers, ctx->GetWorldSize()).swap(total_buffer_sizes); } std::vector<MPI_Request> requests(num_buffers); std::vector<MPI_Status> statuses(num_buffers); const std::vector<const uint8_t *> &send_buffers = serializer->getDataBuffers(); for (int32_t i = 0; i < num_buffers; ++i) { if (AmIRoot(gather_root, ctx)) { std::shared_ptr<cylon::Buffer> receive_buf; RETURN_CYLON_STATUS_IF_FAILED(allocator->Allocate(total_buffer_sizes[i], &receive_buf)); const auto &receive_counts = receiveCounts(all_buffer_sizes, i, num_buffers, ctx->GetWorldSize()); const auto &disp_per_buffer = displacementsPerBuffer(all_buffer_sizes, i, num_buffers, ctx->GetWorldSize()); displacements.push_back(disp_per_buffer); status = MPI_Igatherv(send_buffers[i], local_buffer_sizes[i], MPI_UINT8_T, receive_buf->GetByteBuffer(), receive_counts.data(), disp_per_buffer.data(), MPI_UINT8_T, gather_root, MPI_COMM_WORLD, &requests[i]); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Igatherv failed!"); } receive_buffers.push_back(receive_buf); } else { status = MPI_Igatherv(send_buffers[i], local_buffer_sizes[i], MPI_UINT8_T, nullptr, nullptr, nullptr, MPI_UINT8_T, gather_root, MPI_COMM_WORLD, &requests[i]); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Igatherv failed!"); } } } status = MPI_Waitall(num_buffers, requests.data(), statuses.data()); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Igatherv failed!"); } return cylon::Status::OK(); } cylon::Status cylon::mpi::GatherArrowBuffer(const std::shared_ptr<arrow::Buffer> &buf, int gather_root, const std::shared_ptr<cylon::CylonContext> &ctx, std::vector<std::shared_ptr<arrow::Buffer>> &buffers) { std::vector<int32_t> all_buffer_sizes; if (AmIRoot(gather_root, ctx)) { all_buffer_sizes.resize(ctx->GetWorldSize(), 0); } int32_t size = static_cast<int32_t>(buf->size()); int status = MPI_Gather(&size, 1, MPI_INT32_T, all_buffer_sizes.data(), 1, MPI_INT32_T, gather_root, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Gather failed when receiving buffer sizes!"); } CYLON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Buffer> all_buf, arrow::AllocateBuffer(0)); std::vector<int32_t> disps; if (AmIRoot(gather_root, ctx)) { auto total_size = std::accumulate(all_buffer_sizes.begin(), all_buffer_sizes.end(), 0); CYLON_ASSIGN_OR_RAISE(all_buf, arrow::AllocateBuffer(total_size)); disps.resize(ctx->GetWorldSize(), 0); std::partial_sum(all_buffer_sizes.begin(), all_buffer_sizes.end() - 1, disps.begin() + 1); } status = MPI_Gatherv(buf->data(), size, MPI_UINT8_T, (void *)all_buf->data(), all_buffer_sizes.data(), disps.data(), MPI_UINT8_T, gather_root, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Gatherv failed when receiving buffers!"); } if (gather_root == ctx->GetRank()) { buffers.resize(ctx->GetWorldSize()); for (int i = 0; i < ctx->GetWorldSize(); ++i) { buffers[i] = arrow::SliceBuffer(all_buf, disps[i], all_buffer_sizes[i]); } } return cylon::Status::OK(); } cylon::Status cylon::mpi::AllGather(const std::shared_ptr<cylon::TableSerializer> &serializer, const std::shared_ptr<cylon::Allocator> &allocator, std::vector<int32_t> &all_buffer_sizes, std::vector<std::shared_ptr<cylon::Buffer>> &received_buffers, std::vector<std::vector<int32_t>> &displacements, const std::shared_ptr<cylon::CylonContext> &ctx) { // first gather table buffer sizes const auto& local_buffer_sizes = serializer->getBufferSizes(); int32_t num_buffers = local_buffer_sizes.size(); all_buffer_sizes.resize(ctx->GetWorldSize() * num_buffers); int status = MPI_Allgather(local_buffer_sizes.data(), num_buffers, MPI_INT32_T, all_buffer_sizes.data(), num_buffers, MPI_INT32_T, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Allgather failed when receiving table sizes!"); } std::vector<int32_t> total_buffer_sizes = totalBufferSizes(all_buffer_sizes, num_buffers, ctx->GetWorldSize()); std::vector<MPI_Request> requests(num_buffers); std::vector<MPI_Status> statuses(num_buffers); const std::vector<const uint8_t *> &send_buffers = serializer->getDataBuffers(); for (int32_t i = 0; i < num_buffers; ++i) { std::shared_ptr<cylon::Buffer> receive_buf; RETURN_CYLON_STATUS_IF_FAILED(allocator->Allocate(total_buffer_sizes[i], &receive_buf)); const auto &receive_counts = receiveCounts(all_buffer_sizes, i, num_buffers, ctx->GetWorldSize()); auto disp_per_buffer = displacementsPerBuffer(all_buffer_sizes, i, num_buffers, ctx->GetWorldSize()); status = MPI_Iallgatherv(send_buffers[i], local_buffer_sizes[i], MPI_UINT8_T, receive_buf->GetByteBuffer(), receive_counts.data(), disp_per_buffer.data(), MPI_UINT8_T, MPI_COMM_WORLD, &requests[i]); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Iallgatherv failed when receiving table data!"); } displacements.push_back(std::move(disp_per_buffer)); received_buffers.push_back(std::move(receive_buf)); } status = MPI_Waitall(num_buffers, requests.data(), statuses.data()); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Iallgatherv failed!"); } return cylon::Status::OK(); } cylon::Status cylon::mpi::AllGatherArrowBuffer(const std::shared_ptr<arrow::Buffer> &buf, const std::shared_ptr<cylon::CylonContext> &ctx, std::vector<std::shared_ptr<arrow::Buffer>> &buffers) { std::vector<int32_t> all_buffer_sizes(ctx->GetWorldSize(), 0); int32_t size = static_cast<int32_t>(buf->size()); int status = MPI_Allgather(&size, 1, MPI_INT32_T, all_buffer_sizes.data(), 1, MPI_INT32_T, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Allgather failed when receiving buffer sizes!"); } auto total_size = std::accumulate(all_buffer_sizes.begin(), all_buffer_sizes.end(), 0); CYLON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Buffer> all_buf, arrow::AllocateBuffer(total_size)); std::vector<int32_t> disps(ctx->GetWorldSize(), 0); std::partial_sum(all_buffer_sizes.begin(), all_buffer_sizes.end() - 1, disps.begin() + 1); status = MPI_Allgatherv(buf->data(), size, MPI_UINT8_T, (void *)all_buf->data(), all_buffer_sizes.data(), disps.data(), MPI_UINT8_T, MPI_COMM_WORLD); if (status != MPI_SUCCESS) { return cylon::Status(cylon::Code::ExecutionError, "MPI_Allgatherv failed when receiving buffers!"); } buffers.resize(ctx->GetWorldSize()); for (int i = 0; i < ctx->GetWorldSize(); ++i) { buffers[i] = arrow::SliceBuffer(all_buf, disps[i], all_buffer_sizes[i]); } return cylon::Status::OK(); }
41.455975
113
0.550709
[ "vector" ]
217cac2d329442c6f6b8abecc975387c5e25da87
969
cpp
C++
LC0025.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
LC0025.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
LC0025.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode pre(0, head), *h = &pre; vector<ListNode*> p(k + 1, 0); p[0] = h; do{ for(int i = 1; i < k + 1; i++){ if(p[i - 1]){ p[i] = p[i - 1]->next; }else{ return h->next; } } if(!p[k]) return h->next; p[0]->next = p[k]; p[1]->next = p[k]->next; for(int i = k; i > 1; i--){ p[i]->next = p[i - 1]; } p[0] = p[1]; }while(p[0]->next); return h->next; } };
26.189189
62
0.379773
[ "vector" ]
2189b80b0c3248becbdb2f7d66781a3be2cd075f
15,735
cc
C++
mysql-server/sql/dd/impl/types/index_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/index_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/index_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql/dd/impl/types/index_impl.h" #include <stddef.h> #include <set> #include <sstream> #include <string> #include "my_rapidjson_size_t.h" // IWYU pragma: keep #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include "m_string.h" #include "my_inttypes.h" #include "my_sys.h" #include "mysqld_error.h" // ER_* #include "sql/dd/impl/bootstrap/bootstrap_ctx.h" // dd::bootstrap::DD_bootstrap_ctx #include "sql/dd/impl/properties_impl.h" // Properties_impl #include "sql/dd/impl/raw/raw_record.h" // Raw_record #include "sql/dd/impl/sdi_impl.h" // sdi read/write functions #include "sql/dd/impl/tables/index_column_usage.h" // Index_column_usage #include "sql/dd/impl/tables/indexes.h" // Indexes #include "sql/dd/impl/transaction_impl.h" // Open_dictionary_tables_ctx #include "sql/dd/impl/types/index_element_impl.h" // Index_element_impl #include "sql/dd/impl/types/table_impl.h" // Table_impl #include "sql/dd/properties.h" #include "sql/dd/string_type.h" // dd::String_type #include "sql/dd/types/column.h" #include "sql/dd/types/index_element.h" #include "sql/dd/types/object_table.h" #include "sql/dd/types/weak_object.h" #include "sql/field.h" using dd::tables::Index_column_usage; using dd::tables::Indexes; namespace dd { class Sdi_rcontext; class Sdi_wcontext; class Table; static const std::set<String_type> default_valid_option_keys = { "block_size", "flags", "parser_name"}; /////////////////////////////////////////////////////////////////////////// // Index_impl implementation. /////////////////////////////////////////////////////////////////////////// Index_impl::Index_impl() : m_hidden(false), m_is_generated(false), m_ordinal_position(0), m_options(default_valid_option_keys), m_se_private_data(), m_type(IT_MULTIPLE), m_algorithm(IA_BTREE), m_is_algorithm_explicit(false), m_is_visible(true), m_table(nullptr), m_elements(), m_tablespace_id(INVALID_OBJECT_ID) {} Index_impl::Index_impl(Table_impl *table) : m_hidden(false), m_is_generated(false), m_ordinal_position(0), m_options(default_valid_option_keys), m_se_private_data(), m_type(IT_MULTIPLE), m_algorithm(IA_BTREE), m_is_algorithm_explicit(false), m_is_visible(true), m_table(table), m_elements(), m_tablespace_id(INVALID_OBJECT_ID) {} Index_impl::~Index_impl() {} /////////////////////////////////////////////////////////////////////////// const Table &Index_impl::table() const { return *m_table; } Table &Index_impl::table() { return *m_table; } /////////////////////////////////////////////////////////////////////////// bool Index_impl::validate() const { if (!m_table) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "No table object associated with this index."); return true; } if (m_engine.empty()) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "Engine name is not set."); return true; } if (m_elements.empty()) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "The index has no elements."); return true; } return false; } /////////////////////////////////////////////////////////////////////////// bool Index_impl::restore_children(Open_dictionary_tables_ctx *otx) { return m_elements.restore_items( // Column will be resolved in restore_attributes() called from // Collection::restore_items(). this, otx, otx->get_table<Index_element>(), Index_column_usage::create_key_by_index_id(this->id())); } /////////////////////////////////////////////////////////////////////////// bool Index_impl::store_children(Open_dictionary_tables_ctx *otx) { return m_elements.store_items(otx); } /////////////////////////////////////////////////////////////////////////// bool Index_impl::drop_children(Open_dictionary_tables_ctx *otx) const { return m_elements.drop_items( otx, otx->get_table<Index_element>(), Index_column_usage::create_key_by_index_id(this->id())); } /////////////////////////////////////////////////////////////////////////// bool Index_impl::restore_attributes(const Raw_record &r) { if (check_parent_consistency(m_table, r.read_ref_id(Indexes::FIELD_TABLE_ID))) return true; restore_id(r, Indexes::FIELD_ID); restore_name(r, Indexes::FIELD_NAME); m_hidden = r.read_bool(Indexes::FIELD_HIDDEN); m_is_generated = r.read_bool(Indexes::FIELD_IS_GENERATED); m_ordinal_position = r.read_uint(Indexes::FIELD_ORDINAL_POSITION); m_comment = r.read_str(Indexes::FIELD_COMMENT); m_type = (enum_index_type)r.read_int(Indexes::FIELD_TYPE); m_algorithm = (enum_index_algorithm)r.read_int(Indexes::FIELD_ALGORITHM); m_is_algorithm_explicit = r.read_bool(Indexes::FIELD_IS_ALGORITHM_EXPLICIT); m_is_visible = r.read_bool(Indexes::FIELD_IS_VISIBLE); m_tablespace_id = r.read_ref_id(Indexes::FIELD_TABLESPACE_ID); set_options(r.read_str(Indexes::FIELD_OPTIONS, "")); set_se_private_data(r.read_str(Indexes::FIELD_SE_PRIVATE_DATA, "")); m_engine = r.read_str(Indexes::FIELD_ENGINE); // m_engine_attribute and m_secondary_engine_attribute was added in 80020 if (!bootstrap::DD_bootstrap_ctx::instance().is_dd_upgrade_from_before( bootstrap::DD_VERSION_80021)) { m_engine_attribute = r.read_str(Indexes::FIELD_ENGINE_ATTRIBUTE, ""); m_secondary_engine_attribute = r.read_str(Indexes::FIELD_SECONDARY_ENGINE_ATTRIBUTE, ""); } return false; } /////////////////////////////////////////////////////////////////////////// bool Index_impl::store_attributes(Raw_record *r) { // // Special cases dealing with NULL values for nullable fields // - Store NULL if tablespace id is not set // Eg: A non-innodb table may not have tablespace // - Store NULL if se_private_id is not set // Eg: A non-innodb table may not have se_private_id // - Store NULL in options if there are no key=value pairs // - Store NULL in se_private_data if there are no key=value pairs // Store engine_attributes and secondary_engine_attributes only if // we're not upgrading if (!bootstrap::DD_bootstrap_ctx::instance().is_dd_upgrade_from_before( bootstrap::DD_VERSION_80021) && (r->store(Indexes::FIELD_ENGINE_ATTRIBUTE, m_engine_attribute, m_engine_attribute.empty()) || r->store(Indexes::FIELD_SECONDARY_ENGINE_ATTRIBUTE, m_secondary_engine_attribute, m_secondary_engine_attribute.empty()))) { return true; } return store_id(r, Indexes::FIELD_ID) || store_name(r, Indexes::FIELD_NAME) || r->store(Indexes::FIELD_TABLE_ID, m_table->id()) || r->store(Indexes::FIELD_TYPE, m_type) || r->store(Indexes::FIELD_ALGORITHM, m_algorithm) || r->store(Indexes::FIELD_IS_ALGORITHM_EXPLICIT, m_is_algorithm_explicit) || r->store(Indexes::FIELD_IS_VISIBLE, m_is_visible) || r->store(Indexes::FIELD_IS_GENERATED, m_is_generated) || r->store(Indexes::FIELD_HIDDEN, m_hidden) || r->store(Indexes::FIELD_ORDINAL_POSITION, m_ordinal_position) || r->store(Indexes::FIELD_COMMENT, m_comment) || r->store(Indexes::FIELD_OPTIONS, m_options) || r->store(Indexes::FIELD_SE_PRIVATE_DATA, m_se_private_data) || r->store_ref_id(Indexes::FIELD_TABLESPACE_ID, m_tablespace_id) || r->store(Indexes::FIELD_ENGINE, m_engine); } /////////////////////////////////////////////////////////////////////////// static_assert(Indexes::NUMBER_OF_FIELDS == 17, "Indexes definition has changed, check if serialize() and " "deserialize() need to be updated!"); void Index_impl::serialize(Sdi_wcontext *wctx, Sdi_writer *w) const { w->StartObject(); Entity_object_impl::serialize(wctx, w); write(w, m_hidden, STRING_WITH_LEN("hidden")); write(w, m_is_generated, STRING_WITH_LEN("is_generated")); write(w, m_ordinal_position, STRING_WITH_LEN("ordinal_position")); write(w, m_comment, STRING_WITH_LEN("comment")); write_properties(w, m_options, STRING_WITH_LEN("options")); write_properties(w, m_se_private_data, STRING_WITH_LEN("se_private_data")); write_enum(w, m_type, STRING_WITH_LEN("type")); write_enum(w, m_algorithm, STRING_WITH_LEN("algorithm")); write(w, m_is_algorithm_explicit, STRING_WITH_LEN("is_algorithm_explicit")); write(w, m_is_visible, STRING_WITH_LEN("is_visible")); write(w, m_engine, STRING_WITH_LEN("engine")); write(w, m_engine_attribute, STRING_WITH_LEN("engine_attribute")); write(w, m_secondary_engine_attribute, STRING_WITH_LEN("secondary_engine_attribute")); serialize_each(wctx, w, m_elements, STRING_WITH_LEN("elements")); serialize_tablespace_ref(wctx, w, m_tablespace_id, STRING_WITH_LEN("tablespace_ref")); w->EndObject(); } /////////////////////////////////////////////////////////////////////////// bool Index_impl::deserialize(Sdi_rcontext *rctx, const RJ_Value &val) { Entity_object_impl::deserialize(rctx, val); read(&m_hidden, val, "hidden"); read(&m_is_generated, val, "is_generated"); read(&m_ordinal_position, val, "ordinal_position"); read(&m_comment, val, "comment"); read_properties(&m_options, val, "options"); read_properties(&m_se_private_data, val, "se_private_data"); read_enum(&m_type, val, "type"); read_enum(&m_algorithm, val, "algorithm"); read(&m_is_algorithm_explicit, val, "is_algorithm_explicit"); read(&m_is_visible, val, "is_visible"); read(&m_engine, val, "engine"); read(&m_engine_attribute, val, "engine_attribute"); read(&m_secondary_engine_attribute, val, "secondary_engine_attribute"); deserialize_each( rctx, [this]() { return add_element(nullptr); }, val, "elements"); if (deserialize_tablespace_ref(rctx, &m_tablespace_id, val, "tablespace_name")) { return true; } track_object(rctx, this); return false; } /////////////////////////////////////////////////////////////////////////// void Index_impl::debug_print(String_type &outb) const { dd::Stringstream_type ss; ss << "INDEX OBJECT: { " << "id: {OID: " << id() << "}; " << "m_table: {OID: " << m_table->id() << "}; " << "m_name: " << name() << "; " << "m_type: " << m_type << "; " << "m_algorithm: " << m_algorithm << "; " << "m_is_algorithm_explicit: " << m_is_algorithm_explicit << "; " << "m_is_visible: " << m_is_visible << "; " << "m_is_generated: " << m_is_generated << "; " << "m_comment: " << m_comment << "; " << "m_hidden: " << m_hidden << "; " << "m_ordinal_position: " << m_ordinal_position << "; " << "m_options " << m_options.raw_string() << "; " << "m_se_private_data " << m_se_private_data.raw_string() << "; " << "m_tablespace {OID: " << m_tablespace_id << "}; " << "m_engine: " << m_engine << "; " << "m_engine_attribute: " << m_engine_attribute << "; " << "m_secondary_engine_attribute: " << m_secondary_engine_attribute << "; " << "m_elements: " << m_elements.size() << " [ "; { for (const Index_element *c : elements()) { String_type ob; c->debug_print(ob); ss << ob; } } ss << "] "; ss << " }"; outb = ss.str(); } ///////////////////////////////////////////////////////////////////////// Index_element *Index_impl::add_element(Column *c) { Index_element_impl *e = new (std::nothrow) Index_element_impl(this, c); m_elements.push_back(e); return e; } ////////////////////////////////////////////////////////////////////////// /** Check if index represents candidate key. @note This function is in sync with how we evaluate TABLE_SHARE::primary_key. */ bool Index_impl::is_candidate_key() const { if (type() != Index::IT_PRIMARY && type() != Index::IT_UNIQUE) return false; for (const Index_element *idx_elem_obj : elements()) { // Skip hidden index elements if (idx_elem_obj->is_hidden()) continue; if (idx_elem_obj->column().is_nullable()) return false; if (idx_elem_obj->column().is_virtual()) return false; if (idx_elem_obj->column().type() == enum_column_types::GEOMETRY) return false; /* Probably we should adjust is_prefix() to take these two scenarios into account. But this also means that we probably need avoid setting HA_PART_KEY_SEG in them. */ if ((idx_elem_obj->column().type() == enum_column_types::TINY_BLOB && idx_elem_obj->length() == 255) || (idx_elem_obj->column().type() == enum_column_types::BLOB && idx_elem_obj->length() == 65535) || (idx_elem_obj->column().type() == enum_column_types::MEDIUM_BLOB && idx_elem_obj->length() == (1 << 24) - 1) || (idx_elem_obj->column().type() == enum_column_types::LONG_BLOB && idx_elem_obj->length() == (1LL << 32) - 1)) continue; if (idx_elem_obj->is_prefix()) return false; } return true; } /////////////////////////////////////////////////////////////////////////// Index_impl::Index_impl(const Index_impl &src, Table_impl *parent) : Weak_object(src), Entity_object_impl(src), m_hidden(src.m_hidden), m_is_generated(src.m_is_generated), m_ordinal_position(src.m_ordinal_position), m_comment(src.m_comment), m_options(src.m_options), m_se_private_data(src.m_se_private_data), m_type(src.m_type), m_algorithm(src.m_algorithm), m_is_algorithm_explicit(src.m_is_algorithm_explicit), m_is_visible(src.m_is_visible), m_engine(src.m_engine), m_engine_attribute(src.m_engine_attribute), m_secondary_engine_attribute(src.m_secondary_engine_attribute), m_table(parent), m_elements(), m_tablespace_id(src.m_tablespace_id) { m_elements.deep_copy(src.m_elements, this); } /////////////////////////////////////////////////////////////////////////// const Object_table &Index_impl::object_table() const { return DD_table::instance(); } /////////////////////////////////////////////////////////////////////////// void Index_impl::register_tables(Open_dictionary_tables_ctx *otx) { otx->add_table<Indexes>(); otx->register_tables<Index_element>(); } /////////////////////////////////////////////////////////////////////////// } // namespace dd
37.023529
84
0.629679
[ "geometry", "object" ]
218b6c20fc9e59162b9eb52e7cbd4b9bccaa8a6d
4,434
hpp
C++
src/backend/opencl/kernel/transform.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
4
2015-12-16T09:41:32.000Z
2018-10-29T10:38:53.000Z
src/backend/opencl/kernel/transform.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
3
2015-11-15T18:43:47.000Z
2015-12-16T09:43:14.000Z
src/backend/opencl/kernel/transform.hpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
null
null
null
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <kernel_headers/transform_interp.hpp> #include <kernel_headers/transform.hpp> #include <program.hpp> #include <traits.hpp> #include <string> #include <mutex> #include <map> #include <dispatch.hpp> #include <Param.hpp> #include <debug_opencl.hpp> using cl::Buffer; using cl::Program; using cl::Kernel; using cl::make_kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { namespace kernel { static const dim_type TX = 16; static const dim_type TY = 16; // Used for batching images static const dim_type TI = 4; template<typename T, bool isInverse, af_interp_type method> void transform(Param out, const Param in, const Param tf) { try { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static std::map<int, Program*> transformProgs; static std::map<int, Kernel *> transformKernels; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName() << " -D INVERSE=" << (isInverse ? 1 : 0); if((af_dtype) dtype_traits<T>::af_type == c32 || (af_dtype) dtype_traits<T>::af_type == c64) { options << " -D CPLX=1"; } else { options << " -D CPLX=0"; } if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value) { options << " -D USE_DOUBLE"; } switch(method) { case AF_INTERP_NEAREST: options << " -D INTERP=NEAREST"; break; case AF_INTERP_BILINEAR: options << " -D INTERP=BILINEAR"; break; default: break; } const char *ker_strs[] = {transform_interp_cl, transform_cl}; const int ker_lens[] = {transform_interp_cl_len, transform_cl_len}; Program prog; buildProgram(prog, 2, ker_strs, ker_lens, options.str()); transformProgs[device] = new Program(prog); transformKernels[device] = new Kernel(*transformProgs[device], "transform_kernel"); }); auto transformOp = make_kernel<Buffer, const KParam, const Buffer, const KParam, const Buffer, const KParam, const dim_type, const dim_type, const dim_type> (*transformKernels[device]); NDRange local(TX, TY, 1); dim_type nimages = in.info.dims[2]; dim_type global_x = local[0] * divup(out.info.dims[0], local[0]); const dim_type blocksXPerImage = global_x / local[0]; if(nimages > TI) { dim_type tile_images = divup(nimages, TI); nimages = TI; global_x = global_x * tile_images; } // Multiplied in src/backend/transform.cpp const dim_type ntransforms = out.info.dims[2] / in.info.dims[2]; NDRange global(global_x, local[1] * divup(out.info.dims[1], local[1]) * ntransforms, 1); transformOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data, in.info, *tf.data, tf.info, nimages, ntransforms, blocksXPerImage); CL_DEBUG_FINISH(getQueue()); } catch (cl::Error err) { CL_TO_AF_ERROR(err); throw; } } } }
37.576271
103
0.486243
[ "transform" ]
219052fe1f91b0d3ce2c0845ea9a018ed1391cce
19,466
cpp
C++
modules/arch/x86/X86Arch.cpp
rpavlik/assembler
08480a71611c1b077630897a93407b7e371f8074
[ "BSD-2-Clause" ]
1
2019-12-17T01:47:08.000Z
2019-12-17T01:47:08.000Z
modules/arch/x86/X86Arch.cpp
rpavlik/assembler
08480a71611c1b077630897a93407b7e371f8074
[ "BSD-2-Clause" ]
null
null
null
modules/arch/x86/X86Arch.cpp
rpavlik/assembler
08480a71611c1b077630897a93407b7e371f8074
[ "BSD-2-Clause" ]
null
null
null
// // x86 architecture description // // Copyright (C) 2002-2007 Peter Johnson // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS'' // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "X86Arch.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "yasmx/Basic/Diagnostic.h" #include "yasmx/Parse/Directive.h" #include "yasmx/Parse/NameValue.h" #include "yasmx/Support/registry.h" #include "yasmx/Bytes.h" #include "yasmx/Bytes_util.h" #include "yasmx/Expr.h" #include "yasmx/IntNum.h" #include "yasmx/Object.h" #include "X86EffAddr.h" #include "X86RegisterGroup.h" using namespace yasm; using namespace yasm::arch; X86Arch::X86Arch(const ArchModule& module) : Arch(module), m_amd64_machine(false), m_parser(PARSER_UNKNOWN), m_mode_bits(0), m_force_strict(false), m_default_rel(false), m_nop(NOP_BASIC) { // default to all instructions/features enabled m_active_cpu.set(); } bool X86Arch::setParser(llvm::StringRef parser) { if (parser.equals_lower("nasm")) m_parser = PARSER_NASM; else if (parser.equals_lower("gas") || parser.equals_lower("gnu")) m_parser = PARSER_GAS; else if (parser.equals_lower("gas-intel") || parser.equals_lower("gnu-intel")) m_parser = PARSER_GAS_INTEL; else return false; return true; } bool X86Arch::setMachine(llvm::StringRef machine) { if (machine.equals_lower("x86")) m_amd64_machine = false; else if (machine.equals_lower("amd64")) m_amd64_machine = true; else return false; return true; } X86Arch::~X86Arch() { } llvm::StringRef X86Arch::getMachine() const { if (m_amd64_machine) return "amd64"; else return "x86"; } ArchModule::MachineNames X86Arch::getMachines() { ArchModule::MachineNames machines; machines.push_back(std::make_pair("x86", "IA-32 and derivatives")); machines.push_back(std::make_pair("amd64", "AMD64")); return machines; } unsigned int X86Arch::getAddressSize() const { if (m_mode_bits != 0) return m_mode_bits; if (m_amd64_machine) return 64; else return 32; } bool X86Arch::setVar(llvm::StringRef var, unsigned long val) { if (var.equals_lower("mode_bits")) { assert((val == 16 || val == 32 || val == 64) && "mode_bits must be 16, 32, or 64"); m_mode_bits = static_cast<unsigned int>(val); } else if (var.equals_lower("force_strict")) m_force_strict = (val != 0); else if (var.equals_lower("default_rel")) { assert((val == 0 || m_mode_bits == 64) && "default_rel requires bits=64"); m_default_rel = (val != 0); } else return false; return true; } void X86Arch::DirCpu(DirectiveInfo& info, Diagnostic& diags) { for (NameValues::const_iterator nv=info.getNameValues().begin(), end=info.getNameValues().end(); nv != end; ++nv) { bool recognized = false; if (nv->isString()) recognized = ParseCpu(nv->getString()); else if (nv->isExpr()) { Expr e = nv->getExpr(info.getObject()); if (e.isIntNum()) { llvm::SmallString<128> ss; llvm::raw_svector_ostream oss(ss); oss << e.getIntNum().getUInt(); recognized = ParseCpu(oss.str()); } } if (!recognized) { diags.Report(info.getSource(), diags.getCustomDiagID(Diagnostic::Warning, "ignored unrecognized CPU identifier")) << nv->getValueRange(); } } } void X86Arch::DirBits(DirectiveInfo& info, Diagnostic& diags) { if (info.getNameValues().size() > 1) diags.Report(info.getSource(), diag::warn_directive_one_arg); NameValue& nv = info.getNameValues().front(); if (nv.isExpr()) { Expr e = nv.getExpr(info.getObject()); if (e.isIntNum()) { unsigned long v = e.getIntNum().getUInt(); if (v == 16 || v == 32 || v == 64) { m_mode_bits = v; return; } } } diags.Report(nv.getValueRange().getBegin(), diags.getCustomDiagID(Diagnostic::Error, "BITS must be 16, 32, or 64")); } void X86Arch::DirCode16(DirectiveInfo& info, Diagnostic& diags) { m_mode_bits = 16; } void X86Arch::DirCode32(DirectiveInfo& info, Diagnostic& diags) { m_mode_bits = 32; } void X86Arch::DirCode64(DirectiveInfo& info, Diagnostic& diags) { m_mode_bits = 64; } void X86Arch::DirDefault(DirectiveInfo& info, Diagnostic& diags) { SourceLocation source = info.getSource(); for (NameValues::const_iterator nv=info.getNameValues().begin(), end=info.getNameValues().end(); nv != end; ++nv) { if (nv->isId()) { llvm::StringRef id = nv->getId(); if (id.equals_lower("rel")) { if (m_mode_bits == 64) m_default_rel = true; else diags.Report(source, diags.getCustomDiagID(Diagnostic::Warning, "ignoring default rel in non-64-bit mode")); } else if (id.equals_lower("abs")) m_default_rel = false; else { diags.Report(source, diags.getCustomDiagID(Diagnostic::Error, "unrecognized default '%0'")) << id; } } else { diags.Report(source, diags.getCustomDiagID(Diagnostic::Error, "unrecognized default value")); } } } const unsigned char ** X86Arch::getFill() const { // Fill patterns that GAS uses. static const unsigned char fill16_1[1] = {0x90}; // 1 - nop static const unsigned char fill16_2[2] = {0x89, 0xf6}; // 2 - mov si, si static const unsigned char fill16_3[3] = {0x8d, 0x74, 0x00}; // 3 - lea si, [si+byte 0] static const unsigned char fill16_4[4] = {0x8d, 0xb4, 0x00, 0x00}; // 4 - lea si, [si+word 0] static const unsigned char fill16_5[5] = {0x90, // 5 - nop 0x8d, 0xb4, 0x00, 0x00}; // lea si, [si+word 0] static const unsigned char fill16_6[6] = {0x89, 0xf6, // 6 - mov si, si 0x8d, 0xbd, 0x00, 0x00}; // lea di, [di+word 0] static const unsigned char fill16_7[7] = {0x8d, 0x74, 0x00, // 7 - lea si, [si+byte 0] 0x8d, 0xbd, 0x00, 0x00}; // lea di, [di+word 0] static const unsigned char fill16_8[8] = {0x8d, 0xb4, 0x00, 0x00, // 8 - lea si, [si+word 0] 0x8d, 0xbd, 0x00, 0x00}; // lea di, [di+word 0] static const unsigned char fill16_9[9] = {0xeb, 0x07, 0x90, 0x90, 0x90, 0x90, // 9 - jmp $+9; nop fill 0x90, 0x90, 0x90}; static const unsigned char fill16_10[10] = {0xeb, 0x08, 0x90, 0x90, 0x90, 0x90, // 10 - jmp $+10; nop fill 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill16_11[11] = {0xeb, 0x09, 0x90, 0x90, 0x90, 0x90, // 11 - jmp $+11; nop fill 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill16_12[12] = {0xeb, 0x0a, 0x90, 0x90, 0x90, 0x90, // 12 - jmp $+12; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill16_13[13] = {0xeb, 0x0b, 0x90, 0x90, 0x90, 0x90, // 13 - jmp $+13; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill16_14[14] = {0xeb, 0x0c, 0x90, 0x90, 0x90, 0x90, // 14 - jmp $+14; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill16_15[15] = {0xeb, 0x0d, 0x90, 0x90, 0x90, 0x90, // 15 - jmp $+15; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char *fill16[16] = { NULL, fill16_1, fill16_2, fill16_3, fill16_4, fill16_5, fill16_6, fill16_7, fill16_8, fill16_9, fill16_10, fill16_11, fill16_12, fill16_13, fill16_14, fill16_15 }; static const unsigned char fill32_1[1] = {0x90}; // 1 - nop static const unsigned char fill32_2[2] = {0x66, 0x90}; // 2 - xchg ax, ax (o16 nop) static const unsigned char fill32_3[3] = {0x8d, 0x76, 0x00}; // 3 - lea esi, [esi+byte 0] static const unsigned char fill32_4[4] = {0x8d, 0x74, 0x26, 0x00}; // 4 - lea esi, [esi*1+byte 0] static const unsigned char fill32_5[5] = {0x90, // 5 - nop 0x8d, 0x74, 0x26, 0x00}; // lea esi, [esi*1+byte 0] static const unsigned char fill32_6[6] = {0x8d, 0xb6, 0x00, 0x00, 0x00, 0x00}; // 6 - lea esi, [esi+dword 0] static const unsigned char fill32_7[7] = {0x8d, 0xb4, 0x26, 0x00, 0x00, 0x00, // 7 - lea esi, [esi*1+dword 0] 0x00}; static const unsigned char fill32_8[8] = {0x90, // 8 - nop 0x8d, 0xb4, 0x26, 0x00, 0x00, 0x00, // lea esi, [esi*1+dword 0] 0x00}; #if 0 // GAS uses these static const unsigned char fill32_9[9] = {0x89, 0xf6, // 9 - mov esi, esi 0x8d, 0xbc, 0x27, 0x00, 0x00, 0x00, // lea edi, [edi*1+dword 0] 0x00}; static const unsigned char fill32_10[10] = {0x8d, 0x76, 0x00, // 10 - lea esi, [esi+byte 0] 0x8d, 0xbc, 0x27, 0x00, 0x00, 0x00, // lea edi, [edi+dword 0] 0x00}; static const unsigned char fill32_11[11] = {0x8d, 0x74, 0x26, 0x00, // 11 - lea esi, [esi*1+byte 0] 0x8d, 0xbc, 0x27, 0x00, 0x00, 0x00, // lea edi, [edi*1+dword 0] 0x00}; static const unsigned char fill32_12[12] = {0x8d, 0xb6, 0x00, 0x00, 0x00, 0x00, // 12 - lea esi, [esi+dword 0] 0x8d, 0xbf, 0x00, 0x00, 0x00, 0x00}; // lea edi, [edi+dword 0] static const unsigned char fill32_13[13] = {0x8d, 0xb6, 0x00, 0x00, 0x00, 0x00, // 13 - lea esi, [esi+dword 0] 0x8d, 0xbc, 0x27, 0x00, 0x00, 0x00, // lea edi, [edi*1+dword 0] 0x00}; static const unsigned char fill32_14[14] = {0x8d, 0xb4, 0x26, 0x00, 0x00, 0x00, // 14 - lea esi, [esi*1+dword 0] 0x00, 0x8d, 0xbc, 0x27, 0x00, 0x00, 0x00, // lea edi, [edi*1+dword 0] 0x00}; #else // But on newer processors, these are recommended static const unsigned char fill32_9[9] = {0xeb, 0x07, 0x90, 0x90, 0x90, 0x90, // 9 - jmp $+9; nop fill 0x90, 0x90, 0x90}; static const unsigned char fill32_10[10] = {0xeb, 0x08, 0x90, 0x90, 0x90, 0x90, // 10 - jmp $+10; nop fill 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill32_11[11] = {0xeb, 0x09, 0x90, 0x90, 0x90, 0x90, // 11 - jmp $+11; nop fill 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill32_12[12] = {0xeb, 0x0a, 0x90, 0x90, 0x90, 0x90, // 12 - jmp $+12; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill32_13[13] = {0xeb, 0x0b, 0x90, 0x90, 0x90, 0x90, // 13 - jmp $+13; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char fill32_14[14] = {0xeb, 0x0c, 0x90, 0x90, 0x90, 0x90, // 14 - jmp $+14; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; #endif static const unsigned char fill32_15[15] = {0xeb, 0x0d, 0x90, 0x90, 0x90, 0x90, // 15 - jmp $+15; nop fill 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; static const unsigned char *fill32[16] = { NULL, fill32_1, fill32_2, fill32_3, fill32_4, fill32_5, fill32_6, fill32_7, fill32_8, fill32_9, fill32_10, fill32_11, fill32_12, fill32_13, fill32_14, fill32_15 }; // Long form nops available on more recent Intel and AMD processors static const unsigned char fill32new_3[3] = // 3 - nop(3) {0x0f, 0x1f, 0x00}; static const unsigned char fill32new_4[4] = // 4 - nop(4) {0x0f, 0x1f, 0x40, 0x00}; static const unsigned char fill32new_5[5] = // 5 - nop(5) {0x0f, 0x1f, 0x44, 0x00, 0x00}; static const unsigned char fill32new_6[6] = // 6 - nop(6) {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00}; static const unsigned char fill32new_7[7] = // 7 - nop(7) {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32new_8[8] = // 8 - nop(8) {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32new_9[9] = // 9 - nop(9) {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; // Longer forms preferred by Intel use repeated o16 prefixes static const unsigned char fill32intel_10[10] = // 10 - o16; cs; nop {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32intel_11[11] = // 11 - 2x o16; cs; nop {0x66, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32intel_12[12] = // 12 - 3x o16; cs; nop {0x66, 0x66, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32intel_13[13] = // 13 - 4x o16; cs; nop {0x66, 0x66, 0x66, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32intel_14[14] = // 14 - 5x o16; cs; nop {0x66, 0x66, 0x66, 0x66, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32intel_15[15] = // 15 - 6x o16; cs; nop {0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; // Longer forms preferred by AMD use fewer o16 prefixes and no CS prefix; // Source: Software Optimisation Guide for AMD Family 10h // Processors 40546 revision 3.10 February 2009 static const unsigned char fill32amd_10[10] = // 10 - nop(10) {0x66, 0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; static const unsigned char fill32amd_11[11] = {0x0f, 0x1f, 0x44, 0x00, 0x00, // 11 - nop(5) 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00}; // nop(6) static const unsigned char fill32amd_12[12] = {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00, // 12 - nop(6) 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00}; // nop(6) static const unsigned char fill32amd_13[13] = {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00, // 13 - nop(6) 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00}; // nop(7) static const unsigned char fill32amd_14[14] = {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00, // 14 - nop(7) 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00}; // nop(7) static const unsigned char fill32amd_15[15] = {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00, // 15 - nop(7) 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}; // nop(8) static const unsigned char *fill32_intel[16] = { NULL, fill32_1, fill32_2, fill32new_3, fill32new_4, fill32new_5, fill32new_6, fill32new_7, fill32new_8, fill32new_9, fill32intel_10, fill32intel_11, fill32intel_12, fill32intel_13, fill32intel_14, fill32intel_15 }; static const unsigned char *fill32_amd[16] = { NULL, fill32_1, fill32_2, fill32new_3, fill32new_4, fill32new_5, fill32new_6, fill32new_7, fill32new_8, fill32new_9, fill32amd_10, fill32amd_11, fill32amd_12, fill32amd_13, fill32amd_14, fill32amd_15 }; switch (m_mode_bits) { case 16: return fill16; case 32: if (m_nop == NOP_INTEL) return fill32_intel; else if (m_nop == NOP_AMD) return fill32_amd; else return fill32; case 64: // We know long nops are available in 64-bit mode; default to Intel // ones if unspecified (to match GAS behavior). if (m_nop == NOP_AMD) return fill32_amd; else return fill32_intel; default: assert(false && "Invalid mode_bits in x86_get_fill"); return 0; } } void X86Arch::AddDirectives(Directives& dirs, llvm::StringRef parser) { static const Directives::Init<X86Arch> nasm_dirs[] = { {"cpu", &X86Arch::DirCpu, Directives::ARG_REQUIRED}, {"bits", &X86Arch::DirBits, Directives::ARG_REQUIRED}, {"default", &X86Arch::DirDefault, Directives::ANY}, }; static const Directives::Init<X86Arch> gas_dirs[] = { {".code16", &X86Arch::DirCode16, Directives::ANY}, {".code32", &X86Arch::DirCode32, Directives::ANY}, {".code64", &X86Arch::DirCode64, Directives::ANY}, }; if (parser.equals_lower("nasm")) dirs.AddArray(this, nasm_dirs); else if (parser.equals_lower("gas") || parser.equals_lower("gnu")) dirs.AddArray(this, gas_dirs); } void X86Arch::setEndian(Bytes& bytes) const { bytes.setLittleEndian(); } std::auto_ptr<EffAddr> X86Arch::CreateEffAddr(std::auto_ptr<Expr> e) const { return std::auto_ptr<EffAddr>(new X86EffAddr(m_parser == PARSER_GAS, e)); } void yasm_arch_x86_DoRegister() { RegisterModule<ArchModule, ArchModuleImpl<X86Arch> >("x86"); }
37.291188
80
0.572742
[ "object" ]
2190d71502069cd6fc9ffe96433b2662debc1916
6,023
hpp
C++
client/definition.hpp
zzccttu/moondb
1f5b919917c4ba98d62b0a85ef5e07f0588ee324
[ "MIT" ]
null
null
null
client/definition.hpp
zzccttu/moondb
1f5b919917c4ba98d62b0a85ef5e07f0588ee324
[ "MIT" ]
null
null
null
client/definition.hpp
zzccttu/moondb
1f5b919917c4ba98d62b0a85ef5e07f0588ee324
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <vector> #include <string> namespace MoonDb { enum FieldType { FT_NONE,// 仅用于标记未识别的字段类型 FT_BOOL, FT_BIT,//n位bit,n从1至128 FT_INT8, FT_UINT8, FT_INT16, FT_UINT16, FT_INT32, FT_UINT32, FT_INT64, FT_UINT64, FT_INT128, FT_UINT128, FT_SERIAL16,//16位整数自增字段 FT_SERIAL32,//32位整数自增字段 FT_SERIAL64,//64位整数自增字段 FT_SERIAL128,//128位整数自增字段 FT_FLOAT32, FT_FLOAT64, FT_FLOAT128, FT_NUMERIC,// 任意精度浮点数,尚未实现 FT_ENUM,//最多65535个选项 FT_DATE,//从-16384-01-01至16383-12-31 3个字节 FT_TIME,//8个字节有符号整数,精度为纳秒 FT_DATETIME,//从-32768-01-01 00:00:00至32767-12-31 23:59:59 9个字节,精度为纳秒 FT_TIMESTAMP,//1901年至2100年,时间截可正可负,用有符号64位整数存取,精度为纳秒 FT_CHAR,//n,长度0-65535 FT_VARCHAR,//n,长度0-65535 FT_BINARY, FT_VARBINARY, FT_TEXT,// 长度占4个字节,不同于mysql长度为2个字节,能够存储4G-1个字节的数据 FT_BLOB,// 二进制数据,其余同FT_TEXT FT_DECIMAL64, FT_DECIMAL128,//用128位有符号整数存储,有效数字的值从-170141183460469231731687303715884105728至170141183460469231731687303715884105727;Scale从-32767至32729,为有效数字乘以10的Scale次方,为0表示整数 FT_SIZE, // 以下为非字段类型 FT_ICONVSTRING = 65534,// 程序内部使用的多字节字符串类型 FT_NULL = 65535,// NULL值 }; const uint16_t FT_STRING = 31; enum OperationType { OPER_NONE, OPER_SELECT, OPER_INSERT, OPER_UPDATE, OPER_DELETE, OPER_REPLACE }; enum IndexType { IT_NONE, IT_ROWID, IT_PRIMARY, IT_UNIQUE, IT_KEY, IT_FULLTEXT }; enum IndexMode { IM_BTREE = 1, IM_HASH }; enum TableType { TT_NONE, TT_FIXMEMORY, /**< 内存表,类似No-SQL的键值存储,键为主键,值为其他数据的集合 */ TT_VARMEMORY, TT_HARDDISK, /**< 存储在硬盘,固定长度的字段存储在主表文件,长度仅递增,不去除已删除的数据;变长度的字段统一存储在附表 */ TT_SIZE }; enum ResponseType{ RT_NONE, RT_ERROR, RT_CONNECT, RT_QUERY, RT_LAST_INSERT_ID, RT_AFFECTED_ROWS, RT_EXECUTE, }; class CDefinition { public: static FieldType StringToFieldType(std::string type) { static std::unordered_map<std::string, FieldType> ftmap; if(!ftmap.size()) { ftmap["BOOL"] = FT_BOOL; ftmap["BOOLEAN"] = FT_BOOL; ftmap["BIT"] = FT_BIT; ftmap["INT8"] = FT_INT8; ftmap["UINT8"] = FT_UINT8; ftmap["TINYINT"] = FT_INT8; ftmap["TINYINT UNSIGNED"] = FT_UINT8; ftmap["INT16"] = FT_INT16; ftmap["UINT16"] = FT_UINT16; ftmap["SMALLINT"] = FT_INT16; ftmap["SMALLINT UNSIGNED"] = FT_UINT16; ftmap["MEDIUMINT"] = FT_INT32; ftmap["MEDIUMINT UNSIGNED"] = FT_UINT32; ftmap["INT"] = FT_INT32; ftmap["INT UNSIGNED"] = FT_UINT32; ftmap["INT32"] = FT_INT32; ftmap["UINT32"] = FT_UINT32; ftmap["INTEGER"] = FT_INT32; ftmap["INT64"] = FT_INT64; ftmap["UINT64"] = FT_UINT64; ftmap["BIGINT"] = FT_INT64; ftmap["BIGINT UNSIGNED"] = FT_UINT64; ftmap["SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT"] = FT_SERIAL16; ftmap["SMALLSERIAL"] = FT_SERIAL16; ftmap["SERIAL16"] = FT_SERIAL16; ftmap["INT UNSIGNED NOT NULL AUTO_INCREMENT"] = FT_SERIAL32; ftmap["SERIAL"] = FT_SERIAL32; ftmap["SERIAL32"] = FT_SERIAL32; ftmap["BIGINT UNSIGNED NOT NULL AUTO_INCREMENT"] = FT_SERIAL64; ftmap["BIGSERIAL"] = FT_SERIAL64; ftmap["SERIAL64"] = FT_SERIAL64; ftmap["FLOAT"] = FT_FLOAT32; ftmap["REAL"] = FT_FLOAT32; ftmap["DOUBLE"] = FT_FLOAT64; ftmap["DOUBLE PRECISION"] = FT_FLOAT64; ftmap["FLOAT32"] = FT_FLOAT32; ftmap["FLOAT64"] = FT_FLOAT64; ftmap["DATE"] = FT_DATE; ftmap["TIME"] = FT_TIME; ftmap["DATETIME"] = FT_DATETIME; ftmap["TIMESTAMP"] = FT_TIMESTAMP; ftmap["YEAR"] = FT_INT32; ftmap["CHAR"] = FT_CHAR; ftmap["CHARACTER"] = FT_CHAR; ftmap["VARCHAR"] = FT_VARCHAR; ftmap["CHARACTER VARYING"] = FT_VARCHAR; ftmap["BINARY"] = FT_BINARY; ftmap["VARBINARY"] = FT_VARBINARY; ftmap["TINYTEXT"] = FT_TEXT; ftmap["TEXT"] = FT_TEXT; ftmap["MEDIUMTEXT"] = FT_TEXT; ftmap["LONGTEXT"] = FT_TEXT; ftmap["TINYBLOB"] = FT_BLOB; ftmap["BLOB"] = FT_BLOB; ftmap["MEDIUMBLOB"] = FT_BLOB; ftmap["LONGBLOB"] = FT_BLOB; ftmap["BYTEA"] = FT_BLOB; ftmap["DECIMAL"] = FT_NUMERIC; ftmap["NUMERIC"] = FT_NUMERIC; ftmap["DECIMAL64"] = FT_DECIMAL64; ftmap["DECIMAL128"] = FT_DECIMAL128; ftmap["ENUM"] = FT_ENUM; // 本数据库中的特殊字段类型 ftmap["INT128"] = FT_INT128; ftmap["UINT128"] = FT_UINT128; ftmap["SERIAL128"] = FT_SERIAL128; ftmap["FLOAT128"] = FT_FLOAT128; } auto it = ftmap.find(type); if(it == ftmap.end()) { return FT_NONE; } return it->second; } static std::string FieldTypeToString(FieldType type) { static std::vector<std::string> fieldtypes; if(fieldtypes.size() == 0) { fieldtypes.resize(FT_SIZE); fieldtypes[FT_NONE] = "NONE"; fieldtypes[FT_BOOL] = "BOOL"; fieldtypes[FT_BIT] = "BIT"; fieldtypes[FT_INT8] = "INT8"; fieldtypes[FT_UINT8] = "UINT8"; fieldtypes[FT_INT16] = "INT16"; fieldtypes[FT_UINT16] = "UINT16"; fieldtypes[FT_INT32] = "INT32"; fieldtypes[FT_UINT32] = "UINT32"; fieldtypes[FT_INT64] = "INT64"; fieldtypes[FT_UINT64] = "UINT64"; fieldtypes[FT_INT128] = "INT128"; fieldtypes[FT_UINT128] = "UINT128"; fieldtypes[FT_SERIAL16] = "SERIAL16"; fieldtypes[FT_SERIAL32] = "SERIAL32"; fieldtypes[FT_SERIAL64] = "SERIAL64"; fieldtypes[FT_SERIAL128] = "SERIAL128"; fieldtypes[FT_FLOAT32] = "FLOAT32"; fieldtypes[FT_FLOAT64] = "FLOAT64"; fieldtypes[FT_FLOAT128] = "FLOAT128"; fieldtypes[FT_NUMERIC] = "NUMERIC"; fieldtypes[FT_ENUM] = "ENUM"; fieldtypes[FT_DATE] = "DATE"; fieldtypes[FT_TIME] = "TIME"; fieldtypes[FT_DATETIME] = "DATETIME"; fieldtypes[FT_TIMESTAMP] = "TIMESTAMP"; fieldtypes[FT_CHAR] = "CHAR"; fieldtypes[FT_VARCHAR] = "VARCHAR"; fieldtypes[FT_BINARY] = "BINARY"; fieldtypes[FT_VARBINARY] = "VARBINARY"; fieldtypes[FT_TEXT] = "TEXT"; fieldtypes[FT_BLOB] = "BLOB"; fieldtypes[FT_DECIMAL64] = "DECIMAL64"; fieldtypes[FT_DECIMAL128] = "DECIMAL128"; } if(type >= FT_SIZE) { return fieldtypes[FT_NONE]; } return fieldtypes[type]; } }; }
27.253394
162
0.66794
[ "vector" ]
219391e4d0e78029de2b406ac057f5f2d8145391
1,323
hpp
C++
reader.hpp
ushitora-anqou/mal
204357eaa01368db2bdbb788833338d3f2fe717e
[ "MIT" ]
null
null
null
reader.hpp
ushitora-anqou/mal
204357eaa01368db2bdbb788833338d3f2fe717e
[ "MIT" ]
null
null
null
reader.hpp
ushitora-anqou/mal
204357eaa01368db2bdbb788833338d3f2fe717e
[ "MIT" ]
null
null
null
#pragma once #ifndef MAL_READER_HPP #define MAL_READER_HPP #include <deque> #include "hoolib.hpp" #include "type.hpp" class Reader { private: std::deque<std::string> tokens_; public: Reader(const std::string& src) { auto re = std::regex( R"([\s,]*(~@|[\[\]{}()'`~^@]|"(?:\\.|[^\\"])*"|[^\s\[\]{}('"`,;)]*)?(?:;.*)?)"); HooLib::search(HOOLIB_RANGE(src), re, [& tokens_ = tokens_](auto&& m) { auto str = m.str(1); if (!str.empty()) tokens_.emplace_back(str); }); } const std::string& peek() const { HOOLIB_THROW_IF(tokens_.empty(), "no next expected token when peek") return tokens_.front(); } std::string pop() { HOOLIB_THROW_IF(tokens_.empty(), "no next expected token when pop") // http://faithandbrave.hateblo.jp/entry/20130604/1370327651 std::string ret(std::move(tokens_.front())); tokens_.pop_front(); return ret; } MalTypePtr parse(); private: std::shared_ptr<MalType> read_atom(); std::shared_ptr<MalList> read_list(); MalTypePtr read_form(); std::vector<MalTypePtr> read_list_items(const std::string& end_token); }; namespace mal { std::shared_ptr<MalString> read_file_all(const std::string& filename); } // namespace mal #endif
24.962264
92
0.588813
[ "vector" ]
21947fdf1c69ff9daa43d4e3ba7b82fcf4711ebf
6,009
cpp
C++
tests/matrice.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
6
2015-10-13T17:07:21.000Z
2018-05-08T11:50:22.000Z
tests/matrice.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
tests/matrice.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include "matrice.h" #include <boost/numeric/ublas/assignment.hpp> #include <boost/rational.hpp> BOOST_AUTO_TEST_SUITE(test_matrice) BOOST_AUTO_TEST_CASE(puissance) { matrice::matrice<long long> A(2, 2); A <<= 1, 1, 1, 0; auto F = matrice::puissance_matrice(A, 40); const std::vector<long long> resultat{165580141, 102334155, 102334155, 63245986}; BOOST_CHECK_EQUAL(F.size1(), 2); BOOST_CHECK_EQUAL(F.size2(), 2); BOOST_CHECK_EQUAL(F(0, 0), 165580141); BOOST_CHECK_EQUAL(F(1, 0), 102334155); BOOST_CHECK_EQUAL(F(0, 1), 102334155); BOOST_CHECK_EQUAL(F(1, 1), 63245986); BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), F.data().begin(), F.data().end()); } BOOST_AUTO_TEST_CASE(puissance_modulaire) { matrice::matrice<long long> A(2, 2); A <<= 1, 1, 1, 0; auto F = matrice::puissance_matrice<long long>(A, 100, 1000000000); const std::vector<long long> resultat{817084101, 261915075, 261915075, 555169026}; BOOST_CHECK_EQUAL(F.size1(), 2); BOOST_CHECK_EQUAL(F.size2(), 2); BOOST_CHECK_EQUAL(F(0, 0), 817084101); BOOST_CHECK_EQUAL(F(1, 0), 261915075); BOOST_CHECK_EQUAL(F(0, 1), 261915075); BOOST_CHECK_EQUAL(F(1, 1), 555169026); BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), F.data().begin(), F.data().end()); } BOOST_AUTO_TEST_CASE(inversion1) { typedef boost::rational<long long> fraction; matrice::matrice<fraction> A(3, 3); A <<= 2, -1, 0, -1, 2, -1, 0, -1, 2; matrice::matrice<fraction> resultat(3, 3); resultat <<= 3, 2, 1, 2, 4, 2, 1, 2, 3; resultat /= 4; matrice::matrice<fraction> inverse(3, 3); bool inversible = matrice::inversionLU(A, inverse); BOOST_CHECK_EQUAL(inversible, true); BOOST_CHECK_EQUAL_COLLECTIONS(resultat.data().begin(), resultat.data().end(), inverse.data().begin(), inverse.data().end()); matrice::matrice<fraction> identite(3, 3); identite <<= 1, 0, 0, 0, 1, 0, 0, 0, 1; matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, inverse); BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(), identite.data().begin(), identite.data().end()); } BOOST_AUTO_TEST_CASE(inversion2) { typedef boost::rational<long long> fraction; matrice::matrice<fraction> A(4, 4); A <<= 1, 1, 1, -1, 1, 2, 6, 7, 1, 2, 9, 0, 2, 5, 9, 15; matrice::matrice<fraction> resultat(4, 4); resultat <<= 99, 132, -44, -55, -18, -129, 29, 59, -7, 14, 7, -7, -3, 17, -8, -3; resultat /= 77; matrice::matrice<fraction> inverse(4, 4); bool inversible = matrice::inversionLU(A, inverse); BOOST_CHECK_EQUAL(inversible, true); BOOST_CHECK_EQUAL_COLLECTIONS(resultat.data().begin(), resultat.data().end(), inverse.data().begin(), inverse.data().end()); matrice::matrice<fraction> identite(4, 4); identite <<= 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1; matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, inverse); BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(), identite.data().begin(), identite.data().end()); } BOOST_AUTO_TEST_CASE(resolution_vecteur) { typedef boost::rational<long long> fraction; matrice::matrice<fraction> A(3, 3); A <<= 1, -1, 2, 3, 2, 1, 2, -3, -2; matrice::vecteur<fraction> b(3); b <<= 5, 10, -10; matrice::vecteur<fraction> resultat(3); resultat <<= 1, 2, 3; matrice::vecteur<fraction> x(3); bool solution = matrice::resolutionLU(A, b, x); BOOST_CHECK_EQUAL(solution, true); BOOST_CHECK_EQUAL_COLLECTIONS(x.data().begin(), x.data().end(), resultat.data().begin(), resultat.data().end()); matrice::vecteur<fraction> produit = boost::numeric::ublas::prod(A, x); BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(), b.data().begin(), b.data().end()); } BOOST_AUTO_TEST_CASE(resolution_matrice) { typedef boost::rational<long long> fraction; matrice::matrice<fraction> A(3, 3); A <<= 1, -1, 2, 3, 2, 1, 2, -3, -2; matrice::matrice<fraction> B(3, 3); B <<= 5, 1, 1, 10, 1, 2, -10, 6, 0; matrice::matrice<fraction> resultat(3, 3); resultat <<= 35, 39, 17, 70, -32, 4, 105, -18, 11; resultat /= 35; matrice::matrice<fraction> X(3, 3); bool solution = matrice::resolutionLU(A, B, X); BOOST_CHECK_EQUAL(solution, true); BOOST_CHECK_EQUAL_COLLECTIONS(X.data().begin(), X.data().end(), resultat.data().begin(), resultat.data().end()); matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, X); BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(), B.data().begin(), B.data().end()); } BOOST_AUTO_TEST_SUITE_END()
33.383333
86
0.514728
[ "vector" ]
2195a66e695e181a7850be7f823b1bc9fd2f9f4f
50,278
cpp
C++
src/vm/wasm/eos-vm/tests/spec/names_tests.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
1
2020-02-27T00:29:05.000Z
2020-02-27T00:29:05.000Z
src/vm/wasm/eos-vm/tests/spec/names_tests.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
null
null
null
src/vm/wasm/eos-vm/tests/spec/names_tests.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
1
2020-10-27T14:25:23.000Z
2020-10-27T14:25:23.000Z
#include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <cmath> #include <cstdlib> #include <catch2/catch.hpp> #include <utils.hpp> #include <wasm_config.hpp> #include <eosio/vm/backend.hpp> using namespace eosio; using namespace eosio::vm; extern wasm_allocator wa; BACKEND_TEST_CASE( "Testing wasm <names_0_wasm>", "[names_0_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "names.0.wasm"); backend_t bkend( code ); bkend.set_wasm_allocator( &wa ); bkend.initialize(nullptr); CHECK(bkend.call_with_return(nullptr, "env", "foo")->to_ui32() == UINT32_C(0)); } BACKEND_TEST_CASE( "Testing wasm <names_1_wasm>", "[names_1_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "names.1.wasm"); backend_t bkend( code ); bkend.set_wasm_allocator( &wa ); bkend.initialize(nullptr); CHECK(bkend.call_with_return(nullptr, "env", "foo")->to_ui32() == UINT32_C(1)); } BACKEND_TEST_CASE( "Testing wasm <names_2_wasm>", "[names_2_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "names.2.wasm"); backend_t bkend( code ); bkend.set_wasm_allocator( &wa ); bkend.initialize(nullptr); CHECK(bkend.call_with_return(nullptr, "env", "")->to_ui32() == UINT32_C(0)); CHECK(bkend.call_with_return(nullptr, "env", "0")->to_ui32() == UINT32_C(1)); CHECK(bkend.call_with_return(nullptr, "env", "-0")->to_ui32() == UINT32_C(2)); CHECK(bkend.call_with_return(nullptr, "env", "_")->to_ui32() == UINT32_C(3)); CHECK(bkend.call_with_return(nullptr, "env", "$")->to_ui32() == UINT32_C(4)); CHECK(bkend.call_with_return(nullptr, "env", "@")->to_ui32() == UINT32_C(5)); CHECK(bkend.call_with_return(nullptr, "env", "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,./ ")->to_ui32() == UINT32_C(6)); CHECK(bkend.call_with_return(nullptr, "env", "NaN")->to_ui32() == UINT32_C(7)); CHECK(bkend.call_with_return(nullptr, "env", "Infinity")->to_ui32() == UINT32_C(8)); CHECK(bkend.call_with_return(nullptr, "env", "if")->to_ui32() == UINT32_C(9)); CHECK(bkend.call_with_return(nullptr, "env", "malloc")->to_ui32() == UINT32_C(10)); CHECK(bkend.call_with_return(nullptr, "env", "_malloc")->to_ui32() == UINT32_C(11)); CHECK(bkend.call_with_return(nullptr, "env", "__malloc")->to_ui32() == UINT32_C(12)); CHECK(bkend.call_with_return(nullptr, "env", "a")->to_ui32() == UINT32_C(13)); CHECK(bkend.call_with_return(nullptr, "env", "A")->to_ui32() == UINT32_C(14)); CHECK(bkend.call_with_return(nullptr, "env", "\357\273\277")->to_ui32() == UINT32_C(15)); CHECK(bkend.call_with_return(nullptr, "env", "\303\205")->to_ui32() == UINT32_C(16)); CHECK(bkend.call_with_return(nullptr, "env", "A\314\212")->to_ui32() == UINT32_C(17)); CHECK(bkend.call_with_return(nullptr, "env", "\342\204\253")->to_ui32() == UINT32_C(18)); CHECK(bkend.call_with_return(nullptr, "env", "\357\254\203")->to_ui32() == UINT32_C(19)); CHECK(bkend.call_with_return(nullptr, "env", "f\357\254\201")->to_ui32() == UINT32_C(20)); CHECK(bkend.call_with_return(nullptr, "env", "ffi")->to_ui32() == UINT32_C(21)); CHECK(bkend.call_with_return(nullptr, "env", std::string("\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017", 16))->to_ui32() == UINT32_C(22)); CHECK(bkend.call_with_return(nullptr, "env", "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037")->to_ui32() == UINT32_C(23)); CHECK(bkend.call_with_return(nullptr, "env", " ")->to_ui32() == UINT32_C(24)); CHECK(bkend.call_with_return(nullptr, "env", "\302\200\302\201\302\202\302\203\302\204\302\205\302\206\302\207\302\210\302\211\302\212\302\213\302\214\302\215\302\216\302\217")->to_ui32() == UINT32_C(25)); CHECK(bkend.call_with_return(nullptr, "env", "\302\220\302\221\302\222\302\223\302\224\302\225\302\226\302\227\302\230\302\231\302\232\302\233\302\234\302\235\302\236\302\237")->to_ui32() == UINT32_C(26)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\260\357\277\261\357\277\262\357\277\263\357\277\264\357\277\265\357\277\266\357\277\267")->to_ui32() == UINT32_C(27)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\270\357\277\271\357\277\272\357\277\273\357\277\274\357\277\275\357\277\276\357\277\277")->to_ui32() == UINT32_C(28)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\200\342\220\201\342\220\202\342\220\203\342\220\204\342\220\205\342\220\206\342\220\207\342\220\210\342\220\211\342\220\212\342\220\213\342\220\214\342\220\215\342\220\216\342\220\217")->to_ui32() == UINT32_C(29)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\220\342\220\221\342\220\222\342\220\223\342\220\224\342\220\225\342\220\226\342\220\227\342\220\230\342\220\231\342\220\232\342\220\233\342\220\234\342\220\235\342\220\236\342\220\237")->to_ui32() == UINT32_C(30)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\240\342\220\241")->to_ui32() == UINT32_C(31)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\260\357\277\261\357\277\262\357\277\263\357\277\264\357\277\265\357\277\266\357\277\267\357\277\270\357\277\271\357\277\272\357\277\273\357\277\274\357\277\275")->to_ui32() == UINT32_C(32)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\215")->to_ui32() == UINT32_C(33)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\214")->to_ui32() == UINT32_C(34)); CHECK(bkend.call_with_return(nullptr, "env", "\315\217")->to_ui32() == UINT32_C(35)); CHECK(bkend.call_with_return(nullptr, "env", "\342\201\240")->to_ui32() == UINT32_C(36)); CHECK(bkend.call_with_return(nullptr, "env", "\342\265\277")->to_ui32() == UINT32_C(37)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\201\277")->to_ui32() == UINT32_C(38)); CHECK(bkend.call_with_return(nullptr, "env", "\341\240\216")->to_ui32() == UINT32_C(39)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\257\342\200\213\302\240\302\255\342\201\240\341\232\200\342\200\256\342\200\255")->to_ui32() == UINT32_C(40)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\216\342\200\217\342\200\221\342\200\250\342\200\251\342\200\252\342\200\253\342\200\254\342\200\257\342\201\246\342\201\247\342\201\250\342\201\251")->to_ui32() == UINT32_C(41)); CHECK(bkend.call_with_return(nullptr, "env", "\342\201\252\342\201\253\342\201\254\342\201\255\342\201\256\342\201\257")->to_ui32() == UINT32_C(42)); CHECK(bkend.call_with_return(nullptr, "env", "\342\201\241\342\201\242\342\201\243\342\201\244")->to_ui32() == UINT32_C(43)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\200\200\363\237\277\277\364\217\277\277")->to_ui32() == UINT32_C(44)); CHECK(bkend.call_with_return(nullptr, "env", "Z\314\217\315\206\314\206\315\233\315\214\314\264\315\230\315\236\315\207\314\253\314\245\314\252\315\223\315\210\315\224\315\216\314\227\314\236\314\272\314\257\314\261\314\236\314\231\314\261\314\234\314\226\314\240a\315\227\315\250\314\216\314\204\314\206\315\227\314\277\315\241\315\237\315\200\314\266\315\201\314\245\314\260\314\263\314\255\315\231\314\262\314\261\314\271\314\235\315\216\314\274l\315\204\315\212\314\232\315\227\315\246\315\204\315\253\314\207\315\201\314\266\314\267\315\211\314\251\314\271\314\253\314\235\315\226\315\205\314\231\314\262\314\274\315\207\315\232\315\215\314\256\315\216\314\245\315\205\314\236g\315\203\314\220\314\205\315\256\314\224\314\220\314\216\314\202\314\217\314\276\315\212\314\215\315\213\315\212\315\247\314\201\314\206\315\246\315\236\314\266\315\225\315\224\315\232\314\251o\315\213\314\224\315\220\315\252\315\251\314\241\315\217\314\242\314\247\315\201\314\253\314\231\314\244\314\256\315\226\315\231\315\223\314\272\314\234\314\251\314\274\314\230\314\240")->to_ui32() == UINT32_C(45)); CHECK(bkend.call_with_return(nullptr, "env", "\341\205\237\341\205\240\343\205\244\357\276\240")->to_ui32() == UINT32_C(46)); CHECK(bkend.call_with_return(nullptr, "env", "\357\270\200")->to_ui32() == UINT32_C(47)); CHECK(bkend.call_with_return(nullptr, "env", "\357\270\204")->to_ui32() == UINT32_C(48)); CHECK(bkend.call_with_return(nullptr, "env", "\363\240\204\200")->to_ui32() == UINT32_C(49)); CHECK(bkend.call_with_return(nullptr, "env", "\363\240\207\257")->to_ui32() == UINT32_C(50)); CHECK(bkend.call_with_return(nullptr, "env", "\314\210")->to_ui32() == UINT32_C(51)); CHECK(bkend.call_with_return(nullptr, "env", "\012")->to_ui32() == UINT32_C(52)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\244")->to_ui32() == UINT32_C(53)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\250")->to_ui32() == UINT32_C(54)); CHECK(bkend.call_with_return(nullptr, "env", "\015")->to_ui32() == UINT32_C(55)); CHECK(bkend.call_with_return(nullptr, "env", "\015\012")->to_ui32() == UINT32_C(56)); CHECK(bkend.call_with_return(nullptr, "env", "\012\015")->to_ui32() == UINT32_C(57)); CHECK(bkend.call_with_return(nullptr, "env", "\036")->to_ui32() == UINT32_C(58)); CHECK(bkend.call_with_return(nullptr, "env", "\013")->to_ui32() == UINT32_C(59)); CHECK(bkend.call_with_return(nullptr, "env", "\014")->to_ui32() == UINT32_C(60)); CHECK(bkend.call_with_return(nullptr, "env", "\302\205")->to_ui32() == UINT32_C(61)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\251")->to_ui32() == UINT32_C(62)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\246")->to_ui32() == UINT32_C(63)); CHECK(bkend.call_with_return(nullptr, "env", "\342\217\216")->to_ui32() == UINT32_C(64)); CHECK(bkend.call_with_return(nullptr, "env", "\302\213")->to_ui32() == UINT32_C(65)); CHECK(bkend.call_with_return(nullptr, "env", "\302\214")->to_ui32() == UINT32_C(66)); CHECK(bkend.call_with_return(nullptr, "env", "\302\215")->to_ui32() == UINT32_C(67)); CHECK(bkend.call_with_return(nullptr, "env", "\342\206\265")->to_ui32() == UINT32_C(68)); CHECK(bkend.call_with_return(nullptr, "env", "\342\206\251")->to_ui32() == UINT32_C(69)); CHECK(bkend.call_with_return(nullptr, "env", "\342\214\244")->to_ui32() == UINT32_C(70)); CHECK(bkend.call_with_return(nullptr, "env", "\342\244\266")->to_ui32() == UINT32_C(71)); CHECK(bkend.call_with_return(nullptr, "env", "\342\206\262")->to_ui32() == UINT32_C(72)); CHECK(bkend.call_with_return(nullptr, "env", "\342\256\250")->to_ui32() == UINT32_C(73)); CHECK(bkend.call_with_return(nullptr, "env", "\342\256\260")->to_ui32() == UINT32_C(74)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\275")->to_ui32() == UINT32_C(75)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\220")->to_ui32() == UINT32_C(76)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\221")->to_ui32() == UINT32_C(77)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\222")->to_ui32() == UINT32_C(78)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\223")->to_ui32() == UINT32_C(79)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\224")->to_ui32() == UINT32_C(80)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\225")->to_ui32() == UINT32_C(81)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\226")->to_ui32() == UINT32_C(82)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\227")->to_ui32() == UINT32_C(83)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\230")->to_ui32() == UINT32_C(84)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\231")->to_ui32() == UINT32_C(85)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\232")->to_ui32() == UINT32_C(86)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\233")->to_ui32() == UINT32_C(87)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\234")->to_ui32() == UINT32_C(88)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\235")->to_ui32() == UINT32_C(89)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\236")->to_ui32() == UINT32_C(90)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\237")->to_ui32() == UINT32_C(91)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\240")->to_ui32() == UINT32_C(92)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\241")->to_ui32() == UINT32_C(93)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\242")->to_ui32() == UINT32_C(94)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\243")->to_ui32() == UINT32_C(95)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\244")->to_ui32() == UINT32_C(96)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\245")->to_ui32() == UINT32_C(97)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\246")->to_ui32() == UINT32_C(98)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\247")->to_ui32() == UINT32_C(99)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\250")->to_ui32() == UINT32_C(100)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\251")->to_ui32() == UINT32_C(101)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\252")->to_ui32() == UINT32_C(102)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\253")->to_ui32() == UINT32_C(103)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\254")->to_ui32() == UINT32_C(104)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\255")->to_ui32() == UINT32_C(105)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\256")->to_ui32() == UINT32_C(106)); CHECK(bkend.call_with_return(nullptr, "env", "\357\267\257")->to_ui32() == UINT32_C(107)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\276")->to_ui32() == UINT32_C(108)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\277")->to_ui32() == UINT32_C(109)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\277\276")->to_ui32() == UINT32_C(110)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\277\277")->to_ui32() == UINT32_C(111)); CHECK(bkend.call_with_return(nullptr, "env", "\360\257\277\276")->to_ui32() == UINT32_C(112)); CHECK(bkend.call_with_return(nullptr, "env", "\360\257\277\277")->to_ui32() == UINT32_C(113)); CHECK(bkend.call_with_return(nullptr, "env", "\360\277\277\276")->to_ui32() == UINT32_C(114)); CHECK(bkend.call_with_return(nullptr, "env", "\360\277\277\277")->to_ui32() == UINT32_C(115)); CHECK(bkend.call_with_return(nullptr, "env", "\361\217\277\276")->to_ui32() == UINT32_C(116)); CHECK(bkend.call_with_return(nullptr, "env", "\361\217\277\277")->to_ui32() == UINT32_C(117)); CHECK(bkend.call_with_return(nullptr, "env", "\361\237\277\276")->to_ui32() == UINT32_C(118)); CHECK(bkend.call_with_return(nullptr, "env", "\361\237\277\277")->to_ui32() == UINT32_C(119)); CHECK(bkend.call_with_return(nullptr, "env", "\361\257\277\276")->to_ui32() == UINT32_C(120)); CHECK(bkend.call_with_return(nullptr, "env", "\361\257\277\277")->to_ui32() == UINT32_C(121)); CHECK(bkend.call_with_return(nullptr, "env", "\361\277\277\276")->to_ui32() == UINT32_C(122)); CHECK(bkend.call_with_return(nullptr, "env", "\361\277\277\277")->to_ui32() == UINT32_C(123)); CHECK(bkend.call_with_return(nullptr, "env", "\362\217\277\276")->to_ui32() == UINT32_C(124)); CHECK(bkend.call_with_return(nullptr, "env", "\362\217\277\277")->to_ui32() == UINT32_C(125)); CHECK(bkend.call_with_return(nullptr, "env", "\362\237\277\276")->to_ui32() == UINT32_C(126)); CHECK(bkend.call_with_return(nullptr, "env", "\362\237\277\277")->to_ui32() == UINT32_C(127)); CHECK(bkend.call_with_return(nullptr, "env", "\362\257\277\276")->to_ui32() == UINT32_C(128)); CHECK(bkend.call_with_return(nullptr, "env", "\362\257\277\277")->to_ui32() == UINT32_C(129)); CHECK(bkend.call_with_return(nullptr, "env", "\362\277\277\276")->to_ui32() == UINT32_C(130)); CHECK(bkend.call_with_return(nullptr, "env", "\362\277\277\277")->to_ui32() == UINT32_C(131)); CHECK(bkend.call_with_return(nullptr, "env", "\363\217\277\276")->to_ui32() == UINT32_C(132)); CHECK(bkend.call_with_return(nullptr, "env", "\363\217\277\277")->to_ui32() == UINT32_C(133)); CHECK(bkend.call_with_return(nullptr, "env", "\363\237\277\276")->to_ui32() == UINT32_C(134)); CHECK(bkend.call_with_return(nullptr, "env", "\363\237\277\277")->to_ui32() == UINT32_C(135)); CHECK(bkend.call_with_return(nullptr, "env", "\363\257\277\276")->to_ui32() == UINT32_C(136)); CHECK(bkend.call_with_return(nullptr, "env", "\363\257\277\277")->to_ui32() == UINT32_C(137)); CHECK(bkend.call_with_return(nullptr, "env", "\363\277\277\276")->to_ui32() == UINT32_C(138)); CHECK(bkend.call_with_return(nullptr, "env", "\363\277\277\277")->to_ui32() == UINT32_C(139)); CHECK(bkend.call_with_return(nullptr, "env", "\364\217\277\276")->to_ui32() == UINT32_C(140)); CHECK(bkend.call_with_return(nullptr, "env", "\364\217\277\277")->to_ui32() == UINT32_C(141)); CHECK(bkend.call_with_return(nullptr, "env", "\314\210\342\200\275\314\210\314\211")->to_ui32() == UINT32_C(142)); CHECK(bkend.call_with_return(nullptr, "env", "abc")->to_ui32() == UINT32_C(143)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\255abc")->to_ui32() == UINT32_C(144)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\256cba")->to_ui32() == UINT32_C(145)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\255abc\342\200\256")->to_ui32() == UINT32_C(146)); CHECK(bkend.call_with_return(nullptr, "env", "\342\200\256cba\342\200\255")->to_ui32() == UINT32_C(147)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\221\250")->to_ui32() == UINT32_C(148)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\220\264")->to_ui32() == UINT32_C(149)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\230\210")->to_ui32() == UINT32_C(150)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\230\274")->to_ui32() == UINT32_C(151)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\220\200")->to_ui32() == UINT32_C(152)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\223\220")->to_ui32() == UINT32_C(153)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\225\254")->to_ui32() == UINT32_C(154)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\227\224")->to_ui32() == UINT32_C(155)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\222\234")->to_ui32() == UINT32_C(156)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\224\204")->to_ui32() == UINT32_C(157)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\224\270")->to_ui32() == UINT32_C(158)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\226\240")->to_ui32() == UINT32_C(159)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\231\260")->to_ui32() == UINT32_C(160)); CHECK(bkend.call_with_return(nullptr, "env", "\341\264\200")->to_ui32() == UINT32_C(161)); CHECK(bkend.call_with_return(nullptr, "env", "\341\264\254")->to_ui32() == UINT32_C(162)); CHECK(bkend.call_with_return(nullptr, "env", "\342\222\266")->to_ui32() == UINT32_C(163)); CHECK(bkend.call_with_return(nullptr, "env", "\357\274\241")->to_ui32() == UINT32_C(164)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\204\220")->to_ui32() == UINT32_C(165)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\204\260")->to_ui32() == UINT32_C(166)); CHECK(bkend.call_with_return(nullptr, "env", "\363\240\201\201")->to_ui32() == UINT32_C(167)); CHECK(bkend.call_with_return(nullptr, "env", "U+0041")->to_ui32() == UINT32_C(168)); CHECK(bkend.call_with_return(nullptr, "env", "A\342\200\213")->to_ui32() == UINT32_C(169)); CHECK(bkend.call_with_return(nullptr, "env", "\320\220")->to_ui32() == UINT32_C(170)); CHECK(bkend.call_with_return(nullptr, "env", "\352\231\226")->to_ui32() == UINT32_C(171)); CHECK(bkend.call_with_return(nullptr, "env", "\342\267\274")->to_ui32() == UINT32_C(172)); CHECK(bkend.call_with_return(nullptr, "env", "\342\267\266")->to_ui32() == UINT32_C(173)); CHECK(bkend.call_with_return(nullptr, "env", "\342\261\257")->to_ui32() == UINT32_C(174)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\205\220")->to_ui32() == UINT32_C(175)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\205\260")->to_ui32() == UINT32_C(176)); CHECK(bkend.call_with_return(nullptr, "env", "\342\260\255")->to_ui32() == UINT32_C(177)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\220\202")->to_ui32() == UINT32_C(178)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\220\210")->to_ui32() == UINT32_C(179)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\222\260")->to_ui32() == UINT32_C(180)); CHECK(bkend.call_with_return(nullptr, "env", "\303\200")->to_ui32() == UINT32_C(181)); CHECK(bkend.call_with_return(nullptr, "env", "\303\201")->to_ui32() == UINT32_C(182)); CHECK(bkend.call_with_return(nullptr, "env", "\303\202")->to_ui32() == UINT32_C(183)); CHECK(bkend.call_with_return(nullptr, "env", "\303\203")->to_ui32() == UINT32_C(184)); CHECK(bkend.call_with_return(nullptr, "env", "\303\204")->to_ui32() == UINT32_C(185)); CHECK(bkend.call_with_return(nullptr, "env", "\304\200")->to_ui32() == UINT32_C(186)); CHECK(bkend.call_with_return(nullptr, "env", "\304\202")->to_ui32() == UINT32_C(187)); CHECK(bkend.call_with_return(nullptr, "env", "\304\204")->to_ui32() == UINT32_C(188)); CHECK(bkend.call_with_return(nullptr, "env", "\307\215")->to_ui32() == UINT32_C(189)); CHECK(bkend.call_with_return(nullptr, "env", "\307\236")->to_ui32() == UINT32_C(190)); CHECK(bkend.call_with_return(nullptr, "env", "\307\240")->to_ui32() == UINT32_C(191)); CHECK(bkend.call_with_return(nullptr, "env", "\307\272")->to_ui32() == UINT32_C(192)); CHECK(bkend.call_with_return(nullptr, "env", "\310\200")->to_ui32() == UINT32_C(193)); CHECK(bkend.call_with_return(nullptr, "env", "\310\202")->to_ui32() == UINT32_C(194)); CHECK(bkend.call_with_return(nullptr, "env", "\310\246")->to_ui32() == UINT32_C(195)); CHECK(bkend.call_with_return(nullptr, "env", "\310\272")->to_ui32() == UINT32_C(196)); CHECK(bkend.call_with_return(nullptr, "env", "\323\220")->to_ui32() == UINT32_C(197)); CHECK(bkend.call_with_return(nullptr, "env", "\323\222")->to_ui32() == UINT32_C(198)); CHECK(bkend.call_with_return(nullptr, "env", "\337\212")->to_ui32() == UINT32_C(199)); CHECK(bkend.call_with_return(nullptr, "env", "\340\240\241")->to_ui32() == UINT32_C(200)); CHECK(bkend.call_with_return(nullptr, "env", "\340\240\242")->to_ui32() == UINT32_C(201)); CHECK(bkend.call_with_return(nullptr, "env", "\340\240\243")->to_ui32() == UINT32_C(202)); CHECK(bkend.call_with_return(nullptr, "env", "\340\240\244")->to_ui32() == UINT32_C(203)); CHECK(bkend.call_with_return(nullptr, "env", "\340\240\245")->to_ui32() == UINT32_C(204)); CHECK(bkend.call_with_return(nullptr, "env", "\340\244\204")->to_ui32() == UINT32_C(205)); CHECK(bkend.call_with_return(nullptr, "env", "\340\244\205")->to_ui32() == UINT32_C(206)); CHECK(bkend.call_with_return(nullptr, "env", "\340\245\262")->to_ui32() == UINT32_C(207)); CHECK(bkend.call_with_return(nullptr, "env", "\340\246\205")->to_ui32() == UINT32_C(208)); CHECK(bkend.call_with_return(nullptr, "env", "\340\250\205")->to_ui32() == UINT32_C(209)); CHECK(bkend.call_with_return(nullptr, "env", "\340\252\205")->to_ui32() == UINT32_C(210)); CHECK(bkend.call_with_return(nullptr, "env", "\340\254\205")->to_ui32() == UINT32_C(211)); CHECK(bkend.call_with_return(nullptr, "env", "\340\256\205")->to_ui32() == UINT32_C(212)); CHECK(bkend.call_with_return(nullptr, "env", "\340\260\205")->to_ui32() == UINT32_C(213)); CHECK(bkend.call_with_return(nullptr, "env", "\340\262\205")->to_ui32() == UINT32_C(214)); CHECK(bkend.call_with_return(nullptr, "env", "\340\264\205")->to_ui32() == UINT32_C(215)); CHECK(bkend.call_with_return(nullptr, "env", "\340\270\260")->to_ui32() == UINT32_C(216)); CHECK(bkend.call_with_return(nullptr, "env", "\340\272\260")->to_ui32() == UINT32_C(217)); CHECK(bkend.call_with_return(nullptr, "env", "\340\274\201")->to_ui32() == UINT32_C(218)); CHECK(bkend.call_with_return(nullptr, "env", "\340\275\250")->to_ui32() == UINT32_C(219)); CHECK(bkend.call_with_return(nullptr, "env", "\340\276\270")->to_ui32() == UINT32_C(220)); CHECK(bkend.call_with_return(nullptr, "env", "\341\200\241")->to_ui32() == UINT32_C(221)); CHECK(bkend.call_with_return(nullptr, "env", "\341\200\242")->to_ui32() == UINT32_C(222)); CHECK(bkend.call_with_return(nullptr, "env", "\341\202\234")->to_ui32() == UINT32_C(223)); CHECK(bkend.call_with_return(nullptr, "env", "\341\205\241")->to_ui32() == UINT32_C(224)); CHECK(bkend.call_with_return(nullptr, "env", "\341\212\240")->to_ui32() == UINT32_C(225)); CHECK(bkend.call_with_return(nullptr, "env", "\341\213\220")->to_ui32() == UINT32_C(226)); CHECK(bkend.call_with_return(nullptr, "env", "\341\216\240")->to_ui32() == UINT32_C(227)); CHECK(bkend.call_with_return(nullptr, "env", "\341\220\212")->to_ui32() == UINT32_C(228)); CHECK(bkend.call_with_return(nullptr, "env", "\341\226\263")->to_ui32() == UINT32_C(229)); CHECK(bkend.call_with_return(nullptr, "env", "\341\232\250")->to_ui32() == UINT32_C(230)); CHECK(bkend.call_with_return(nullptr, "env", "\341\232\252")->to_ui32() == UINT32_C(231)); CHECK(bkend.call_with_return(nullptr, "env", "\341\233\206")->to_ui32() == UINT32_C(232)); CHECK(bkend.call_with_return(nullptr, "env", "\341\234\200")->to_ui32() == UINT32_C(233)); CHECK(bkend.call_with_return(nullptr, "env", "\341\234\240")->to_ui32() == UINT32_C(234)); CHECK(bkend.call_with_return(nullptr, "env", "\341\235\200")->to_ui32() == UINT32_C(235)); CHECK(bkend.call_with_return(nullptr, "env", "\341\235\240")->to_ui32() == UINT32_C(236)); CHECK(bkend.call_with_return(nullptr, "env", "\341\240\240")->to_ui32() == UINT32_C(237)); CHECK(bkend.call_with_return(nullptr, "env", "\341\242\207")->to_ui32() == UINT32_C(238)); CHECK(bkend.call_with_return(nullptr, "env", "\341\244\240")->to_ui32() == UINT32_C(239)); CHECK(bkend.call_with_return(nullptr, "env", "\341\245\243")->to_ui32() == UINT32_C(240)); CHECK(bkend.call_with_return(nullptr, "env", "\341\250\225")->to_ui32() == UINT32_C(241)); CHECK(bkend.call_with_return(nullptr, "env", "\341\251\213")->to_ui32() == UINT32_C(242)); CHECK(bkend.call_with_return(nullptr, "env", "\341\251\241")->to_ui32() == UINT32_C(243)); CHECK(bkend.call_with_return(nullptr, "env", "\341\256\203")->to_ui32() == UINT32_C(244)); CHECK(bkend.call_with_return(nullptr, "env", "\341\257\200")->to_ui32() == UINT32_C(245)); CHECK(bkend.call_with_return(nullptr, "env", "\341\257\201")->to_ui32() == UINT32_C(246)); CHECK(bkend.call_with_return(nullptr, "env", "\341\260\243")->to_ui32() == UINT32_C(247)); CHECK(bkend.call_with_return(nullptr, "env", "\341\270\200")->to_ui32() == UINT32_C(248)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\240")->to_ui32() == UINT32_C(249)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\242")->to_ui32() == UINT32_C(250)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\244")->to_ui32() == UINT32_C(251)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\246")->to_ui32() == UINT32_C(252)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\250")->to_ui32() == UINT32_C(253)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\252")->to_ui32() == UINT32_C(254)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\254")->to_ui32() == UINT32_C(255)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\256")->to_ui32() == UINT32_C(256)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\260")->to_ui32() == UINT32_C(257)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\262")->to_ui32() == UINT32_C(258)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\264")->to_ui32() == UINT32_C(259)); CHECK(bkend.call_with_return(nullptr, "env", "\341\272\266")->to_ui32() == UINT32_C(260)); CHECK(bkend.call_with_return(nullptr, "env", "\343\201\202")->to_ui32() == UINT32_C(261)); CHECK(bkend.call_with_return(nullptr, "env", "\343\202\242")->to_ui32() == UINT32_C(262)); CHECK(bkend.call_with_return(nullptr, "env", "\343\204\232")->to_ui32() == UINT32_C(263)); CHECK(bkend.call_with_return(nullptr, "env", "\343\205\217")->to_ui32() == UINT32_C(264)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\216")->to_ui32() == UINT32_C(265)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\217")->to_ui32() == UINT32_C(266)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\220")->to_ui32() == UINT32_C(267)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\221")->to_ui32() == UINT32_C(268)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\222")->to_ui32() == UINT32_C(269)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\223")->to_ui32() == UINT32_C(270)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\224")->to_ui32() == UINT32_C(271)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\225")->to_ui32() == UINT32_C(272)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\226")->to_ui32() == UINT32_C(273)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\227")->to_ui32() == UINT32_C(274)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\230")->to_ui32() == UINT32_C(275)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\231")->to_ui32() == UINT32_C(276)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\232")->to_ui32() == UINT32_C(277)); CHECK(bkend.call_with_return(nullptr, "env", "\343\210\233")->to_ui32() == UINT32_C(278)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\256")->to_ui32() == UINT32_C(279)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\257")->to_ui32() == UINT32_C(280)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\260")->to_ui32() == UINT32_C(281)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\261")->to_ui32() == UINT32_C(282)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\262")->to_ui32() == UINT32_C(283)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\263")->to_ui32() == UINT32_C(284)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\264")->to_ui32() == UINT32_C(285)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\265")->to_ui32() == UINT32_C(286)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\266")->to_ui32() == UINT32_C(287)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\267")->to_ui32() == UINT32_C(288)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\270")->to_ui32() == UINT32_C(289)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\271")->to_ui32() == UINT32_C(290)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\272")->to_ui32() == UINT32_C(291)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\273")->to_ui32() == UINT32_C(292)); CHECK(bkend.call_with_return(nullptr, "env", "\343\213\220")->to_ui32() == UINT32_C(293)); CHECK(bkend.call_with_return(nullptr, "env", "\352\200\212")->to_ui32() == UINT32_C(294)); CHECK(bkend.call_with_return(nullptr, "env", "\352\223\256")->to_ui32() == UINT32_C(295)); CHECK(bkend.call_with_return(nullptr, "env", "\352\225\211")->to_ui32() == UINT32_C(296)); CHECK(bkend.call_with_return(nullptr, "env", "\352\232\240")->to_ui32() == UINT32_C(297)); CHECK(bkend.call_with_return(nullptr, "env", "\352\240\200")->to_ui32() == UINT32_C(298)); CHECK(bkend.call_with_return(nullptr, "env", "\352\240\243")->to_ui32() == UINT32_C(299)); CHECK(bkend.call_with_return(nullptr, "env", "\352\241\235")->to_ui32() == UINT32_C(300)); CHECK(bkend.call_with_return(nullptr, "env", "\352\242\202")->to_ui32() == UINT32_C(301)); CHECK(bkend.call_with_return(nullptr, "env", "\352\243\252")->to_ui32() == UINT32_C(302)); CHECK(bkend.call_with_return(nullptr, "env", "\352\244\242")->to_ui32() == UINT32_C(303)); CHECK(bkend.call_with_return(nullptr, "env", "\352\245\206")->to_ui32() == UINT32_C(304)); CHECK(bkend.call_with_return(nullptr, "env", "\352\246\204")->to_ui32() == UINT32_C(305)); CHECK(bkend.call_with_return(nullptr, "env", "\352\250\200")->to_ui32() == UINT32_C(306)); CHECK(bkend.call_with_return(nullptr, "env", "\357\275\261")->to_ui32() == UINT32_C(307)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\202")->to_ui32() == UINT32_C(308)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\200\200")->to_ui32() == UINT32_C(309)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\212\200")->to_ui32() == UINT32_C(310)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\212\240")->to_ui32() == UINT32_C(311)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\214\200")->to_ui32() == UINT32_C(312)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\216\240")->to_ui32() == UINT32_C(313)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\222\226")->to_ui32() == UINT32_C(314)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\224\200")->to_ui32() == UINT32_C(315)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\235\200")->to_ui32() == UINT32_C(316)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\240\200")->to_ui32() == UINT32_C(317)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\244\240")->to_ui32() == UINT32_C(318)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\246\200")->to_ui32() == UINT32_C(319)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\246\240")->to_ui32() == UINT32_C(320)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\250\200")->to_ui32() == UINT32_C(321)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\254\200")->to_ui32() == UINT32_C(322)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\260\200")->to_ui32() == UINT32_C(323)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\260\201")->to_ui32() == UINT32_C(324)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\262\200")->to_ui32() == UINT32_C(325)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\200\205")->to_ui32() == UINT32_C(326)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\202\203")->to_ui32() == UINT32_C(327)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\204\247")->to_ui32() == UINT32_C(328)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\205\220")->to_ui32() == UINT32_C(329)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\206\203")->to_ui32() == UINT32_C(330)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\210\200")->to_ui32() == UINT32_C(331)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\212\200")->to_ui32() == UINT32_C(332)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\212\260")->to_ui32() == UINT32_C(333)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\214\205")->to_ui32() == UINT32_C(334)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\215\260")->to_ui32() == UINT32_C(335)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\220\200")->to_ui32() == UINT32_C(336)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\222\201")->to_ui32() == UINT32_C(337)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\226\200")->to_ui32() == UINT32_C(338)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\230\200")->to_ui32() == UINT32_C(339)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\232\200")->to_ui32() == UINT32_C(340)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\234\222")->to_ui32() == UINT32_C(341)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\234\240")->to_ui32() == UINT32_C(342)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\242\241")->to_ui32() == UINT32_C(343)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\253\225")->to_ui32() == UINT32_C(344)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\260\200")->to_ui32() == UINT32_C(345)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\262\217")->to_ui32() == UINT32_C(346)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\262\257")->to_ui32() == UINT32_C(347)); CHECK(bkend.call_with_return(nullptr, "env", "\360\222\200\200")->to_ui32() == UINT32_C(348)); CHECK(bkend.call_with_return(nullptr, "env", "\360\226\247\225")->to_ui32() == UINT32_C(349)); CHECK(bkend.call_with_return(nullptr, "env", "\360\226\251\206")->to_ui32() == UINT32_C(350)); CHECK(bkend.call_with_return(nullptr, "env", "\360\226\253\247")->to_ui32() == UINT32_C(351)); CHECK(bkend.call_with_return(nullptr, "env", "\360\226\275\224")->to_ui32() == UINT32_C(352)); CHECK(bkend.call_with_return(nullptr, "env", "\360\233\261\201")->to_ui32() == UINT32_C(353)); CHECK(bkend.call_with_return(nullptr, "env", "\360\233\261\244")->to_ui32() == UINT32_C(354)); CHECK(bkend.call_with_return(nullptr, "env", "\360\236\240\243")->to_ui32() == UINT32_C(355)); CHECK(bkend.call_with_return(nullptr, "env", "\360\237\207\246")->to_ui32() == UINT32_C(356)); CHECK(bkend.call_with_return(nullptr, "env", "\342\261\255")->to_ui32() == UINT32_C(357)); CHECK(bkend.call_with_return(nullptr, "env", "\316\233")->to_ui32() == UINT32_C(358)); CHECK(bkend.call_with_return(nullptr, "env", "\342\261\260")->to_ui32() == UINT32_C(359)); CHECK(bkend.call_with_return(nullptr, "env", "\302\252")->to_ui32() == UINT32_C(360)); CHECK(bkend.call_with_return(nullptr, "env", "\342\210\200")->to_ui32() == UINT32_C(361)); CHECK(bkend.call_with_return(nullptr, "env", "\342\202\263")->to_ui32() == UINT32_C(362)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\244\200")->to_ui32() == UINT32_C(363)); CHECK(bkend.call_with_return(nullptr, "env", "\342\262\200")->to_ui32() == UINT32_C(364)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\214\260")->to_ui32() == UINT32_C(365)); CHECK(bkend.call_with_return(nullptr, "env", "\316\206")->to_ui32() == UINT32_C(366)); CHECK(bkend.call_with_return(nullptr, "env", "\316\221")->to_ui32() == UINT32_C(367)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\210")->to_ui32() == UINT32_C(368)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\211")->to_ui32() == UINT32_C(369)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\212")->to_ui32() == UINT32_C(370)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\213")->to_ui32() == UINT32_C(371)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\214")->to_ui32() == UINT32_C(372)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\215")->to_ui32() == UINT32_C(373)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\216")->to_ui32() == UINT32_C(374)); CHECK(bkend.call_with_return(nullptr, "env", "\341\274\217")->to_ui32() == UINT32_C(375)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\210")->to_ui32() == UINT32_C(376)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\211")->to_ui32() == UINT32_C(377)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\212")->to_ui32() == UINT32_C(378)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\213")->to_ui32() == UINT32_C(379)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\214")->to_ui32() == UINT32_C(380)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\215")->to_ui32() == UINT32_C(381)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\216")->to_ui32() == UINT32_C(382)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\217")->to_ui32() == UINT32_C(383)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\270")->to_ui32() == UINT32_C(384)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\271")->to_ui32() == UINT32_C(385)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\272")->to_ui32() == UINT32_C(386)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\273")->to_ui32() == UINT32_C(387)); CHECK(bkend.call_with_return(nullptr, "env", "\341\276\274")->to_ui32() == UINT32_C(388)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\232\250")->to_ui32() == UINT32_C(389)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\233\242")->to_ui32() == UINT32_C(390)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\234\234")->to_ui32() == UINT32_C(391)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\235\226")->to_ui32() == UINT32_C(392)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\236\220")->to_ui32() == UINT32_C(393)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\266")->to_ui32() == UINT32_C(394)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\272")->to_ui32() == UINT32_C(395)); CHECK(bkend.call_with_return(nullptr, "env", "\342\251\234")->to_ui32() == UINT32_C(396)); CHECK(bkend.call_with_return(nullptr, "env", "\341\227\205")->to_ui32() == UINT32_C(397)); CHECK(bkend.call_with_return(nullptr, "env", "\341\216\252")->to_ui32() == UINT32_C(398)); CHECK(bkend.call_with_return(nullptr, "env", ")\313\272\313\274\360\224\227\217\360\235\205\264\360\235\205\266\360\235\205\270\360\235\205\272\342\201\276\342\202\216\342\235\251\342\235\253\342\237\257\357\264\277\357\270\266\357\271\232\357\274\211\357\275\240\363\240\200\251\342\235\263\342\235\265\342\237\247\342\237\251\342\237\253\342\237\255\342\246\210\342\246\212\342\246\226\342\270\243\342\270\245\357\270\230\357\270\270\357\270\272\357\270\274\357\270\276\357\271\200\357\271\202\357\271\204\357\271\210\357\271\234\357\271\236\357\274\275\357\275\235\357\275\243\363\240\201\235\363\240\201\275\302\273\342\200\231\342\200\235\342\200\272\342\235\257")->to_ui32() == UINT32_C(399)); CHECK(bkend.call_with_return(nullptr, "env", "(\313\271\313\273\360\224\227\216\360\235\205\263\360\235\205\265\360\235\205\267\360\235\205\271\342\201\275\342\202\215\342\235\250\342\235\252\342\237\256\357\264\276\357\270\265\357\271\231\357\274\210\357\275\237\363\240\200\250\342\235\262\342\235\264\342\237\246\342\237\250\342\237\252\342\237\254\342\246\207\342\246\211\342\246\225\342\270\242\342\270\244\357\270\227\357\270\267\357\270\271\357\270\273\357\270\275\357\270\277\357\271\201\357\271\203\357\271\207\357\271\233\357\271\235\357\274\273\357\275\233\357\275\242\363\240\201\233\363\240\201\273\302\253\342\200\230\342\200\234\342\200\271\342\235\256")->to_ui32() == UINT32_C(400)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\252\213\360\235\252\244")->to_ui32() == UINT32_C(401)); CHECK(bkend.call_with_return(nullptr, "env", "\360\235\252\213")->to_ui32() == UINT32_C(402)); CHECK(bkend.call_with_return(nullptr, "env", "\302\275")->to_ui32() == UINT32_C(403)); CHECK(bkend.call_with_return(nullptr, "env", "1\342\201\2042")->to_ui32() == UINT32_C(404)); CHECK(bkend.call_with_return(nullptr, "env", "1/2")->to_ui32() == UINT32_C(405)); CHECK(bkend.call_with_return(nullptr, "env", "\340\255\263")->to_ui32() == UINT32_C(406)); CHECK(bkend.call_with_return(nullptr, "env", "\340\265\264")->to_ui32() == UINT32_C(407)); CHECK(bkend.call_with_return(nullptr, "env", "\342\263\275")->to_ui32() == UINT32_C(408)); CHECK(bkend.call_with_return(nullptr, "env", "\352\240\261")->to_ui32() == UINT32_C(409)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\205\201")->to_ui32() == UINT32_C(410)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\205\265")->to_ui32() == UINT32_C(411)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\205\266")->to_ui32() == UINT32_C(412)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\246\275")->to_ui32() == UINT32_C(413)); CHECK(bkend.call_with_return(nullptr, "env", "\360\220\271\273")->to_ui32() == UINT32_C(414)); CHECK(bkend.call_with_return(nullptr, "env", "\357\274\202")->to_ui32() == UINT32_C(415)); CHECK(bkend.call_with_return(nullptr, "env", "")->to_ui32() == UINT32_C(416)); CHECK(bkend.call_with_return(nullptr, "env", "\010")->to_ui32() == UINT32_C(417)); CHECK(bkend.call_with_return(nullptr, "env", "\342\214\253")->to_ui32() == UINT32_C(418)); CHECK(bkend.call_with_return(nullptr, "env", "\342\214\246")->to_ui32() == UINT32_C(419)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\210")->to_ui32() == UINT32_C(420)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\241")->to_ui32() == UINT32_C(421)); CHECK(bkend.call_with_return(nullptr, "env", "\341\267\273")->to_ui32() == UINT32_C(422)); CHECK(bkend.call_with_return(nullptr, "env", "\017")->to_ui32() == UINT32_C(423)); CHECK(bkend.call_with_return(nullptr, "env", "\342\206\220")->to_ui32() == UINT32_C(424)); CHECK(bkend.call_with_return(nullptr, "env", "\342\214\247")->to_ui32() == UINT32_C(425)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\222")->to_ui32() == UINT32_C(426)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\224")->to_ui32() == UINT32_C(427)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\242")->to_ui32() == UINT32_C(428)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\253")->to_ui32() == UINT32_C(429)); CHECK(bkend.call_with_return(nullptr, "env", "\032")->to_ui32() == UINT32_C(430)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\246")->to_ui32() == UINT32_C(431)); CHECK(bkend.call_with_return(nullptr, "env", "\342\220\232")->to_ui32() == UINT32_C(432)); CHECK(bkend.call_with_return(nullptr, "env", "\357\277\274")->to_ui32() == UINT32_C(433)); CHECK(bkend.call_with_return(nullptr, "env", "?")->to_ui32() == UINT32_C(434)); CHECK(bkend.call_with_return(nullptr, "env", "\302\277")->to_ui32() == UINT32_C(435)); CHECK(bkend.call_with_return(nullptr, "env", "\341\245\205")->to_ui32() == UINT32_C(436)); CHECK(bkend.call_with_return(nullptr, "env", "\315\276")->to_ui32() == UINT32_C(437)); CHECK(bkend.call_with_return(nullptr, "env", "\325\236")->to_ui32() == UINT32_C(438)); CHECK(bkend.call_with_return(nullptr, "env", "\330\237")->to_ui32() == UINT32_C(439)); CHECK(bkend.call_with_return(nullptr, "env", "\341\215\247")->to_ui32() == UINT32_C(440)); CHECK(bkend.call_with_return(nullptr, "env", "\342\201\207")->to_ui32() == UINT32_C(441)); CHECK(bkend.call_with_return(nullptr, "env", "\342\215\260")->to_ui32() == UINT32_C(442)); CHECK(bkend.call_with_return(nullptr, "env", "\342\235\223")->to_ui32() == UINT32_C(443)); CHECK(bkend.call_with_return(nullptr, "env", "\342\235\224")->to_ui32() == UINT32_C(444)); CHECK(bkend.call_with_return(nullptr, "env", "\342\263\272")->to_ui32() == UINT32_C(445)); CHECK(bkend.call_with_return(nullptr, "env", "\342\263\273")->to_ui32() == UINT32_C(446)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\256")->to_ui32() == UINT32_C(447)); CHECK(bkend.call_with_return(nullptr, "env", "\343\211\204")->to_ui32() == UINT32_C(448)); CHECK(bkend.call_with_return(nullptr, "env", "\352\230\217")->to_ui32() == UINT32_C(449)); CHECK(bkend.call_with_return(nullptr, "env", "\352\233\267")->to_ui32() == UINT32_C(450)); CHECK(bkend.call_with_return(nullptr, "env", "\357\270\226")->to_ui32() == UINT32_C(451)); CHECK(bkend.call_with_return(nullptr, "env", "\357\271\226")->to_ui32() == UINT32_C(452)); CHECK(bkend.call_with_return(nullptr, "env", "\357\274\237")->to_ui32() == UINT32_C(453)); CHECK(bkend.call_with_return(nullptr, "env", "\360\221\205\203")->to_ui32() == UINT32_C(454)); CHECK(bkend.call_with_return(nullptr, "env", "\360\236\245\237")->to_ui32() == UINT32_C(455)); CHECK(bkend.call_with_return(nullptr, "env", "\363\240\200\277")->to_ui32() == UINT32_C(456)); CHECK(bkend.call_with_return(nullptr, "env", "\360\226\241\204")->to_ui32() == UINT32_C(457)); CHECK(bkend.call_with_return(nullptr, "env", "\342\257\221")->to_ui32() == UINT32_C(458)); CHECK(bkend.call_with_return(nullptr, "env", "\302\266")->to_ui32() == UINT32_C(459)); CHECK(bkend.call_with_return(nullptr, "env", "\342\201\213")->to_ui32() == UINT32_C(460)); CHECK(bkend.call_with_return(nullptr, "env", "\334\200")->to_ui32() == UINT32_C(461)); CHECK(bkend.call_with_return(nullptr, "env", "\341\203\273")->to_ui32() == UINT32_C(462)); CHECK(bkend.call_with_return(nullptr, "env", "\341\215\250")->to_ui32() == UINT32_C(463)); CHECK(bkend.call_with_return(nullptr, "env", "\343\200\267")->to_ui32() == UINT32_C(464)); CHECK(bkend.call_with_return(nullptr, "env", "\342\235\241")->to_ui32() == UINT32_C(465)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\217")->to_ui32() == UINT32_C(466)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\220")->to_ui32() == UINT32_C(467)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\221")->to_ui32() == UINT32_C(468)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\216")->to_ui32() == UINT32_C(469)); CHECK(bkend.call_with_return(nullptr, "env", "\024")->to_ui32() == UINT32_C(470)); CHECK(bkend.call_with_return(nullptr, "env", "\342\230\231")->to_ui32() == UINT32_C(471)); CHECK(bkend.call_with_return(nullptr, "env", "\342\270\277")->to_ui32() == UINT32_C(472)); CHECK(bkend.call_with_return(nullptr, "env", "\343\200\207")->to_ui32() == UINT32_C(473)); CHECK(bkend.call_with_return(nullptr, "env", "\340\271\233")->to_ui32() == UINT32_C(474)); CHECK(bkend.call_with_return(nullptr, "env", "\352\231\256")->to_ui32() == UINT32_C(475)); } /* BACKEND_TEST_CASE( "Testing wasm <names_3_wasm>", "[names_3_wasm_tests]" ) { using backend_t = backend<std::nullptr_t, TestType>; auto code = backend_t::read_wasm( std::string(wasm_directory) + "names.3.wasm"); backend_t bkend( code ); bkend.set_wasm_allocator( &wa ); bkend.initialize(nullptr); CHECK(!bkend.call_with_return(nullptr, "env", "print32", UINT32_C(42), UINT32_C(123))); } */
94.507519
1,093
0.676658
[ "vector" ]
2195d3c3f968db17c44a1583263ab69f8c0a8d8c
136,267
cpp
C++
src/cld/Frontend/Compiler/ParserDeclarations.cpp
zero9178/cld
2899ade8045074c5ee939253d2d7f8067c46e72d
[ "MIT" ]
14
2020-10-16T08:29:32.000Z
2021-12-21T10:37:05.000Z
src/cld/Frontend/Compiler/ParserDeclarations.cpp
zero9178/cld
2899ade8045074c5ee939253d2d7f8067c46e72d
[ "MIT" ]
null
null
null
src/cld/Frontend/Compiler/ParserDeclarations.cpp
zero9178/cld
2899ade8045074c5ee939253d2d7f8067c46e72d
[ "MIT" ]
null
null
null
#include "Parser.hpp" #include <cld/Support/ScopeExit.hpp> #include <algorithm> #include <unordered_set> #include "ErrorMessages.hpp" #include "ParserUtil.hpp" #include "SemanticUtil.hpp" #include "Semantics.hpp" using namespace cld::Syntax; namespace { std::vector<DeclarationSpecifier> parseDeclarationSpecifierList(cld::Lexer::CTokenIterator& begin, cld::Lexer::CTokenIterator end, cld::Parser::Context& context) { bool seenTypeSpecifier = false; std::vector<DeclarationSpecifier> declarationSpecifiers; do { auto result = parseDeclarationSpecifier(begin, end, context.withRecoveryTokens(cld::Parser::firstDeclarationSpecifierSet)); if (result) { if (!seenTypeSpecifier && std::holds_alternative<TypeSpecifier>(*result)) { seenTypeSpecifier = true; } declarationSpecifiers.push_back(std::move(*result)); } } while (begin < end && cld::Parser::firstIsInDeclarationSpecifier(*begin, context) && (begin->getTokenType() != cld::Lexer::TokenType::Identifier || !seenTypeSpecifier)); return declarationSpecifiers; } } // namespace std::vector<cld::Syntax::SpecifierQualifier> cld::Parser::parseSpecifierQualifierList(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { bool seenTypeSpecifier = false; std::vector<SpecifierQualifier> specifierQualifiers; do { auto result = parseSpecifierQualifier(begin, end, context.withRecoveryTokens(cld::Parser::firstSpecifierQualifierSet)); if (result) { if (!seenTypeSpecifier && std::holds_alternative<TypeSpecifier>(*result)) { seenTypeSpecifier = true; } specifierQualifiers.push_back(std::move(*result)); } } while (begin < end && firstIsInSpecifierQualifier(*begin, context) && (begin->getTokenType() != Lexer::TokenType::Identifier || !seenTypeSpecifier)); return specifierQualifiers; } TranslationUnit cld::Parser::parseTranslationUnit(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { std::vector<Syntax::ExternalDeclaration> global; #ifdef LLVM_ENABLE_EXCEPTIONS try { #endif while (begin < end) { // I'd love to make this a GNU only extension but MinGW headers have this defect and I don't want to // to switch to gnu99 just to use MinGW begin = std::find_if_not(begin, end, cld::compose(cld::bind_front(std::equal_to<>{}, Lexer::TokenType::SemiColon), &Lexer::CToken::getTokenType)); auto result = parseExternalDeclaration(begin, end, context.withRecoveryTokens(firstExternalDeclarationSet)); if (result) { global.push_back(std::move(*result)); } } #ifdef LLVM_ENABLE_EXCEPTIONS } catch (const FatalParserError&) { } #endif return Syntax::TranslationUnit(std::move(global)); } namespace { // The last parameter being std::optional<std::optional<T>> looks really bad lol // This is because it's optional once due to not having been parsed correctly, and optional due to not having been // specified std::optional<cld::Syntax::Declaration> finishDeclaration( std::vector<cld::Syntax::DeclarationSpecifier>&& declarationSpecifiers, cld::Lexer::CTokenIterator start, cld::Lexer::CTokenIterator& begin, cld::Lexer::CTokenIterator end, cld::Parser::Context& context, std::optional<std::pair<std::optional<Declarator>, std::optional<GNUAttributes>>> alreadyParsedDeclarator = {}) { using namespace cld::Parser; using namespace cld; bool isTypedef = std::any_of(declarationSpecifiers.begin(), declarationSpecifiers.end(), [](const DeclarationSpecifier& declarationSpecifier) { auto* storage = std::get_if<StorageClassSpecifier>(&declarationSpecifier); if (!storage) { return false; } return storage->getSpecifier() == StorageClassSpecifier::Typedef; }); bool declaratorMightActuallyBeTypedef = false; if (begin < end && std::none_of(declarationSpecifiers.begin(), declarationSpecifiers.end(), [](const DeclarationSpecifier& specifier) { return std::holds_alternative<TypeSpecifier>(specifier); }) && begin->getTokenType() == Lexer::TokenType::Identifier && context.isTypedef(begin->getText())) { declaratorMightActuallyBeTypedef = true; } std::vector<cld::Syntax::Declaration::InitDeclarator> initDeclarators; if (alreadyParsedDeclarator) { if (!isTypedef && alreadyParsedDeclarator->first) { const auto* loc = Semantics::declaratorToLoc(*alreadyParsedDeclarator->first); context.addToScope(loc->getText(), {start, begin, loc}); } // GNU Attribute for this case may have already been parsed by the caller if there was no asm statement // but attributes std::optional<GNUSimpleASM> simpleASM; auto attributes = std::move(alreadyParsedDeclarator->second); if (!attributes) { simpleASM = parseGNUSimpleASM(begin, end, context); attributes = parseGNUAttributes(begin, end, context); } if (begin == end || begin->getTokenType() != Lexer::TokenType::Assignment) { if (alreadyParsedDeclarator->first) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*alreadyParsedDeclarator->first)), nullptr, std::move(simpleASM), std::move(attributes)}); } } else { begin++; auto initializer = parseInitializer(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::SemiColon, Lexer::TokenType::Comma))); if (alreadyParsedDeclarator->first && initializer) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*alreadyParsedDeclarator->first)), std::make_unique<Initializer>(std::move(*initializer)), std::move(simpleASM), std::move(attributes)}); } else if (alreadyParsedDeclarator->first) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*alreadyParsedDeclarator->first)), nullptr, std::move(simpleASM), std::move(attributes)}); } } } bool first = !alreadyParsedDeclarator.has_value(); do { std::optional<GNUAttributes> optionalBeforeAttribute; if (first) { first = false; } else if (begin < end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; optionalBeforeAttribute = parseGNUAttributes(begin, end, context); } else { break; } auto declarator = parseDeclarator(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::SemiColon, Lexer::TokenType::Assignment))); if (!isTypedef && declarator) { const auto* loc = Semantics::declaratorToLoc(*declarator); context.addToScope(loc->getText(), {start, begin, loc}); } auto simpleASM = parseGNUSimpleASM(begin, end, context); auto attributes = parseGNUAttributes(begin, end, context); if (begin == end || begin->getTokenType() != Lexer::TokenType::Assignment) { if (declarator) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*declarator)), nullptr, std::move(simpleASM), std::move(attributes), std::move(optionalBeforeAttribute)}); } continue; } begin++; auto initializer = parseInitializer( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::SemiColon, Lexer::TokenType::Comma))); if (declarator && initializer) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*declarator)), std::make_unique<Initializer>(std::move(*initializer)), std::move(simpleASM), std::move(attributes), std::move(optionalBeforeAttribute)}); } else if (declarator) { initDeclarators.push_back({std::make_unique<Declarator>(std::move(*declarator)), nullptr, std::move(simpleASM), std::move(attributes), std::move(optionalBeforeAttribute)}); } } while (true); if (declaratorMightActuallyBeTypedef && initDeclarators.size() == 1) { auto* loc = context.getLocationOf(Semantics::declaratorToLoc(*initDeclarators[0].declarator)->getText()); if (loc) { if (!expect(Lexer::TokenType::SemiColon, begin, end, context, [&] { return Notes::TYPEDEF_OVERSHADOWED_BY_DECLARATION.args( *loc->identifier, context.getSourceInterface(), *loc->identifier); })) { context.skipUntil(begin, end); return {}; } } else { if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); return {}; } } } else { if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); return {}; } } if (isTypedef) { for (auto& iter : initDeclarators) { const auto* loc = Semantics::declaratorToLoc(*iter.declarator); context.addTypedef(loc->getText(), {start, begin, loc}); } } return Declaration(start, begin, std::move(declarationSpecifiers), std::move(initDeclarators)); } } // namespace std::optional<cld::Syntax::ExternalDeclaration> cld::Parser::parseExternalDeclaration(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; begin = std::find_if_not( begin, end, [](const Lexer::CToken& token) { return token.getTokenType() == Lexer::TokenType::GNUExtension; }); auto extensionReset = context.enableExtensions(start != begin); if (begin != end && begin->getTokenType() == Lexer::TokenType::GNUASM) { auto result = parseGNUSimpleASM(begin, end, context); expect(Lexer::TokenType::SemiColon, begin, end, context); if (result) { return {std::move(*result)}; } return {}; } auto declarationSpecifiers = parseDeclarationSpecifierList( begin, end, context.withRecoveryTokens(firstDeclaratorSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon))); if (begin == end || begin->getTokenType() == Lexer::TokenType::SemiColon) { expect(Lexer::TokenType::SemiColon, begin, end, context); return Declaration(start, begin, std::move(declarationSpecifiers), {}); } auto declarator = parseDeclarator( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::Comma, Lexer::TokenType::SemiColon, Lexer::TokenType::OpenBrace, Lexer::TokenType::Assignment))); if (begin == end) { expect(Lexer::TokenType::SemiColon, begin, end, context); return {}; } auto attributes = parseGNUAttributes(begin, end, context); if (begin != end && (begin->getTokenType() == Lexer::TokenType::OpenBrace || firstIsInDeclaration(*begin, context))) { std::vector<Declaration> declarations; while (begin < end && firstIsInDeclaration(*begin, context)) { auto result = parseDeclaration( begin, end, context.withRecoveryTokens(firstDeclarationSet | Context::fromTokenTypes(Lexer::TokenType::OpenBrace))); if (result) { declarations.push_back(std::move(*result)); } } context.pushScope(); if (!declarator) { parseCompoundStatement(begin, end, context, false); context.popScope(); return {}; } const DirectDeclaratorParenthesesParameters* parameters = nullptr; const DirectDeclaratorParenthesesIdentifiers* identifierList = nullptr; for (auto& iter : Semantics::RecursiveVisitor(declarator->getDirectDeclarator(), Semantics::DIRECT_DECL_NEXT_FN)) { cld::match( iter, [&](const DirectDeclaratorParenthesesParameters& dd) { parameters = &dd; identifierList = nullptr; }, [&](const DirectDeclaratorParenthesesIdentifiers& dd) { parameters = nullptr; identifierList = &dd; }, [](const DirectDeclaratorIdentifier&) {}, [&](const DirectDeclaratorParentheses& parentheses) { if (!parentheses.getDeclarator().getPointers().empty()) { parameters = nullptr; identifierList = nullptr; } }, [&](const auto&) { parameters = nullptr; identifierList = nullptr; }); } if (identifierList) { for (auto& iter : identifierList->getIdentifiers()) { context.addToScope(iter->getText(), {start, begin, iter}); } } else if (parameters) { auto& parameterDeclarations = parameters->getParameterTypeList().getParameters(); std::unordered_set<std::string_view> addedByParameters; for (auto& iter : parameterDeclarations) { if (parameterDeclarations.size() == 1 && iter.declarationSpecifiers.size() == 1 && std::holds_alternative<TypeSpecifier>(iter.declarationSpecifiers[0])) { auto* primitive = std::get_if<TypeSpecifier::PrimitiveTypeSpecifier>( &cld::get<TypeSpecifier>(iter.declarationSpecifiers[0]).getVariant()); if (primitive && *primitive == TypeSpecifier::PrimitiveTypeSpecifier::Void) { break; } } // // Any parameters that overshadow typedefs need to also affect later parameters // for (auto& specifier : iter.declarationSpecifiers) { auto* typeSpecifier = std::get_if<TypeSpecifier>(&specifier); if (!typeSpecifier) { continue; } auto* identifier = std::get_if<std::string_view>(&typeSpecifier->getVariant()); if (!identifier) { continue; } if (addedByParameters.count(*identifier)) { auto* loc = context.getLocationOf(*identifier); context.log(Errors::Parser::EXPECTED_TYPENAME_INSTEAD_OF_N.args( *typeSpecifier->begin(), context.getSourceInterface(), *typeSpecifier->begin())); if (loc) { context.log(Notes::TYPEDEF_OVERSHADOWED_BY_DECLARATION.args( *loc->identifier, context.getSourceInterface(), *loc->identifier)); } } } if (std::holds_alternative<std::unique_ptr<AbstractDeclarator>>(iter.declarator)) { if (iter.declarationSpecifiers.empty()) { continue; } context.log(Errors::Parser::MISSING_PARAMETER_NAME.args(iter, context.getSourceInterface(), iter)); if (iter.declarationSpecifiers.size() == 1 && std::holds_alternative<TypeSpecifier>(iter.declarationSpecifiers[0]) && std::holds_alternative<std::string_view>( cld::get<TypeSpecifier>(iter.declarationSpecifiers[0]).getVariant())) { auto& typeSpecifier = cld::get<TypeSpecifier>(iter.declarationSpecifiers[0]); auto name = cld::get<std::string_view>(typeSpecifier.getVariant()); auto* loc = context.getLocationOf(name); if (loc) { context.log(Notes::IDENTIFIER_IS_TYPEDEF.args( *loc->identifier, context.getSourceInterface(), *loc->identifier)); } } continue; } auto& decl = cld::get<std::unique_ptr<Declarator>>(iter.declarator); const auto* loc = Semantics::declaratorToLoc(*decl); context.addToScope(loc->getText(), {start, begin, loc}); addedByParameters.insert(loc->getText()); } } auto compoundStatement = parseCompoundStatement(begin, end, context, false); context.popScope(); if (!declarator || !compoundStatement) { return {}; } context.addToScope(Semantics::declaratorToLoc(*declarator)->getText(), {start, compoundStatement->begin(), Semantics::declaratorToLoc(*declarator)}); return FunctionDefinition(start, begin, std::move(declarationSpecifiers), std::move(*declarator), std::move(attributes), std::move(declarations), std::move(*compoundStatement)); } return finishDeclaration(std::move(declarationSpecifiers), start, begin, end, context, std::optional<std::pair<std::optional<Declarator>, std::optional<GNUAttributes>>>{ std::in_place, std::move(declarator), std::move(attributes)}); } std::optional<cld::Syntax::Declaration> cld::Parser::parseDeclaration(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; auto declarationSpecifiers = parseDeclarationSpecifierList( begin, end, context.withRecoveryTokens(firstDeclaratorSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon))); if (begin == end || begin->getTokenType() == Lexer::TokenType::SemiColon) { expect(Lexer::TokenType::SemiColon, begin, end, context); return Declaration(start, begin, std::move(declarationSpecifiers), {}); } return finishDeclaration(std::move(declarationSpecifiers), start, begin, end, context); } std::optional<cld::Syntax::DeclarationSpecifier> cld::Parser::parseDeclarationSpecifier(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (begin < end) { auto currToken = *begin; switch (begin->getTokenType()) { case Lexer::TokenType::TypedefKeyword: case Lexer::TokenType::ExternKeyword: case Lexer::TokenType::StaticKeyword: case Lexer::TokenType::AutoKeyword: case Lexer::TokenType::RegisterKeyword: case Lexer::TokenType::ConstKeyword: case Lexer::TokenType::RestrictKeyword: case Lexer::TokenType::VolatileKeyword: case Lexer::TokenType::InlineKeyword: case Lexer::TokenType::VoidKeyword: case Lexer::TokenType::CharKeyword: case Lexer::TokenType::ShortKeyword: case Lexer::TokenType::IntKeyword: case Lexer::TokenType::Int128Keyword: case Lexer::TokenType::UnderlineBool: case Lexer::TokenType::LongKeyword: case Lexer::TokenType::FloatKeyword: case Lexer::TokenType::DoubleKeyword: case Lexer::TokenType::SignedKeyword: case Lexer::TokenType::UnsignedKeyword: begin++; default: break; } switch (currToken.getTokenType()) { case Lexer::TokenType::TypedefKeyword: return DeclarationSpecifier{StorageClassSpecifier(start, start + 1, StorageClassSpecifier::Typedef)}; case Lexer::TokenType::ExternKeyword: return DeclarationSpecifier{StorageClassSpecifier(start, start + 1, StorageClassSpecifier::Extern)}; case Lexer::TokenType::StaticKeyword: return DeclarationSpecifier{StorageClassSpecifier(start, start + 1, StorageClassSpecifier::Static)}; case Lexer::TokenType::AutoKeyword: return DeclarationSpecifier{StorageClassSpecifier(start, start + 1, StorageClassSpecifier::Auto)}; case Lexer::TokenType::RegisterKeyword: return DeclarationSpecifier{StorageClassSpecifier(start, start + 1, StorageClassSpecifier::Register)}; case Lexer::TokenType::ConstKeyword: return DeclarationSpecifier{TypeQualifier(start, start + 1, TypeQualifier::Const)}; case Lexer::TokenType::RestrictKeyword: return DeclarationSpecifier{TypeQualifier(start, start + 1, TypeQualifier::Restrict)}; case Lexer::TokenType::VolatileKeyword: return DeclarationSpecifier{TypeQualifier(start, start + 1, TypeQualifier::Volatile)}; case Lexer::TokenType::InlineKeyword: return DeclarationSpecifier{FunctionSpecifier{start, start + 1}}; case Lexer::TokenType::VoidKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Void)}; case Lexer::TokenType::CharKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Char)}; case Lexer::TokenType::ShortKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Short)}; case Lexer::TokenType::IntKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Int)}; case Lexer::TokenType::LongKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Long)}; case Lexer::TokenType::FloatKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Float)}; case Lexer::TokenType::DoubleKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Double)}; case Lexer::TokenType::UnderlineBool: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Bool)}; case Lexer::TokenType::SignedKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Signed)}; case Lexer::TokenType::UnsignedKeyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Unsigned)}; case Lexer::TokenType::Int128Keyword: return Syntax::DeclarationSpecifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Int128)}; case Lexer::TokenType::UnionKeyword: case Lexer::TokenType::StructKeyword: case Lexer::TokenType::GNUExtension: { auto expected = parseStructOrUnionSpecifier(begin, end, context); if (!expected) { context.skipUntil(begin, end); return {}; } return DeclarationSpecifier{TypeSpecifier( start, begin, std::make_unique<Syntax::StructOrUnionSpecifier>(std::move(*expected)))}; } case Lexer::TokenType::EnumKeyword: { auto expected = parseEnumSpecifier(begin, end, context); if (!expected) { context.skipUntil(begin, end); return {}; } return DeclarationSpecifier{ TypeSpecifier(start, begin, std::make_unique<EnumSpecifier>(std::move(*expected)))}; } case Lexer::TokenType::Identifier: { auto name = begin->getText(); if (context.isTypedefInScope(name) || context.isBuiltin(name)) { return Syntax::DeclarationSpecifier{TypeSpecifier(start, ++begin, name)}; } break; } case Lexer::TokenType::GNUAttribute: { auto option = parseGNUAttributes(begin, end, context); if (option) { return Syntax::DeclarationSpecifier{std::move(*option)}; } return {}; } default: break; } } if (begin != end) { context.log(Errors::Parser::EXPECTED_STORAGE_SPECIFIER_OR_TYPENAME_BEFORE_N.args( *begin, context.getSourceInterface(), *begin)); } else { context.log(Errors::Parser::EXPECTED_STORAGE_SPECIFIER_OR_TYPENAME.args( diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); } context.skipUntil(begin, end); return {}; } std::optional<cld::Syntax::StructOrUnionSpecifier> cld::Parser::parseStructOrUnionSpecifier(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { CLD_ASSERT(begin != end); const auto* start = begin; const auto* temp = begin; begin = std::find_if_not( begin, end, cld::compose(cld::bind_front(std::equal_to<>{}, Lexer::TokenType::GNUExtension), &Lexer::CToken::getTokenType)); bool hadExtension = temp != begin; auto extensionReset = context.enableExtensions(hadExtension); bool isUnion; if (begin != end && begin->getTokenType() == Lexer::TokenType::StructKeyword) { begin++; isUnion = false; } else if (begin != end && begin->getTokenType() == Lexer::TokenType::UnionKeyword) { begin++; isUnion = true; } else { if (begin != end) { context.log(Errors::Parser::EXPECTED_N_OR_N_INSTEAD_OF_N.args(*begin, context.getSourceInterface(), Lexer::TokenType::StructKeyword, Lexer::TokenType::UnionKeyword, *begin)); context.skipUntil(begin, end); return {}; } context.log(Errors::Parser::EXPECTED_N_OR_N.args(*start, context.getSourceInterface(), Lexer::TokenType::StructKeyword, Lexer::TokenType::UnionKeyword, *start)); return {}; } auto beforeAttributes = parseGNUAttributes(begin, end, context); if (begin == end) { context.log(Errors::Parser::EXPECTED_N_OR_N_AFTER_N.args( diag::after(*(begin - 1)), context.getSourceInterface(), Lexer::TokenType::Identifier, Lexer::TokenType::OpenBrace, *(begin - 1))); return {}; } const auto* name = begin->getTokenType() == Lexer::TokenType::Identifier ? begin : nullptr; if (name) { begin++; } // __extension__ only allowed for struct definitions, not declarations if ((begin == end || begin->getTokenType() != Lexer::TokenType::OpenBrace) && !hadExtension) { if (!name) { expect(Lexer::TokenType::Identifier, begin, end, context); context.skipUntil(begin, end); return {}; } return StructOrUnionSpecifier(start, begin, isUnion, std::move(beforeAttributes), name, {}, {}, context.extensionsEnabled(start)); } const Lexer::CToken* openBrace = nullptr; if (expect(Lexer::TokenType::OpenBrace, begin, end, context)) { openBrace = begin - 1; } std::vector<StructOrUnionSpecifier::StructDeclaration> structDeclarations; while (begin < end && (firstIsInSpecifierQualifier(*begin, context) || begin->getTokenType() == Lexer::TokenType::Identifier || begin->getTokenType() == Lexer::TokenType::GNUExtension)) { std::optional<ValueReset<bool>> extensionReset2; if (begin->getTokenType() == Lexer::TokenType::GNUExtension) { extensionReset2.emplace(context.enableExtensions(true)); begin++; } auto specifierQualifiers = parseSpecifierQualifierList( begin, end, context.withRecoveryTokens(firstDeclaratorSet | Context::fromTokenTypes(Lexer::TokenType::Colon))); std::vector<StructOrUnionSpecifier::StructDeclaration::StructDeclarator> declarators; if (begin < end && (firstIsInDeclarator(*begin, context) || begin->getTokenType() == Lexer::TokenType::Colon)) { bool first = true; do { std::optional<GNUAttributes> beforeDeclAttributes; if (first) { first = false; } else if (begin < end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; beforeDeclAttributes = parseGNUAttributes(begin, end, context); } else { break; } if (begin < end && begin->getTokenType() == Lexer::TokenType::Colon) { begin++; auto constant = parseConditionalExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::SemiColon))); auto afterAttributes = parseGNUAttributes(begin, end, context); declarators.push_back( {std::move(beforeDeclAttributes), nullptr, std::move(constant), std::move(afterAttributes)}); continue; } auto declarator = parseDeclarator( begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::SemiColon, Lexer::TokenType::Colon))); if (begin < end && begin->getTokenType() == Lexer::TokenType::Colon) { begin++; auto constant = parseConditionalExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::SemiColon))); auto afterAttributes = parseGNUAttributes(begin, end, context); if (declarator) { declarators.push_back({std::move(beforeDeclAttributes), std::make_unique<Declarator>(std::move(*declarator)), std::move(constant), std::move(afterAttributes)}); } } else { auto afterAttributes = parseGNUAttributes(begin, end, context); if (declarator) { declarators.push_back({std::move(beforeDeclAttributes), std::make_unique<Declarator>(std::move(*declarator)), std::nullopt, std::move(afterAttributes)}); } } } while (true); } if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end, firstDeclarationSpecifierSet | Context::fromTokenTypes(Lexer::TokenType::CloseBrace)); } structDeclarations.push_back({std::move(specifierQualifiers), std::move(declarators)}); } if (openBrace) { if (!expect(Lexer::TokenType::CloseBrace, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openBrace, context.getSourceInterface(), *openBrace); })) { context.skipUntil(begin, end); } } else { if (!expect(Lexer::TokenType::CloseBrace, begin, end, context)) { context.skipUntil(begin, end); } } if (structDeclarations.empty()) { if (isUnion) { context.log(Errors::Parser::UNION_REQUIRES_AT_LEAST_ONE_FIELD.args( *start, context.getSourceInterface(), std::forward_as_tuple(*start, *(begin - 1)))); } else { context.log(Errors::Parser::STRUCT_REQUIRES_AT_LEAST_ONE_FIELD.args( *start, context.getSourceInterface(), std::forward_as_tuple(*start, *(begin - 1)))); } } auto afterAttributes = parseGNUAttributes(begin, end, context); return StructOrUnionSpecifier(start, begin, isUnion, std::move(beforeAttributes), name, std::move(structDeclarations), std::move(afterAttributes), context.extensionsEnabled(start)); } std::optional<cld::Syntax::SpecifierQualifier> cld::Parser::parseSpecifierQualifier(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (begin < end) { auto currToken = *begin; switch (currToken.getTokenType()) { case Lexer::TokenType::ConstKeyword: case Lexer::TokenType::RestrictKeyword: case Lexer::TokenType::VolatileKeyword: case Lexer::TokenType::VoidKeyword: case Lexer::TokenType::CharKeyword: case Lexer::TokenType::ShortKeyword: case Lexer::TokenType::IntKeyword: case Lexer::TokenType::Int128Keyword: case Lexer::TokenType::LongKeyword: case Lexer::TokenType::FloatKeyword: case Lexer::TokenType::UnderlineBool: case Lexer::TokenType::DoubleKeyword: case Lexer::TokenType::SignedKeyword: case Lexer::TokenType::UnsignedKeyword: begin++; default: break; } switch (currToken.getTokenType()) { case Lexer::TokenType::ConstKeyword: return SpecifierQualifier{TypeQualifier(start, start + 1, TypeQualifier::Const)}; case Lexer::TokenType::RestrictKeyword: return SpecifierQualifier{TypeQualifier(start, start + 1, TypeQualifier::Restrict)}; case Lexer::TokenType::VolatileKeyword: return SpecifierQualifier{TypeQualifier(start, start + 1, TypeQualifier::Volatile)}; case Lexer::TokenType::VoidKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Void)}; case Lexer::TokenType::CharKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Char)}; case Lexer::TokenType::ShortKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Short)}; case Lexer::TokenType::IntKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Int)}; case Lexer::TokenType::LongKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Long)}; case Lexer::TokenType::FloatKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Float)}; case Lexer::TokenType::UnderlineBool: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Bool)}; case Lexer::TokenType::DoubleKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Double)}; case Lexer::TokenType::SignedKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Signed)}; case Lexer::TokenType::UnsignedKeyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Unsigned)}; case Lexer::TokenType::Int128Keyword: return Syntax::SpecifierQualifier{ TypeSpecifier(start, begin, TypeSpecifier::PrimitiveTypeSpecifier::Int128)}; case Lexer::TokenType::UnionKeyword: case Lexer::TokenType::StructKeyword: case Lexer::TokenType::GNUExtension: { auto expected = parseStructOrUnionSpecifier(begin, end, context); if (!expected) { context.skipUntil(begin, end); return {}; } return SpecifierQualifier{TypeSpecifier( start, begin, std::make_unique<Syntax::StructOrUnionSpecifier>(std::move(*expected)))}; } case Lexer::TokenType::EnumKeyword: { auto expected = parseEnumSpecifier(begin, end, context); if (!expected) { context.skipUntil(begin, end); return {}; } return SpecifierQualifier{ TypeSpecifier(start, begin, std::make_unique<EnumSpecifier>(std::move(*expected)))}; } case Lexer::TokenType::Identifier: { auto name = begin->getText(); if (context.isTypedefInScope(name) || context.isBuiltin(name)) { return Syntax::SpecifierQualifier{TypeSpecifier(start, ++begin, name)}; } if (context.isTypedef(name)) { auto* loc = context.getLocationOf(begin->getText()); CLD_ASSERT(loc); context.log(Errors::Parser::EXPECTED_TYPENAME_INSTEAD_OF_N.args( *begin, context.getSourceInterface(), *begin)); context.log(Notes::TYPEDEF_OVERSHADOWED_BY_DECLARATION.args( *loc->identifier, context.getSourceInterface(), *loc->identifier)); context.skipUntil(begin, end); return {}; } break; } case Lexer::TokenType::GNUAttribute: { auto option = parseGNUAttributes(begin, end, context); if (option) { return Syntax::SpecifierQualifier{std::move(*option)}; } return {}; } default: break; } } if (begin < end) { context.log(Errors::Parser::EXPECTED_TYPENAME_BEFORE_N.args(*begin, context.getSourceInterface(), *begin)); } else { context.log(Errors::Parser::EXPECTED_TYPENAME.args(diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); } context.skipUntil(begin, end); return {}; } std::optional<cld::Syntax::Declarator> cld::Parser::parseDeclarator(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; std::vector<Syntax::Pointer> pointers; while (begin < end && begin->getTokenType() == Lexer::TokenType::Asterisk) { auto result = parsePointer(begin, end, context.withRecoveryTokens(firstDeclaratorSet)); pointers.push_back(std::move(result)); } auto directDeclarator = parseDirectDeclarator(begin, end, context); if (!directDeclarator) { return {}; } return Declarator(start, begin, std::move(pointers), std::move(*directDeclarator)); } namespace { std::optional<cld::Syntax::DirectDeclarator> parseDirectDeclaratorSuffix(cld::Lexer::CTokenIterator& begin, cld::Lexer::CTokenIterator end, cld::Parser::Context& context, std::unique_ptr<DirectDeclarator>&& directDeclarator) { using namespace cld; using namespace cld::Parser; const auto* start = directDeclarator ? cld::match(*directDeclarator, [](auto&& value) { return value.begin(); }) : begin; while (begin < end && (begin->getTokenType() == Lexer::TokenType::OpenParentheses || begin->getTokenType() == Lexer::TokenType::OpenSquareBracket)) { switch (begin->getTokenType()) { case Lexer::TokenType::OpenParentheses: { auto scope = context.parenthesesEntered(begin); const auto* openPpos = begin; auto checkForClose = std::optional{cld::ScopeExit( [&] { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } })}; begin++; if (begin < end && firstIsInParameterTypeList(*begin, context)) { auto parameterTypeList = parseParameterTypeList( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); checkForClose.reset(); if (directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorParenthesesParameters( start, begin, std::move(*directDeclarator), std::move(parameterTypeList))); } break; } if (begin == end) { break; } std::vector<Lexer::CTokenIterator> identifiers; if (begin->getTokenType() == Lexer::TokenType::Identifier) { identifiers.push_back(begin); begin++; while (begin < end && (begin->getTokenType() == Lexer::TokenType::Comma || begin->getTokenType() == Lexer::TokenType::Identifier)) { if (!expect(Lexer::TokenType::Comma, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Identifier, Lexer::TokenType::CloseParentheses)); } std::string_view name; if (!expectIdentifier(begin, end, context, name)) { context.skipUntil( begin, end, Context::fromTokenTypes(Lexer::TokenType::Comma, Lexer::TokenType::CloseParentheses)); continue; } if (!context.isTypedef(name)) { identifiers.push_back(begin - 1); continue; } context.log(Errors::Parser::EXPECTED_N_INSTEAD_OF_TYPENAME.args( *(begin - 1), context.getSourceInterface(), Lexer::TokenType::Identifier, *(begin - 1))); if (auto* loc = context.getLocationOf(name)) { context.log(Notes::IDENTIFIER_IS_TYPEDEF.args( *loc->identifier, context.getSourceInterface(), *loc->identifier)); } } } checkForClose.reset(); if (directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorParenthesesIdentifiers( start, begin, std::move(*directDeclarator), std::move(identifiers))); } break; } case Lexer::TokenType::OpenSquareBracket: { auto scope = context.squareBracketEntered(begin); const auto* openPpos = begin; auto checkForClose = std::optional{cld::ScopeExit( [&] { if (!expect(Lexer::TokenType::CloseSquareBracket, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } })}; begin++; if (begin == end) { return {}; } if (begin->getTokenType() == Lexer::TokenType::StaticKeyword) { const auto* staticLoc = begin++; std::vector<TypeQualifier> typeQualifiers; while (begin < end && (begin->getTokenType() == Lexer::TokenType::ConstKeyword || begin->getTokenType() == Lexer::TokenType::RestrictKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword)) { switch (begin->getTokenType()) { case Lexer::TokenType::ConstKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Const); break; case Lexer::TokenType::RestrictKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Restrict); break; case Lexer::TokenType::VolatileKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Volatile); break; default: CLD_UNREACHABLE; } begin++; } auto assignmentExpression = cld::Parser::parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); checkForClose.reset(); if (assignmentExpression && directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>( DirectDeclaratorStatic(start, begin, std::move(directDeclarator), staticLoc, std::move(typeQualifiers), std::move(*assignmentExpression))); } break; } std::vector<TypeQualifier> typeQualifiers; while (begin < end && (begin->getTokenType() == Lexer::TokenType::ConstKeyword || begin->getTokenType() == Lexer::TokenType::RestrictKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword)) { switch (begin->getTokenType()) { case Lexer::TokenType::ConstKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Const); break; case Lexer::TokenType::RestrictKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Restrict); break; case Lexer::TokenType::VolatileKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Volatile); break; default: CLD_UNREACHABLE; } begin++; } if (begin == end) { break; } if (begin->getTokenType() == Lexer::TokenType::StaticKeyword) { const auto* staticLoc = begin++; auto assignment = cld::Parser::parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); checkForClose.reset(); if (assignment && directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>( DirectDeclaratorStatic(start, begin, std::move(directDeclarator), staticLoc, std::move(typeQualifiers), std::move(*assignment))); } } else if (begin->getTokenType() == Lexer::TokenType::Asterisk) { const auto* asterisk = begin++; checkForClose.reset(); if (directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorAsterisk( start, begin, std::move(*directDeclarator), std::move(typeQualifiers), asterisk)); } } else if (firstIsInAssignmentExpression(*begin, context)) { auto assignment = cld::Parser::parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); checkForClose.reset(); if (assignment && directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorNoStaticOrAsterisk( start, begin, std::move(directDeclarator), std::move(typeQualifiers), std::make_unique<AssignmentExpression>(std::move(*assignment)))); } } else { checkForClose.reset(); if (directDeclarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorNoStaticOrAsterisk( start, begin, std::move(directDeclarator), std::move(typeQualifiers), nullptr)); } } break; } default: break; } } if (!directDeclarator) { return {}; } return std::move(*directDeclarator); } std::optional<cld::Syntax::DirectAbstractDeclarator> parseDirectAbstractDeclaratorSuffix(cld::Lexer::CTokenIterator& begin, cld::Lexer::CTokenIterator end, cld::Parser::Context& context, std::unique_ptr<DirectAbstractDeclarator>&& directAbstractDeclarator) { using namespace cld; using namespace cld::Parser; bool first = !directAbstractDeclarator; const auto* start = directAbstractDeclarator ? cld::match(*directAbstractDeclarator, [](auto&& value) { return value.begin(); }) : begin; while (begin < end && (begin->getTokenType() == Lexer::TokenType::OpenParentheses || begin->getTokenType() == Lexer::TokenType::OpenSquareBracket)) { switch (begin->getTokenType()) { case Lexer::TokenType::OpenParentheses: { auto scope = context.parenthesesEntered(begin); const auto* openPpos = begin; auto closeParenth = std::optional{cld::ScopeExit( [&] { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } })}; begin++; // https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#Attribute-Syntax: // At present, the first parameter in a function prototype must have some type specifier that is not an // attribute specifier; this resolves an ambiguity in the interpretation of void f(int // (__attribute__((foo)) x)), but is subject to change. if (begin < end && firstIsInDeclarationSpecifier(*begin, context) && begin->getTokenType() != Lexer::TokenType::GNUAttribute) { auto parameterTypeList = parseParameterTypeList( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); closeParenth.reset(); directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorParameterTypeList( start, begin, std::move(directAbstractDeclarator), std::make_unique<ParameterTypeList>(std::move(parameterTypeList)))); } else if (begin < end && first && firstIsInAbstractDeclarator(*begin, context)) { auto attribute = parseGNUAttributes(begin, end, context); auto abstractDeclarator = parseAbstractDeclarator(begin, end, context); closeParenth.reset(); directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorParentheses( start, begin, std::move(attribute), std::make_unique<AbstractDeclarator>(std::move(abstractDeclarator)))); } else { closeParenth.reset(); directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorParameterTypeList( start, begin, std::move(directAbstractDeclarator), nullptr)); } break; } case Lexer::TokenType::OpenSquareBracket: { auto scope = context.squareBracketEntered(begin); const auto* openPpos = begin; auto closeParenth = std::optional{cld::ScopeExit( [&] { if (!expect(Lexer::TokenType::CloseSquareBracket, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } })}; begin++; if (begin == end) { return {}; } if (begin->getTokenType() == Lexer::TokenType::StaticKeyword) { const auto* staticLoc = begin++; std::vector<TypeQualifier> typeQualifiers; while (begin < end && (begin->getTokenType() == Lexer::TokenType::ConstKeyword || begin->getTokenType() == Lexer::TokenType::RestrictKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword)) { switch (begin->getTokenType()) { case Lexer::TokenType::ConstKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Const); break; case Lexer::TokenType::RestrictKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Restrict); break; case Lexer::TokenType::VolatileKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Volatile); break; default: CLD_UNREACHABLE; } begin++; } auto assignmentExpression = cld::Parser::parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); closeParenth.reset(); if (assignmentExpression) { directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorStatic( start, begin, std::move(directAbstractDeclarator), staticLoc, std::move(typeQualifiers), std::move(*assignmentExpression))); } break; } if (begin->getTokenType() == Lexer::TokenType::Asterisk) { const auto* asterisk = begin++; closeParenth.reset(); directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>( DirectAbstractDeclaratorAsterisk(start, begin, std::move(directAbstractDeclarator), asterisk)); break; } std::vector<TypeQualifier> typeQualifiers; while (begin < end && (begin->getTokenType() == Lexer::TokenType::ConstKeyword || begin->getTokenType() == Lexer::TokenType::RestrictKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword)) { switch (begin->getTokenType()) { case Lexer::TokenType::ConstKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Const); break; case Lexer::TokenType::RestrictKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Restrict); break; case Lexer::TokenType::VolatileKeyword: typeQualifiers.emplace_back(begin, begin + 1, TypeQualifier::Volatile); break; default: CLD_UNREACHABLE; } begin++; } if (begin < end && begin->getTokenType() == Lexer::TokenType::StaticKeyword) { const auto* staticLoc = begin++; auto assignment = cld::Parser::parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); closeParenth.reset(); if (assignment) { directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>( DirectAbstractDeclaratorStatic(start, begin, std::move(directAbstractDeclarator), staticLoc, std::move(typeQualifiers), std::move(*assignment))); } break; } if (begin < end && firstIsInAssignmentExpression(*begin, context)) { auto assignment = parseAssignmentExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); closeParenth.reset(); if (assignment) { directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorAssignmentExpression( start, begin, std::move(directAbstractDeclarator), std::move(typeQualifiers), std::make_unique<AssignmentExpression>(std::move(*assignment)))); } } else { closeParenth.reset(); directAbstractDeclarator = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorAssignmentExpression( start, begin, std::move(directAbstractDeclarator), std::move(typeQualifiers), nullptr)); } break; } default: break; } first = false; } if (first) { if (begin == end) { context.log(Errors::Parser::EXPECTED_N_OR_N.args(diag::after(*(begin - 1)), context.getSourceInterface(), Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket, *(begin - 1))); } else { context.log(Errors::Parser::EXPECTED_N_OR_N_INSTEAD_OF_N.args(*begin, context.getSourceInterface(), Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket, *begin)); } context.skipUntil(begin, end); return {}; } if (!directAbstractDeclarator) { return {}; } return std::move(*directAbstractDeclarator); } } // namespace std::optional<cld::Syntax::DirectDeclarator> cld::Parser::parseDirectDeclarator(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { std::unique_ptr<DirectDeclarator> directDeclarator; const auto* start = begin; if (begin < end && begin->getTokenType() == Lexer::TokenType::Identifier) { const auto* currToken = begin; begin++; directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorIdentifier(start, begin, currToken)); } else if (begin < end && begin->getTokenType() == Lexer::TokenType::OpenParentheses) { auto scope = context.parenthesesEntered(begin); const auto* openPpos = begin; begin++; auto attributes = parseGNUAttributes(begin, end, context); auto declarator = parseDeclarator( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); if (declarator) { directDeclarator = std::make_unique<DirectDeclarator>(DirectDeclaratorParentheses( start, begin, std::move(attributes), std::make_unique<Declarator>(std::move(*declarator)))); } if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil( begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } } else { if (begin == end) { context.log(Errors::Parser::EXPECTED_N_OR_N.args(diag::after(*(begin - 1)), context.getSourceInterface(), Lexer::TokenType::OpenParentheses, Lexer::TokenType::Identifier, *(begin - 1))); } else { context.log(Errors::Parser::EXPECTED_N_OR_N_INSTEAD_OF_N.args(*begin, context.getSourceInterface(), Lexer::TokenType::OpenParentheses, Lexer::TokenType::Identifier, *begin)); } context.skipUntil( begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } return parseDirectDeclaratorSuffix(begin, end, context, std::move(directDeclarator)); } cld::Syntax::ParameterTypeList cld::Parser::parseParameterTypeList(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; auto parameterList = parseParameterList(begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::Comma))); bool hasEllipse = false; if (begin < end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; if (begin == end || begin->getTokenType() != Lexer::TokenType::Ellipse) { context.log(Errors::Parser::EXPECTED_PARAMETER_AFTER_N.args(diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); } else { begin++; hasEllipse = true; } } return ParameterTypeList(start, begin, std::move(parameterList), hasEllipse); } cld::Syntax::ParameterList cld::Parser::parseParameterList(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; std::vector<ParameterDeclaration> parameterDeclarations; bool first = true; while (begin < end) { if (first) { first = false; } else if (begin->getTokenType() == Lexer::TokenType::Comma && (begin + 1 == end || (begin + 1)->getTokenType() != Lexer::TokenType::Ellipse)) { begin++; } else { break; } const auto* parameterBegin = begin; auto declarationSpecifiers = parseDeclarationSpecifierList( begin, end, context.withRecoveryTokens(firstAbstractDeclaratorSet | firstDeclaratorSet | Context::fromTokenTypes(Lexer::TokenType::Comma))); if (begin == end || begin->getTokenType() == Lexer::TokenType::CloseParentheses || begin->getTokenType() == Lexer::TokenType::Comma) { parameterDeclarations.emplace_back(parameterBegin, begin, std::move(declarationSpecifiers)); continue; } struct Stack { std::vector<Syntax::Pointer> pointers; std::optional<ValueReset<std::uint64_t>> scope; const Lexer::CToken* openParentheses; std::optional<GNUAttributes> attributes; }; std::vector<Stack> pointerStack; using DeclaratorVariant = std::variant<std::monostate, std::unique_ptr<Declarator>, std::unique_ptr<AbstractDeclarator>>; DeclaratorVariant foundDeclarator; while (std::holds_alternative<std::monostate>(foundDeclarator)) { auto* thisDeclBegin = begin; pointerStack.emplace_back(); while (begin < end && begin->getTokenType() == Lexer::TokenType::Asterisk) { pointerStack.back().pointers.push_back(parsePointer( begin, end, context.withRecoveryTokens(firstAbstractDeclaratorSet | firstDeclaratorSet))); } if (begin == end) { if (!pointerStack.back().pointers.empty()) { foundDeclarator = std::make_unique<AbstractDeclarator>(thisDeclBegin, begin, std::move(pointerStack.back().pointers)); pointerStack.pop_back(); continue; } auto result = parseDirectAbstractDeclarator(begin, end, context); foundDeclarator = std::make_unique<AbstractDeclarator>( thisDeclBegin, begin, std::move(pointerStack.back().pointers), std::move(result)); pointerStack.pop_back(); continue; } switch (begin->getTokenType()) { default: { // Abstract declarator is only allowed to be missing if there was at least one pointer if (!pointerStack.back().pointers.empty()) { foundDeclarator = std::make_unique<AbstractDeclarator>(thisDeclBegin, begin, std::move(pointerStack.back().pointers)); pointerStack.pop_back(); break; } if (pointerStack.size() >= 2 && (firstIsInParameterList(*begin, context) || begin->getTokenType() == Lexer::TokenType::CloseParentheses)) { pointerStack.pop_back(); // This can happen if the previous ( was actually not a Direct(Abstract)DeclaratorParentheses // but is a function declarator instead. In this case we need to pop. This syntax is possible // when the DirectAbstractDeclarator of the function declarator does not exist auto closeParenth = std::optional{cld::ScopeExit( [&] { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args( *pointerStack.back().openParentheses, context.getSourceInterface(), *pointerStack.back().openParentheses); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::OpenSquareBracket)); } })}; if (begin->getTokenType() == Lexer::TokenType::CloseParentheses) { closeParenth.reset(); foundDeclarator = std::make_unique<AbstractDeclarator>( thisDeclBegin, begin, std::move(pointerStack.back().pointers), DirectAbstractDeclaratorParameterTypeList(start, begin, {}, nullptr)); } else { auto parameterTypeList = parseParameterTypeList(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::CloseParentheses))); closeParenth.reset(); foundDeclarator = std::make_unique<AbstractDeclarator>( thisDeclBegin, begin, std::move(pointerStack.back().pointers), DirectAbstractDeclaratorParameterTypeList( start, begin, {}, std::make_unique<ParameterTypeList>(std::move(parameterTypeList)))); } pointerStack.pop_back(); break; } [[fallthrough]]; } case Lexer::TokenType::OpenSquareBracket: { auto result = parseDirectAbstractDeclarator( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::Comma))); foundDeclarator = std::make_unique<AbstractDeclarator>( thisDeclBegin, begin, std::move(pointerStack.back().pointers), std::move(result)); pointerStack.pop_back(); break; } case Lexer::TokenType::Identifier: { auto result = parseDirectDeclarator(begin, end, context); if (!result) { foundDeclarator = std::unique_ptr<Syntax::Declarator>{}; } else { foundDeclarator = std::make_unique<Declarator>( thisDeclBegin, begin, std::move(pointerStack.back().pointers), std::move(*result)); } pointerStack.pop_back(); break; } case Lexer::TokenType::OpenParentheses: { pointerStack.back().scope = context.parenthesesEntered(begin); pointerStack.back().openParentheses = begin++; pointerStack.back().attributes = parseGNUAttributes(begin, end, context); break; } } } for (auto iter = pointerStack.rbegin(); iter != pointerStack.rend(); pointerStack.pop_back(), iter = pointerStack.rbegin()) { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*iter->openParentheses, context.getSourceInterface(), *iter->openParentheses); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::CloseParentheses, Lexer::TokenType::Comma)); } iter->scope.reset(); foundDeclarator = cld::match( std::move(foundDeclarator), [](std::monostate) -> DeclaratorVariant { CLD_UNREACHABLE; }, [&](std::unique_ptr<Declarator>&& declarator) -> DeclaratorVariant { std::unique_ptr<DirectDeclarator> parentheses; if (declarator) { parentheses = std::make_unique<DirectDeclarator>(DirectDeclaratorParentheses( iter->openParentheses, begin, std::move(iter->attributes), std::move(declarator))); } auto result = parseDirectDeclaratorSuffix(begin, end, context, std::move(parentheses)); if (result) { return std::make_unique<Declarator>(iter->openParentheses, begin, std::move(iter->pointers), std::move(*result)); } return std::unique_ptr<Declarator>{}; }, [&](std::unique_ptr<AbstractDeclarator>&& abstractDeclarator) -> DeclaratorVariant { auto parentheses = std::make_unique<DirectAbstractDeclarator>(DirectAbstractDeclaratorParentheses( iter->openParentheses, begin, std::move(iter->attributes), std::move(abstractDeclarator))); auto result = parseDirectAbstractDeclaratorSuffix(begin, end, context, std::move(parentheses)); return std::make_unique<AbstractDeclarator>(iter->openParentheses, begin, std::move(iter->pointers), std::move(result)); }); } auto attributes = parseGNUAttributes(begin, end, context); cld::match( std::move(foundDeclarator), [](std::monostate) { CLD_UNREACHABLE; }, [&](std::unique_ptr<Declarator>&& declarator) { parameterDeclarations.emplace_back(parameterBegin, begin, std::move(declarationSpecifiers), std::move(declarator), std::move(attributes)); }, [&](std::unique_ptr<AbstractDeclarator>&& abstractDeclarator) { parameterDeclarations.emplace_back(parameterBegin, begin, std::move(declarationSpecifiers), std::move(abstractDeclarator), std::move(attributes)); }); } if (first) { context.log(Errors::Parser::PARAMETER_LIST_REQUIRES_AT_LEAST_ONE_PARAMETER.args( *begin, context.getSourceInterface(), *begin)); } return ParameterList(start, begin, std::move(parameterDeclarations)); } cld::Syntax::Pointer cld::Parser::parsePointer(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::Asterisk, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::ConstKeyword, Lexer::TokenType::RestrictKeyword, Lexer::TokenType::VolatileKeyword)); } std::vector<std::variant<TypeQualifier, GNUAttributes>> typeQualifier; while (begin < end && (begin->getTokenType() == Lexer::TokenType::ConstKeyword || begin->getTokenType() == Lexer::TokenType::RestrictKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword || begin->getTokenType() == Lexer::TokenType::GNUAttribute)) { switch (begin->getTokenType()) { case Lexer::TokenType::ConstKeyword: typeQualifier.emplace_back(std::in_place_type<TypeQualifier>, begin, begin + 1, TypeQualifier::Const); begin++; break; case Lexer::TokenType::RestrictKeyword: typeQualifier.emplace_back(std::in_place_type<TypeQualifier>, begin, begin + 1, TypeQualifier::Restrict); begin++; break; case Lexer::TokenType::VolatileKeyword: typeQualifier.emplace_back(std::in_place_type<TypeQualifier>, begin, begin + 1, TypeQualifier::Volatile); begin++; break; case Lexer::TokenType::GNUAttribute: { auto attributes = parseGNUAttributes(begin, end, context); CLD_ASSERT(attributes); typeQualifier.emplace_back(std::move(*attributes)); } break; default: CLD_UNREACHABLE; } } return Pointer(start, begin, std::move(typeQualifier)); } cld::Syntax::AbstractDeclarator cld::Parser::parseAbstractDeclarator(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; std::vector<Syntax::Pointer> pointers; while (begin < end && begin->getTokenType() == Lexer::TokenType::Asterisk) { auto result = parsePointer(begin, end, context.withRecoveryTokens(firstAbstractDeclaratorSet)); pointers.push_back(std::move(result)); } if (begin < end ? !firstIsInDirectAbstractDeclarator(*begin, context) && !pointers.empty() : !pointers.empty()) { return AbstractDeclarator(start, begin, std::move(pointers), {}); } auto result = parseDirectAbstractDeclarator(begin, end, context); return AbstractDeclarator(start, begin, std::move(pointers), std::move(result)); } std::optional<cld::Syntax::DirectAbstractDeclarator> cld::Parser::parseDirectAbstractDeclarator(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { return parseDirectAbstractDeclaratorSuffix(begin, end, context, {}); } std::optional<cld::Syntax::EnumSpecifier> cld::Parser::parseEnumSpecifier(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::EnumKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenBrace, Lexer::TokenType::Identifier)); } auto beforeAttributes = parseGNUAttributes(begin, end, context); const Lexer::CToken* name = nullptr; if (begin < end && begin->getTokenType() == Lexer::TokenType::Identifier) { name = begin; begin++; } else if (begin == end) { context.log(Errors::Parser::EXPECTED_N_AFTER_N.args(diag::after(*(begin - 1)), context.getSourceInterface(), Lexer::TokenType::Identifier, *(begin - 1))); context.skipUntil(begin, end); return {}; } const auto* openPpos = begin; if (begin == end || begin->getTokenType() != Lexer::TokenType::OpenBrace) { if (!name) { expect(Lexer::TokenType::Identifier, begin, end, context); context.skipUntil(begin, end); return {}; } return EnumSpecifier(start, begin, EnumSpecifier::EnumTag{std::move(beforeAttributes), name}); } begin++; bool inLoop = false; std::vector<EnumDeclaration::EnumValue> values; while ( begin < end && (begin->getTokenType() == Lexer::TokenType::Identifier || begin->getTokenType() == Lexer::TokenType::Comma)) { inLoop = true; const auto* thisValueStart = begin; if (!expect(Lexer::TokenType::Identifier, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Assignment, Lexer::TokenType::Comma, Lexer::TokenType::CloseBrace)); } values.push_back({thisValueStart, parseGNUAttributes(begin, end, context), std::nullopt}); if (begin < end && begin->getTokenType() == Lexer::TokenType::Assignment) { begin++; auto constant = parseConditionalExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::CloseBrace, Lexer::TokenType::Comma))); if (thisValueStart->getTokenType() == Lexer::TokenType::Identifier) { values.back().value = std::move(constant); } } if (thisValueStart->getTokenType() == Lexer::TokenType::Identifier) { context.addToScope(thisValueStart->getText(), {thisValueStart, begin, thisValueStart}); } if (begin < end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; } else if (begin == end || begin->getTokenType() != Lexer::TokenType::CloseBrace) { if (begin == end) { context.log(Errors::Parser::EXPECTED_N.args(diag::after(*(begin - 1)), context.getSourceInterface(), Lexer::TokenType::CloseBrace, *(begin - 1))); context.log(Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos)); return {}; } context.log(Errors::Parser::EXPECTED_N_INSTEAD_OF_N.args(*begin, context.getSourceInterface(), Lexer::TokenType::Comma, *begin)); context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Identifier, Lexer::TokenType::CloseBrace)); } } if (begin < end) { begin++; } else { expect(Lexer::TokenType::CloseBrace, begin, end, context); return {}; } if (!inLoop) { context.log(Errors::Parser::ENUM_REQUIRES_AT_LEAST_ONE_VALUE.args( *openPpos, context.getSourceInterface(), std::forward_as_tuple(*openPpos, *(begin - 1)))); } auto afterAttributes = parseGNUAttributes(begin, end, context); return EnumSpecifier(start, begin, EnumDeclaration(start, begin, std::move(beforeAttributes), name, std::move(values), std::move(afterAttributes))); } std::optional<cld::Syntax::CompoundStatement> cld::Parser::parseCompoundStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, cld::Parser::Context& context, bool pushScope) { const auto* start = begin; auto scope = context.braceEntered(begin); bool braceSeen = true; if (!expect(Lexer::TokenType::OpenBrace, begin, end, context)) { braceSeen = false; context.skipUntil(begin, end, firstCompoundItem | Context::fromTokenTypes(Lexer::TokenType::CloseBrace)); } std::vector<CompoundItem> items; if (pushScope) { context.pushScope(); } while (begin < end && firstIsInCompoundItem(*begin, context)) { auto result = parseCompoundItem( begin, end, context.withRecoveryTokens(firstCompoundItem | Context::fromTokenTypes(Lexer::TokenType::CloseBrace))); if (result) { items.push_back(std::move(*result)); } } if (pushScope) { context.popScope(); } if (braceSeen) { if (!expect(Lexer::TokenType::CloseBrace, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*start, context.getSourceInterface(), *start); })) { context.skipUntil(begin, end); } } else { if (!expect(Lexer::TokenType::CloseBrace, begin, end, context)) { context.skipUntil(begin, end); } } return CompoundStatement(start, begin, std::move(items)); } std::optional<cld::Syntax::CompoundItem> cld::Parser::parseCompoundItem(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* lookahead = std::find_if_not( begin, end, [](const Lexer::CToken& token) { return token.getTokenType() == Lexer::TokenType::GNUExtension; }); if (lookahead != end && firstIsInDeclarationSpecifier(*lookahead, context) && !(lookahead->getTokenType() == Lexer::TokenType::Identifier && lookahead + 1 < end && (lookahead + 1)->getTokenType() == Lexer::TokenType::Colon)) { auto extensionReset = context.enableExtensions(lookahead != begin); auto declaration = parseDeclaration(lookahead, end, context); begin = lookahead; if (!declaration) { return {}; } return CompoundItem(std::move(*declaration)); } auto statement = parseStatement(begin, end, context); if (!statement) { return {}; } return CompoundItem(std::move(*statement)); } std::optional<cld::Syntax::Initializer> cld::Parser::parseInitializer(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (begin == end || begin->getTokenType() != Lexer::TokenType::OpenBrace) { auto assignment = parseAssignmentExpression(begin, end, context); if (!assignment) { return {}; } return Initializer(start, begin, std::move(*assignment)); } auto scope = context.braceEntered(begin); begin++; auto initializerList = parseInitializerList( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseBrace, Lexer::TokenType::Comma))); if (begin < end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; } if (!expect(Lexer::TokenType::CloseBrace, begin, end, context)) { context.skipUntil(begin, end); } if (!initializerList) { return {}; } return Initializer{start, begin, std::move(*initializerList)}; } std::optional<cld::Syntax::InitializerList> cld::Parser::parseInitializerList(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; typename InitializerList::vector vector; bool first = true; do { if (first) { first = false; } else { expect(Lexer::TokenType::Comma, begin, end, context); } Syntax::InitializerList::DesignatorList designation; bool hasDesignation = false; while (begin < end && (begin->getTokenType() == Lexer::TokenType::OpenSquareBracket || begin->getTokenType() == Lexer::TokenType::Dot)) { hasDesignation = true; if (begin->getTokenType() == Lexer::TokenType::OpenSquareBracket) { auto scope = context.squareBracketEntered(begin); const auto* openPpos = begin; begin++; auto constant = parseConditionalExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseSquareBracket))); if (constant) { designation.emplace_back(std::move(*constant)); } if (!expect(Lexer::TokenType::CloseSquareBracket, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Assignment, Lexer::TokenType::OpenSquareBracket, Lexer::TokenType::Dot)); } } else { const auto* token = ++begin; if (!expect(Lexer::TokenType::Identifier, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Assignment, Lexer::TokenType::OpenSquareBracket, Lexer::TokenType::Dot)); } designation.emplace_back(token); } } if (hasDesignation) { if (!expect(Lexer::TokenType::Assignment, begin, end, context)) { context.skipUntil(begin, end, firstInitializerSet); } } auto initializer = parseInitializer(begin, end, context); if (!initializer) { continue; } vector.push_back({std::move(*initializer), std::move(designation)}); } while (begin < end && begin + 1 < end && (firstIsInInitializerList(begin->getTokenType() == Lexer::TokenType::Comma ? *(begin + 1) : *begin, context))); return InitializerList{start, begin, std::move(vector)}; } std::optional<cld::Syntax::Statement> cld::Parser::parseStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (begin != end) { switch (begin->getTokenType()) { case Lexer::TokenType::ReturnKeyword: { auto ret = parseReturnStatement(begin, end, context); return Statement(std::move(ret)); } case Lexer::TokenType::IfKeyword: { auto ifStat = parseIfStatement(begin, end, context); if (!ifStat) { return {}; } return Statement(std::move(*ifStat)); } case Lexer::TokenType::SwitchKeyword: { auto switchStat = parseSwitchStatement(begin, end, context); if (!switchStat) { return {}; } return Statement(std::move(*switchStat)); } case Lexer::TokenType::OpenBrace: { auto compoundStatement = parseCompoundStatement(begin, end, context, false); if (!compoundStatement) { return {}; } return Statement{std::move(*compoundStatement)}; } case Lexer::TokenType::ForKeyword: { auto forStat = parseForStatement(begin, end, context); if (!forStat) { return {}; } return Statement(std::move(*forStat)); } case Lexer::TokenType::WhileKeyword: { auto headWhile = parseHeadWhileStatement(begin, end, context); if (!headWhile) { return {}; } return Statement(std::move(*headWhile)); } case Lexer::TokenType::DoKeyword: { auto doWhile = parseFootWhileStatement(begin, end, context); if (!doWhile) { return {}; } return Statement(std::move(*doWhile)); } case Lexer::TokenType::BreakKeyword: { begin++; if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); return {}; } return Statement(BreakStatement(start, begin)); } case Lexer::TokenType::ContinueKeyword: { begin++; if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); return {}; } return Statement(ContinueStatement(start, begin)); } case Lexer::TokenType::DefaultKeyword: { const auto* defaultToken = begin++; const auto* colonToken = begin; if (!expect(Lexer::TokenType::Colon, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } auto statement = parseStatement(begin, end, context); if (!statement) { return {}; } return Statement(DefaultStatement(start, begin, defaultToken, colonToken, std::make_unique<Statement>(std::move(*statement)))); } case Lexer::TokenType::CaseKeyword: { const auto* caseToken = begin++; auto expression = parseConditionalExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::Colon))); const auto* colonToken = begin; if (!expect(Lexer::TokenType::Colon, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } auto statement = parseStatement(begin, end, context); if (!statement || !expression) { return {}; } return Statement(CaseStatement(start, begin, caseToken, std::move(*expression), colonToken, std::make_unique<Statement>(std::move(*statement)))); } case Lexer::TokenType::GotoKeyword: { const auto* id = ++begin; if (!expect(Lexer::TokenType::Identifier, begin, end, context)) { if (begin < end && begin + 1 < end && (begin + 1)->getTokenType() == Lexer::TokenType::SemiColon) { begin++; } else { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } } if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } return Statement(GotoStatement(start, begin, id)); } case Lexer::TokenType::GNUASM: { auto statement = parseGNUASMStatement(begin, end, context); if (statement) { return Statement(std::move(*statement)); } return {}; } case Lexer::TokenType::Identifier: { if (begin + 1 < end && (begin + 1)->getTokenType() == Lexer::TokenType::Colon) { const auto* name = begin; begin += 2; auto attribute = parseGNUAttributes(begin, end, context); if (attribute) { if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } return Statement(LabelStatement(start, begin, name, std::move(*attribute))); } auto statement = parseStatement(begin, end, context); if (!statement) { return {}; } return Statement(LabelStatement(start, begin, name, std::move(*statement))); } [[fallthrough]]; } default: { break; } } } if (begin != end && begin->getTokenType() != Lexer::TokenType::SemiColon) { auto expression = parseExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::SemiColon))); std::optional<Message> note; if (start + 1 == begin && start->getTokenType() == Lexer::TokenType::Identifier && context.isTypedef(start->getText()) && begin->getTokenType() == Lexer::TokenType::Identifier) { auto* loc = context.getLocationOf(start->getText()); if (loc) { if (!expect(Lexer::TokenType::SemiColon, begin, end, context, [&] { return Notes::TYPEDEF_OVERSHADOWED_BY_DECLARATION.args( *loc->identifier, context.getSourceInterface(), *loc->identifier); })) { context.skipUntil(begin, end); } } else { if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } } } else { if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } } return Statement(ExpressionStatement(start, begin, std::make_unique<Expression>(std::move(expression)))); } auto attributes = parseGNUAttributes(begin, end, context); if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } return Statement(ExpressionStatement(start, begin, nullptr, std::move(attributes))); } std::optional<cld::Syntax::HeadWhileStatement> cld::Parser::parseHeadWhileStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::WhileKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } std::optional<Lexer::CTokenIterator> openPpos; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet); } else { openPpos = begin - 1; } auto expression = parseExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); std::optional<Message> note; if (openPpos) { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**openPpos, context.getSourceInterface(), **openPpos); })) { context.skipUntil(begin, end, firstStatementSet); } } else { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } } auto statement = parseStatement(begin, end, context); if (!statement) { return {}; } return HeadWhileStatement(start, begin, std::move(expression), std::make_unique<Statement>(std::move(*statement))); } std::optional<cld::Syntax::FootWhileStatement> cld::Parser::parseFootWhileStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; std::optional<Lexer::CTokenIterator> doPos; if (!expect(Lexer::TokenType::DoKeyword, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } else { doPos = start; } auto statement = parseStatement(begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::WhileKeyword))); if (doPos) { if (!expect(Lexer::TokenType::WhileKeyword, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**doPos, context.getSourceInterface(), **doPos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } } else { if (!expect(Lexer::TokenType::WhileKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } } std::optional<Lexer::CTokenIterator> openPpos; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet); } else { openPpos = begin - 1; } auto expression = parseExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); if (openPpos) { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**openPpos, context.getSourceInterface(), **openPpos); })) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } } else { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } } if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } if (!statement) { return {}; } return FootWhileStatement(start, begin, std::make_unique<Statement>(std::move(*statement)), std::move(expression)); } cld::Syntax::ReturnStatement cld::Parser::parseReturnStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::ReturnKeyword, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } if (begin < end && begin->getTokenType() == Lexer::TokenType::SemiColon) { expect(Lexer::TokenType::SemiColon, begin, end, context); return ReturnStatement(start, begin, nullptr); } if (begin == end || !firstIsInExpression(*begin, context)) { expect(Lexer::TokenType::SemiColon, begin, end, context); context.skipUntil(begin, end); return ReturnStatement(start, begin, nullptr); } auto expression = parseExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::SemiColon))); if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } return ReturnStatement(start, begin, std::make_unique<Expression>(std::move(expression))); } std::optional<cld::Syntax::IfStatement> cld::Parser::parseIfStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::IfKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } std::optional<Lexer::CTokenIterator> openPpos; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet); } else { openPpos = begin - 1; } auto expression = parseExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); if (openPpos) { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**openPpos, context.getSourceInterface(), **openPpos); })) { context.skipUntil(begin, end, firstStatementSet); } } else { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } } auto statement = parseStatement(begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::ElseKeyword))); if (!statement && (begin == end || begin->getTokenType() != Lexer::TokenType::ElseKeyword)) { return {}; } if (begin < end && begin->getTokenType() == Lexer::TokenType::ElseKeyword) { begin++; auto elseStatement = parseStatement(begin, end, context); if (!statement || !elseStatement) { return {}; } return IfStatement(start, begin, std::move(expression), std::make_unique<Statement>(std::move(*statement)), std::make_unique<Statement>(std::move(*elseStatement))); } return IfStatement(start, begin, std::move(expression), std::make_unique<Statement>(std::move(*statement))); } std::optional<cld::Syntax::SwitchStatement> cld::Parser::parseSwitchStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::SwitchKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } std::optional<Lexer::CTokenIterator> openPpos; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet); } else { openPpos = begin - 1; } auto expression = parseExpression( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); if (openPpos) { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**openPpos, context.getSourceInterface(), **openPpos); })) { context.skipUntil(begin, end, firstStatementSet); } } else { if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context)) { context.skipUntil(begin, end, firstStatementSet); } } auto statement = parseStatement(begin, end, context); if (!statement) { return {}; } return SwitchStatement(start, begin, std::move(expression), std::make_unique<Statement>(std::move(*statement))); } std::optional<cld::Syntax::ForStatement> cld::Parser::parseForStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { const auto* start = begin; if (!expect(Lexer::TokenType::ForKeyword, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses)); } const auto* openPpos = begin; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet | firstDeclarationSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } if (begin == end) { context.log(Errors::Parser::EXPECTED_EXPRESSION_OR_DECLARATION.args( diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); return {}; } std::variant<Declaration, std::unique_ptr<Expression>> initial{nullptr}; if (firstIsInDeclaration(*begin, context)) { auto decl = parseDeclaration( begin, end, context.withRecoveryTokens(firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon))); if (decl) { initial = std::move(*decl); } } else if (begin->getTokenType() != Lexer::TokenType::SemiColon) { auto exp = parseExpression( begin, end, context.withRecoveryTokens(firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon))); initial = std::make_unique<Expression>(std::move(exp)); if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon)); } } else { begin++; } std::unique_ptr<Expression> controlling; if (begin == end) { context.log(Errors::Parser::EXPECTED_EXPRESSION.args(diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); return {}; } if (begin->getTokenType() != Lexer::TokenType::SemiColon) { auto exp = parseExpression( begin, end, context.withRecoveryTokens(firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::SemiColon))); controlling = std::make_unique<Expression>(std::move(exp)); if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end, firstExpressionSet | Context::fromTokenTypes(Lexer::TokenType::CloseParentheses)); } } else { begin++; } std::unique_ptr<Expression> post; if (begin == end) { context.log(Errors::Parser::EXPECTED_EXPRESSION.args(diag::after(*(begin - 1)), context.getSourceInterface(), *(begin - 1))); return {}; } if (begin->getTokenType() != Lexer::TokenType::CloseParentheses) { auto exp = parseExpression(begin, end, context); post = std::make_unique<Expression>(std::move(exp)); if (!expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openPpos, context.getSourceInterface(), *openPpos); })) { context.skipUntil(begin, end, firstStatementSet); } } else { begin++; } auto stat = parseStatement(begin, end, context); if (!stat) { return {}; } return ForStatement(start, begin, std::make_unique<Statement>(std::move(*stat)), std::move(initial), std::move(controlling), std::move(post)); } std::optional<cld::Syntax::GNUAttributes> cld::Parser::parseGNUAttributes(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { if (begin == end || begin->getTokenType() != Lexer::TokenType::GNUAttribute) { return {}; } const auto* const start = begin; std::vector<Syntax::GNUAttributes::GNUAttribute> attributes; while (begin != end && begin->getTokenType() == Lexer::TokenType::GNUAttribute) { begin++; std::optional<Lexer::CTokenIterator> firstOpenParenth; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil( begin, end, Context::fromTokenTypes(Lexer::TokenType::OpenParentheses, Lexer::TokenType::CloseParentheses)); } else { firstOpenParenth = begin - 1; } std::optional<Lexer::CTokenIterator> secondOpenParenth; if (!expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::CloseParentheses)); } else { secondOpenParenth = begin - 1; } while (begin != end && begin->getTokenType() != Lexer::TokenType::CloseParentheses) { begin = std::find_if_not(begin, end, [](const Lexer::CToken& token) { return token.getTokenType() == Lexer::TokenType ::Comma; }); if (begin == end) { break; } const Lexer::CToken* attributeName = nullptr; switch (begin->getTokenType()) { case Lexer::TokenType::Identifier: case Lexer::TokenType::VoidKeyword: case Lexer::TokenType::CharKeyword: case Lexer::TokenType::ShortKeyword: case Lexer::TokenType::IntKeyword: case Lexer::TokenType::Int128Keyword: case Lexer::TokenType::LongKeyword: case Lexer::TokenType::FloatKeyword: case Lexer::TokenType::DoubleKeyword: case Lexer::TokenType::SignedKeyword: case Lexer::TokenType::UnsignedKeyword: case Lexer::TokenType::TypedefKeyword: case Lexer::TokenType::ExternKeyword: case Lexer::TokenType::StaticKeyword: case Lexer::TokenType::AutoKeyword: case Lexer::TokenType::RegisterKeyword: case Lexer::TokenType::ConstKeyword: case Lexer::TokenType::RestrictKeyword: case Lexer::TokenType::SizeofKeyword: case Lexer::TokenType::VolatileKeyword: case Lexer::TokenType::InlineKeyword: case Lexer::TokenType::ReturnKeyword: case Lexer::TokenType::BreakKeyword: case Lexer::TokenType::ContinueKeyword: case Lexer::TokenType::DoKeyword: case Lexer::TokenType::ElseKeyword: case Lexer::TokenType::ForKeyword: case Lexer::TokenType::IfKeyword: case Lexer::TokenType::WhileKeyword: case Lexer::TokenType::StructKeyword: case Lexer::TokenType::SwitchKeyword: case Lexer::TokenType::CaseKeyword: case Lexer::TokenType::DefaultKeyword: case Lexer::TokenType::UnionKeyword: case Lexer::TokenType::EnumKeyword: case Lexer::TokenType::GotoKeyword: case Lexer::TokenType::UnderlineBool: case Lexer::TokenType::GNUAttribute: case Lexer::TokenType::GNUTypeOf: case Lexer::TokenType::GNUASM: case Lexer::TokenType::GNUExtension: { attributeName = begin++; break; } default: { context.log(Errors::Parser::EXPECTED_ATTRIBUTE_NAME_INSTEAD_OF_N.args( *begin, context.getSourceInterface(), *begin)); context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::Comma, Lexer::TokenType::OpenParentheses, Lexer::TokenType::CloseParentheses)); if (begin != end && begin->getTokenType() == Lexer::TokenType::CloseParentheses) { break; } } } if (begin == end || begin->getTokenType() != Lexer::TokenType::OpenParentheses) { if (attributeName) { attributes.push_back({attributeName, {}}); continue; } break; } const auto* openParenthAttrib = begin++; std::vector<Syntax::AssignmentExpression> expressions; bool requireExpressions = false; if (begin != end && begin->getTokenType() == Lexer::TokenType::Identifier && (begin + 1) != end && ((begin + 1)->getTokenType() == Lexer::TokenType::Comma || (begin + 1)->getTokenType() == Lexer::TokenType::CloseParentheses) && !context.isTypedef(begin->getText())) { auto id = parseAssignmentExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::CloseParentheses))); if (id) { expressions.push_back(std::move(*id)); } if (begin != end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; requireExpressions = true; } } if (!requireExpressions && (begin == end || begin->getTokenType() == Lexer::TokenType::CloseParentheses)) { if (begin != end) { begin++; } attributes.push_back({attributeName, std::move(expressions)}); continue; } { auto first = parseAssignmentExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::CloseParentheses))); if (first) { expressions.push_back(std::move(*first)); } } while (begin != end && begin->getTokenType() == cld::Lexer::TokenType::Comma) { begin++; auto expression = parseAssignmentExpression(begin, end, context.withRecoveryTokens(Context::fromTokenTypes( Lexer::TokenType::Comma, Lexer::TokenType::CloseParentheses))); if (expression) { expressions.push_back(std::move(*expression)); } } expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openParenthAttrib, context.getSourceInterface(), *openParenthAttrib); }); attributes.push_back({attributeName, std::move(expressions)}); } if (secondOpenParenth) { expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**secondOpenParenth, context.getSourceInterface(), **secondOpenParenth); }); } else { expect(Lexer::TokenType::CloseParentheses, begin, end, context); } if (firstOpenParenth) { expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(**firstOpenParenth, context.getSourceInterface(), **firstOpenParenth); }); } else { expect(Lexer::TokenType::CloseParentheses, begin, end, context); } } return Syntax::GNUAttributes(start, begin, std::move(attributes)); } namespace { std::string parseGNUASMString(cld::Lexer::CTokenIterator& begin, cld::Lexer::CTokenIterator end, cld::Parser::Context& context) { using namespace cld; using namespace cld::Parser; if (!expect(Lexer::TokenType::StringLiteral, begin, end, context)) { context.skipUntil(begin, end); if (begin == end) { return {}; } if (begin->getTokenType() == Lexer::TokenType::CloseParentheses) { begin++; } return {}; } begin--; const auto* literalStart = begin; auto literal = parseStringLiteral(begin, end, context); std::string value; if (!std::holds_alternative<std::string>(literal.getValue())) { context.log(Errors::Parser::EXPECTED_NORMAL_STRING_LITERAL_INSIDE_OF_ASM.args( tcb::span(literalStart, begin), context.getSourceInterface(), tcb::span(literalStart, begin))); } else { value = cld::get<std::string>(literal.getValue()); } return value; } } // namespace std::optional<cld::Syntax::GNUSimpleASM> cld::Parser::parseGNUSimpleASM(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { if (begin == end || begin->getTokenType() != Lexer::TokenType::GNUASM) { return {}; } const auto* start = begin++; const Lexer::CToken* openParentheses = nullptr; if (expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { openParentheses = begin - 1; } else { context.skipUntil(begin, end, Context::fromTokenTypes(Lexer::TokenType::CloseParentheses, Lexer::TokenType::StringLiteral)); } auto value = parseGNUASMString(begin, end, context); if (openParentheses) { expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openParentheses, context.getSourceInterface(), *openParentheses); }); } else { expect(Lexer::TokenType::CloseParentheses, begin, end, context); } return GNUSimpleASM(start, begin, std::move(value)); } std::optional<cld::Syntax::GNUASMStatement> cld::Parser::parseGNUASMStatement(Lexer::CTokenIterator& begin, Lexer::CTokenIterator end, Context& context) { CLD_ASSERT(begin != end && begin->getTokenType() == Lexer::TokenType::GNUASM); const auto* start = begin++; std::vector<Syntax::GNUASMQualifier> qualifiers; while (begin != end && (begin->getTokenType() == Lexer::TokenType::GotoKeyword || begin->getTokenType() == Lexer::TokenType::VolatileKeyword || begin->getTokenType() == Lexer::TokenType::InlineKeyword)) { qualifiers.emplace_back(begin++); } const Lexer::CToken* openParentheses = nullptr; if (expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { openParentheses = begin - 1; } auto asmString = parseGNUASMString( begin, end, context.withRecoveryTokens(Context::fromTokenTypes(Lexer::TokenType::CloseParentheses))); std::vector<Syntax::GNUASMStatement::GNUASMOperand> first; std::vector<Syntax::GNUASMStatement::GNUASMOperand> second; std::vector<std::string> clobber; if (begin != end && begin->getTokenType() == Lexer::TokenType::Colon) { begin++; auto parseASMOperand = [&context, &begin, end](std::vector<Syntax::GNUASMStatement::GNUASMOperand>& result) { bool first = true; while (begin != end && (first ? begin->getTokenType() == Lexer::TokenType::StringLiteral || begin->getTokenType() == Lexer::TokenType::OpenSquareBracket : begin->getTokenType() == Lexer::TokenType::Comma)) { if (first) { first = false; } else { begin++; } const Lexer::CToken* identifier = nullptr; if (begin != end && begin->getTokenType() == Lexer::TokenType::OpenSquareBracket) { const auto* openSquareBracket = begin++; if (expect(Lexer::TokenType::Identifier, begin, end, context)) { identifier = begin - 1; } expect(Lexer::TokenType::CloseSquareBracket, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openSquareBracket, context.getSourceInterface(), *openSquareBracket); }); } auto string = parseGNUASMString(begin, end, context); const Lexer::CToken* subOpenParentheses = nullptr; if (expect(Lexer::TokenType::OpenParentheses, begin, end, context)) { subOpenParentheses = begin - 1; } auto expression = parseExpression(begin, end, context); if (subOpenParentheses) { expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*subOpenParentheses, context.getSourceInterface(), *subOpenParentheses); }); } else { expect(Lexer::TokenType::CloseParentheses, begin, end, context); } result.push_back({identifier, std::move(string), std::move(expression)}); } }; parseASMOperand(first); if (begin != end && begin->getTokenType() == Lexer::TokenType::Colon) { begin++; parseASMOperand(second); if (begin != end && begin->getTokenType() == Lexer::TokenType::Colon) { begin++; clobber.push_back(parseGNUASMString(begin, end, context)); while (begin != end && begin->getTokenType() == Lexer::TokenType::Comma) { begin++; clobber.push_back(parseGNUASMString(begin, end, context)); } } } } if (openParentheses) { expect(Lexer::TokenType::CloseParentheses, begin, end, context, [&] { return Notes::TO_MATCH_N_HERE.args(*openParentheses, context.getSourceInterface(), *openParentheses); }); } else { expect(Lexer::TokenType::CloseParentheses, begin, end, context); } if (!expect(Lexer::TokenType::SemiColon, begin, end, context)) { context.skipUntil(begin, end); } return GNUASMStatement(start, begin, std::move(qualifiers), std::move(asmString), std::move(first), std::move(second), std::move(clobber)); }
44.156513
120
0.519774
[ "vector" ]
2199c7dc11f5dd6a9c6560e3c4f882ac92c2b24e
29,999
cpp
C++
src/yvalve/alt.cpp
AlexeyMochalov/firebird
8b485a455c70d1eaf201192b46b5dd5fdf5ea386
[ "Condor-1.1" ]
988
2016-03-16T10:27:43.000Z
2022-03-31T14:52:19.000Z
src/yvalve/alt.cpp
AlexeyMochalov/firebird
8b485a455c70d1eaf201192b46b5dd5fdf5ea386
[ "Condor-1.1" ]
574
2016-03-23T15:35:56.000Z
2022-03-31T07:11:03.000Z
src/yvalve/alt.cpp
AlexeyMochalov/firebird
8b485a455c70d1eaf201192b46b5dd5fdf5ea386
[ "Condor-1.1" ]
241
2016-03-17T09:53:16.000Z
2022-03-29T19:58:29.000Z
/* * PROGRAM: JRD Access Method * MODULE: alt.cpp * DESCRIPTION: Alternative entrypoints * * The contents of this file are subject to the Interbase Public * License Version 1.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.Inprise.com/IPL.html * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code was created by Inprise Corporation * and its predecessors. Portions created by Inprise Corporation are * Copyright (C) Inprise Corporation. * * All Rights Reserved. * Contributor(s): ______________________________________. * * 23-May-2001 Claudio Valderrama - isc_add_user allowed user names * up to 32 characters length; changed to 31. * * 2002.10.29 Sean Leyne - Removed support for obsolete IPX/SPX Protocol * 2002.10.29 Sean Leyne - Removed obsolete "Netware" port * * 2002.10.30 Sean Leyne - Removed support for obsolete "PC_PLATFORM" define * */ #include "firebird.h" #include <string.h> #include <stdio.h> #include "../common/classes/init.h" #include <stdarg.h> #include "ibase.h" #include "../yvalve/gds_proto.h" #include "../yvalve/utl_proto.h" #include "../yvalve/why_proto.h" #include "../utilities/gsec/gsec.h" #include "../common/security.h" #include "../common/call_service.h" #include "../jrd/event.h" #include "../yvalve/alt_proto.h" #include "../jrd/constants.h" static ISC_STATUS executeSecurityCommand(ISC_STATUS*, const USER_SEC_DATA*, Auth::UserData&); SLONG API_ROUTINE_VARARG isc_event_block(UCHAR** event_buffer, UCHAR** result_buffer, USHORT count, ...) { /************************************** * * i s c _ e v e n t _ b l o c k * ************************************** * * Functional description * Create an initialized event parameter block from a * variable number of input arguments. * Return the size of the block. * * Return 0 if any error occurs. * **************************************/ va_list ptr; va_start(ptr, count); // calculate length of event parameter block, setting initial length to include version // and counts for each argument SLONG length = 1; USHORT i = count; while (i--) { const char* q = va_arg(ptr, SCHAR *); length += static_cast<SLONG>(strlen(q)) + 5; } va_end(ptr); UCHAR* p = *event_buffer = (UCHAR *) gds__alloc((SLONG) length); // FREE: apparently never freed if (!*event_buffer) // NOMEM: return 0; if ((*result_buffer = (UCHAR *) gds__alloc((SLONG) length)) == NULL) { // NOMEM: // FREE: apparently never freed gds__free(*event_buffer); *event_buffer = NULL; return 0; } #ifdef DEBUG_GDS_ALLOC // I can find no place where these are freed // 1994-October-25 David Schnepper gds_alloc_flag_unfreed((void *) *event_buffer); gds_alloc_flag_unfreed((void *) *result_buffer); #endif // DEBUG_GDS_ALLOC // initialize the block with event names and counts *p++ = EPB_version1; va_start(ptr, count); i = count; while (i--) { const char* q = va_arg(ptr, SCHAR *); // Strip the blanks from the ends const char* end = q + strlen(q); while (--end >= q && *end == ' ') ; *p++ = end - q + 1; while (q <= end) *p++ = *q++; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; } va_end(ptr); return static_cast<SLONG>(p - *event_buffer); } USHORT API_ROUTINE isc_event_block_a(SCHAR** event_buffer, SCHAR** result_buffer, USHORT count, TEXT** name_buffer) { /************************************** * * i s c _ e v e n t _ b l o c k _ a * ************************************** * * Functional description * Create an initialized event parameter block from a * vector of input arguments. (Ada needs this) * Assume all strings are 31 characters long. * Return the size of the block. * **************************************/ const int MAX_NAME_LENGTH = 31; // calculate length of event parameter block, setting initial length to include version // and counts for each argument USHORT i = count; TEXT** nb = name_buffer; SLONG length = 0; while (i--) { const TEXT* const q = *nb++; // Strip trailing blanks from string const char* end = q + MAX_NAME_LENGTH; while (--end >= q && *end == ' ') ; length += end - q + 1 + 5; } i = count; char* p = *event_buffer = (SCHAR *) gds__alloc((SLONG) length); // FREE: apparently never freed if (!(*event_buffer)) // NOMEM: return 0; if ((*result_buffer = (SCHAR *) gds__alloc((SLONG) length)) == NULL) { // NOMEM: // FREE: apparently never freed gds__free(*event_buffer); *event_buffer = NULL; return 0; } #ifdef DEBUG_GDS_ALLOC // I can find no place where these are freed // 1994-October-25 David Schnepper gds_alloc_flag_unfreed((void *) *event_buffer); gds_alloc_flag_unfreed((void *) *result_buffer); #endif // DEBUG_GDS_ALLOC *p++ = EPB_version1; nb = name_buffer; while (i--) { const TEXT* q = *nb++; // Strip trailing blanks from string const char* end = q + MAX_NAME_LENGTH; while (--end >= q && *end == ' ') ; *p++ = end - q + 1; while (q <= end) *p++ = *q++; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; } return (p - *event_buffer); } void API_ROUTINE isc_event_block_s(SCHAR** event_buffer, SCHAR** result_buffer, USHORT count, TEXT** name_buffer, USHORT* return_count) { /************************************** * * i s c _ e v e n t _ b l o c k _ s * ************************************** * * Functional description * THIS IS THE COBOL VERSION of gds__event_block_a for Cobols * that don't permit return values. * **************************************/ *return_count = isc_event_block_a(event_buffer, result_buffer, count, name_buffer); } ISC_STATUS API_ROUTINE_VARARG gds__start_transaction(ISC_STATUS* status_vector, FB_API_HANDLE* tra_handle, SSHORT count, ...) { // This infamous structure is defined several times in different places struct teb_t { FB_API_HANDLE* teb_database; int teb_tpb_length; UCHAR* teb_tpb; }; teb_t tebs[16]; teb_t* teb = tebs; if (count > FB_NELEM(tebs)) teb = (teb_t*) gds__alloc(((SLONG) sizeof(teb_t) * count)); // FREE: later in this module if (!teb) { // NOMEM: status_vector[0] = isc_arg_gds; status_vector[1] = isc_virmemexh; status_vector[2] = isc_arg_end; return status_vector[1]; } const teb_t* const end = teb + count; va_list ptr; va_start(ptr, count); for (teb_t* teb_iter = teb; teb_iter < end; ++teb_iter) { teb_iter->teb_database = va_arg(ptr, FB_API_HANDLE*); teb_iter->teb_tpb_length = va_arg(ptr, int); teb_iter->teb_tpb = va_arg(ptr, UCHAR *); } va_end(ptr); const ISC_STATUS status = isc_start_multiple(status_vector, tra_handle, count, teb); if (teb != tebs) gds__free(teb); return status; } ISC_STATUS API_ROUTINE gds__attach_database(ISC_STATUS* status_vector, SSHORT file_length, const SCHAR* file_name, FB_API_HANDLE* db_handle, SSHORT dpb_length, const SCHAR* dpb) { return isc_attach_database(status_vector, file_length, file_name, db_handle, dpb_length, dpb); } ISC_STATUS API_ROUTINE gds__blob_info(ISC_STATUS* status_vector, FB_API_HANDLE* blob_handle, SSHORT msg_length, const SCHAR* msg, SSHORT buffer_length, SCHAR* buffer) { return isc_blob_info(status_vector, blob_handle, msg_length, msg, buffer_length, buffer); } ISC_STATUS API_ROUTINE gds__cancel_blob(ISC_STATUS* status_vector, FB_API_HANDLE* blob_handle) { return isc_cancel_blob(status_vector, blob_handle); } ISC_STATUS API_ROUTINE gds__cancel_events(ISC_STATUS * status_vector, FB_API_HANDLE* db_handle, SLONG * event_id) { return isc_cancel_events(status_vector, db_handle, event_id); } ISC_STATUS API_ROUTINE gds__close_blob(ISC_STATUS* status_vector, FB_API_HANDLE* blob_handle) { return isc_close_blob(status_vector, blob_handle); } ISC_STATUS API_ROUTINE gds__commit_retaining(ISC_STATUS* status_vector, FB_API_HANDLE* tra_handle) { return isc_commit_retaining(status_vector, tra_handle); } ISC_STATUS API_ROUTINE gds__commit_transaction(ISC_STATUS* status_vector, FB_API_HANDLE *tra_handle) { return isc_commit_transaction(status_vector, tra_handle); } ISC_STATUS API_ROUTINE gds__compile_request(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* req_handle, SSHORT blr_length, const SCHAR* blr) { return isc_compile_request(status_vector, db_handle, req_handle, blr_length, blr); } ISC_STATUS API_ROUTINE gds__compile_request2(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* req_handle, SSHORT blr_length, const SCHAR* blr) { return isc_compile_request2(status_vector, db_handle, req_handle, blr_length, blr); } ISC_STATUS API_ROUTINE gds__create_blob(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, FB_API_HANDLE* blob_handle, GDS_QUAD* blob_id) { return isc_create_blob(status_vector, db_handle, tra_handle, blob_handle, blob_id); } ISC_STATUS API_ROUTINE gds__create_blob2(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, FB_API_HANDLE* blob_handle, GDS_QUAD* blob_id, SSHORT bpb_length, const SCHAR* bpb) { return isc_create_blob2(status_vector, db_handle, tra_handle, blob_handle, blob_id, bpb_length, bpb); } ISC_STATUS API_ROUTINE gds__create_database(ISC_STATUS* status_vector, SSHORT file_length, const SCHAR* file_name, FB_API_HANDLE* db_handle, SSHORT dpb_length, const SCHAR* dpb, SSHORT db_type) { return isc_create_database(status_vector, file_length, file_name, db_handle, dpb_length, dpb, db_type); } ISC_STATUS API_ROUTINE gds__database_cleanup(ISC_STATUS * status_vector, FB_API_HANDLE* db_handle, AttachmentCleanupRoutine *routine, void* arg) { return isc_database_cleanup(status_vector, db_handle, routine, arg); } ISC_STATUS API_ROUTINE gds__database_info(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, SSHORT msg_length, const SCHAR* msg, SSHORT buffer_length, SCHAR* buffer) { return isc_database_info(status_vector, db_handle, msg_length, msg, buffer_length, buffer); } ISC_STATUS API_ROUTINE gds__detach_database(ISC_STATUS * status_vector, FB_API_HANDLE* db_handle) { return isc_detach_database(status_vector, db_handle); } ISC_STATUS API_ROUTINE gds__get_segment(ISC_STATUS* status_vector, FB_API_HANDLE* blob_handle, USHORT * return_length, USHORT buffer_length, SCHAR * buffer) { return isc_get_segment(status_vector, blob_handle, return_length, buffer_length, buffer); } ISC_STATUS API_ROUTINE gds__get_slice(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, GDS_QUAD* array_id, SSHORT sdl_length, const SCHAR* sdl, SSHORT parameters_leng, const SLONG* parameters, SLONG slice_length, void* slice, SLONG* return_length) { return isc_get_slice(status_vector, db_handle, tra_handle, array_id, sdl_length, reinterpret_cast<const UCHAR*>(sdl), parameters_leng, parameters, slice_length, (SCHAR *) slice, return_length); } ISC_STATUS API_ROUTINE gds__open_blob(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, FB_API_HANDLE* blob_handle, GDS_QUAD* blob_id) { return isc_open_blob(status_vector, db_handle, tra_handle, blob_handle, blob_id); } ISC_STATUS API_ROUTINE gds__open_blob2(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, FB_API_HANDLE* blob_handle, GDS_QUAD* blob_id, SSHORT bpb_length, const SCHAR* bpb) { return isc_open_blob2(status_vector, db_handle, tra_handle, blob_handle, blob_id, bpb_length, reinterpret_cast<const UCHAR*>(bpb)); } ISC_STATUS API_ROUTINE gds__prepare_transaction(ISC_STATUS* status_vector, FB_API_HANDLE* tra_handle) { return isc_prepare_transaction(status_vector, tra_handle); } ISC_STATUS API_ROUTINE gds__prepare_transaction2(ISC_STATUS* status_vector, FB_API_HANDLE* tra_handle, SSHORT msg_length, const SCHAR* msg) { return isc_prepare_transaction2(status_vector, tra_handle, msg_length, reinterpret_cast<const UCHAR*>(msg)); } ISC_STATUS API_ROUTINE gds__put_segment(ISC_STATUS* status_vector, FB_API_HANDLE* blob_handle, USHORT segment_length, const SCHAR* segment) { return isc_put_segment(status_vector, blob_handle, segment_length, segment); } ISC_STATUS API_ROUTINE gds__put_slice(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, GDS_QUAD* array_id, SSHORT sdl_length, const SCHAR* sdl, SSHORT parameters_leng, const SLONG* parameters, SLONG slice_length, void* slice) { return isc_put_slice(status_vector, db_handle, tra_handle, array_id, sdl_length, sdl, parameters_leng, parameters, slice_length, reinterpret_cast<SCHAR*>(slice)); } ISC_STATUS API_ROUTINE gds__que_events(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, SLONG* event_id, SSHORT events_length, const UCHAR* events, FPTR_EVENT_CALLBACK ast_address, void* ast_argument) { return isc_que_events(status_vector, db_handle, event_id, events_length, events, ast_address, ast_argument); } ISC_STATUS API_ROUTINE gds__receive(ISC_STATUS * status_vector, FB_API_HANDLE* req_handle, SSHORT msg_type, SSHORT msg_length, void *msg, SSHORT req_level) { return isc_receive(status_vector, req_handle, msg_type, msg_length, (SCHAR*) msg, req_level); } ISC_STATUS API_ROUTINE gds__reconnect_transaction(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, SSHORT msg_length, const SCHAR* msg) { return isc_reconnect_transaction(status_vector, db_handle, tra_handle, msg_length, msg); } ISC_STATUS API_ROUTINE gds__release_request(ISC_STATUS * status_vector, FB_API_HANDLE* req_handle) { return isc_release_request(status_vector, req_handle); } ISC_STATUS API_ROUTINE gds__request_info(ISC_STATUS* status_vector, FB_API_HANDLE* req_handle, SSHORT req_level, SSHORT msg_length, const SCHAR* msg, SSHORT buffer_length, SCHAR* buffer) { return isc_request_info(status_vector, req_handle, req_level, msg_length, msg, buffer_length, buffer); } ISC_STATUS API_ROUTINE gds__rollback_transaction(ISC_STATUS * status_vector, FB_API_HANDLE* tra_handle) { return isc_rollback_transaction(status_vector, tra_handle); } ISC_STATUS API_ROUTINE gds__seek_blob(ISC_STATUS * status_vector, FB_API_HANDLE* blob_handle, SSHORT mode, SLONG offset, SLONG * result) { return isc_seek_blob(status_vector, blob_handle, mode, offset, result); } ISC_STATUS API_ROUTINE gds__send(ISC_STATUS* status_vector, FB_API_HANDLE* req_handle, SSHORT msg_type, SSHORT msg_length, const void* msg, SSHORT req_level) { return isc_send(status_vector, req_handle, msg_type, msg_length, static_cast<const SCHAR*>(msg), req_level); } ISC_STATUS API_ROUTINE gds__start_and_send(ISC_STATUS* status_vector, FB_API_HANDLE* req_handle, FB_API_HANDLE* tra_handle, SSHORT msg_type, SSHORT msg_length, const void* msg, SSHORT req_level) { return isc_start_and_send(status_vector, req_handle, tra_handle, msg_type, msg_length, (const SCHAR*) msg, req_level); } ISC_STATUS API_ROUTINE gds__start_multiple(ISC_STATUS * status_vector, FB_API_HANDLE* tra_handle, SSHORT db_count, void *teb_vector) { return isc_start_multiple(status_vector, tra_handle, db_count, (SCHAR*) teb_vector); } ISC_STATUS API_ROUTINE gds__start_request(ISC_STATUS * status_vector, FB_API_HANDLE* req_handle, FB_API_HANDLE* tra_handle, SSHORT req_level) { return isc_start_request(status_vector, req_handle, tra_handle, req_level); } ISC_STATUS API_ROUTINE gds__transaction_info(ISC_STATUS* status_vector, FB_API_HANDLE* tra_handle, SSHORT msg_length, const SCHAR* msg, SSHORT buffer_length, SCHAR* buffer) { return isc_transaction_info(status_vector, tra_handle, msg_length, msg, buffer_length, buffer); } ISC_STATUS API_ROUTINE gds__unwind_request(ISC_STATUS * status_vector, FB_API_HANDLE* req_handle, SSHORT req_level) { return isc_unwind_request(status_vector, req_handle, req_level); } ISC_STATUS API_ROUTINE gds__ddl(ISC_STATUS* status_vector, FB_API_HANDLE* db_handle, FB_API_HANDLE* tra_handle, SSHORT ddl_length, const SCHAR* ddl) { return isc_ddl(status_vector, db_handle, tra_handle, ddl_length, ddl); } void API_ROUTINE gds__event_counts(ULONG* result_vector, SSHORT length, UCHAR* before, const UCHAR* after) { isc_event_counts(result_vector, length, before, after); } SLONG API_ROUTINE isc_free(SCHAR * blk) { return gds__free(blk); } SLONG API_ROUTINE isc_ftof(const SCHAR* string1, const USHORT length1, SCHAR* string2, const USHORT length2) { return gds__ftof(string1, length1, string2, length2); } void API_ROUTINE gds__get_client_version(SCHAR * buffer) { isc_get_client_version(buffer); } int API_ROUTINE gds__get_client_major_version() { return isc_get_client_major_version(); } int API_ROUTINE gds__get_client_minor_version() { return isc_get_client_minor_version(); } ISC_STATUS API_ROUTINE isc_print_blr(const SCHAR* blr, FPTR_PRINT_CALLBACK callback, void* callback_argument, SSHORT language) { return gds__print_blr(reinterpret_cast<const UCHAR*>(blr), callback, callback_argument, language); } ISC_STATUS API_ROUTINE isc_print_status(const ISC_STATUS* status_vector) { return gds__print_status(status_vector); } void API_ROUTINE isc_qtoq(const GDS_QUAD* quad1, GDS_QUAD* quad2) { gds__qtoq(quad1, quad2); } SLONG API_ROUTINE isc_sqlcode(const ISC_STATUS* status_vector) { return gds__sqlcode(status_vector); } void API_ROUTINE isc_sqlcode_s(const ISC_STATUS* status_vector, ULONG * sqlcode) { *sqlcode = gds__sqlcode(status_vector); return; } void API_ROUTINE isc_vtof(const SCHAR* string1, SCHAR* string2, USHORT length) { gds__vtof(string1, string2, length); } void API_ROUTINE isc_vtov(const SCHAR* string1, SCHAR* string2, SSHORT length) { gds__vtov(string1, string2, length); } void API_ROUTINE gds__decode_date(const GDS_QUAD* date, void* time_structure) { isc_decode_date(date, time_structure); } void API_ROUTINE gds__encode_date(const void* time_structure, GDS_QUAD* date) { isc_encode_date(time_structure, date); } SLONG API_ROUTINE isc_vax_integer(const SCHAR* input, SSHORT length) { return gds__vax_integer(reinterpret_cast<const UCHAR*>(input), length); } ISC_STATUS API_ROUTINE gds__event_wait(ISC_STATUS * status_vector, FB_API_HANDLE* db_handle, SSHORT events_length, const UCHAR* events, UCHAR* events_update) { return isc_wait_for_event(status_vector, db_handle, events_length, events, events_update); } // CVC: This non-const signature is needed for compatibility, see gds.cpp. SLONG API_ROUTINE isc_interprete(SCHAR* buffer, ISC_STATUS** status_vector_p) { return gds__interprete(buffer, status_vector_p); } int API_ROUTINE gds__version(FB_API_HANDLE* db_handle, FPTR_VERSION_CALLBACK callback, void* callback_argument) { return isc_version(db_handle, callback, callback_argument); } void API_ROUTINE gds__set_debug(int flag) { isc_set_debug(flag); } int API_ROUTINE isc_blob_display(ISC_STATUS* status_vector, ISC_QUAD* blob_id, FB_API_HANDLE* database, FB_API_HANDLE* transaction, const SCHAR* field_name, const SSHORT* name_length) { /************************************** * * i s c _ b l o b _ d i s p l a y * ************************************** * * Functional description * PASCAL callable version of EDIT_blob. * **************************************/ if (status_vector) status_vector[1] = 0; return blob__display((SLONG *) blob_id, database, transaction, field_name, name_length); } int API_ROUTINE isc_blob_dump(ISC_STATUS* status_vector, ISC_QUAD* blob_id, FB_API_HANDLE* database, FB_API_HANDLE* transaction, const SCHAR* file_name, const SSHORT* name_length) { /************************************** * * i s c _ b l o b _ d u m p * ************************************** * * Functional description * Translate a pascal callable dump * into an internal dump call. * **************************************/ if (status_vector) status_vector[1] = 0; return blob__dump((SLONG *) blob_id, database, transaction, file_name, name_length); } int API_ROUTINE isc_blob_edit(ISC_STATUS* status_vector, ISC_QUAD* blob_id, FB_API_HANDLE* database, FB_API_HANDLE* transaction, const SCHAR* field_name, const SSHORT* name_length) { /************************************** * * b l o b _ $ e d i t * ************************************** * * Functional description * Translate a pascal callable edit * into an internal edit call. * **************************************/ if (status_vector) status_vector[1] = 0; return blob__edit((SLONG*) blob_id, database, transaction, field_name, name_length); } int API_ROUTINE isc_blob_load(ISC_STATUS* status_vector, ISC_QUAD* blob_id, FB_API_HANDLE* database, FB_API_HANDLE* transaction, const SCHAR* file_name, const SSHORT* name_length) { /************************************** * * i s c _ b l o b _ l o a d * ************************************** * * Functional description * Translate a pascal callable load * into an internal load call. * **************************************/ if (status_vector) status_vector[1] = 0; return blob__load((SLONG *) blob_id, database, transaction, file_name, name_length); } void API_ROUTINE CVT_move(const dsc*, dsc*, FPTR_ERROR err) // I believe noone could use this private API in his routines. // This requires knowledge about our descriptors, which are hardly usable // outside Firebird, AP-2008. { err(isc_random, isc_arg_string, "CVT_move() private API not supported any more", isc_arg_end); } namespace { ISC_STATUS user_error(ISC_STATUS* vector, ISC_STATUS code) { vector[0] = isc_arg_gds; vector[1] = code; vector[2] = isc_arg_end; return vector[1]; } } namespace { template <typename T1, typename T2> void copyField(T1& f, T2 from, short flag) { Firebird::LocalStatus s; Firebird::CheckStatusWrapper statusWrapper(&s); if (flag && from) { f.set(&statusWrapper, from); check(&statusWrapper); f.setEntered(&statusWrapper, 1); check(&statusWrapper); } else { f.setEntered(&statusWrapper, 0); check(&statusWrapper); } } } // anonymous namespace ISC_STATUS API_ROUTINE isc_add_user(ISC_STATUS* status, const USER_SEC_DATA* input_user_data) { /************************************** * * i s c _ a d d _ u s e r * ************************************** * * Functional description * Adds a user to the server's security * database. * Return 0 if the user was added * * Return > 0 if any error occurs. * **************************************/ Auth::StackUserData userInfo; userInfo.op = Auth::ADD_OPER; Firebird::LocalStatus s; Firebird::CheckStatusWrapper statusWrapper(&s); if (input_user_data->user_name) { Firebird::string work = input_user_data->user_name; if (work.length() > USERNAME_LENGTH) { return user_error(status, isc_usrname_too_long); } Firebird::string::size_type l = work.find(' '); if (l != Firebird::string::npos) { work.resize(l); } userInfo.user.set(&statusWrapper, work.c_str()); Firebird::check(&statusWrapper); userInfo.user.setEntered(&statusWrapper, 1); Firebird::check(&statusWrapper); } else { return user_error(status, isc_usrname_required); } if (input_user_data->password) { userInfo.pass.set(&statusWrapper, input_user_data->password); Firebird::check(&statusWrapper); userInfo.pass.setEntered(&statusWrapper, 1); Firebird::check(&statusWrapper); } else { return user_error(status, isc_password_required); } copyField(userInfo.u, input_user_data->uid, input_user_data->sec_flags & sec_uid_spec); copyField(userInfo.g, input_user_data->gid, input_user_data->sec_flags & sec_gid_spec); copyField(userInfo.group, input_user_data->group_name, input_user_data->sec_flags & sec_group_name_spec); copyField(userInfo.first, input_user_data->first_name, input_user_data->sec_flags & sec_first_name_spec); copyField(userInfo.middle, input_user_data->middle_name, input_user_data->sec_flags & sec_middle_name_spec); copyField(userInfo.last, input_user_data->last_name, input_user_data->sec_flags & sec_last_name_spec); return executeSecurityCommand(status, input_user_data, userInfo); } ISC_STATUS API_ROUTINE isc_delete_user(ISC_STATUS* status, const USER_SEC_DATA* input_user_data) { /************************************** * * i s c _ d e l e t e _ u s e r * ************************************** * * Functional description * Deletes a user from the server's security * database. * Return 0 if the user was deleted * * Return > 0 if any error occurs. * **************************************/ Auth::StackUserData userInfo; userInfo.op = Auth::DEL_OPER; Firebird::LocalStatus s; Firebird::CheckStatusWrapper statusWrapper(&s); if (input_user_data->user_name) { Firebird::string work = input_user_data->user_name; if (work.length() > USERNAME_LENGTH) { return user_error(status, isc_usrname_too_long); } Firebird::string::size_type l = work.find(' '); if (l != Firebird::string::npos) { work.resize(l); } userInfo.user.set(&statusWrapper, work.c_str()); Firebird::check(&statusWrapper); userInfo.user.setEntered(&statusWrapper, 1); Firebird::check(&statusWrapper); } else { return user_error(status, isc_usrname_required); } return executeSecurityCommand(status, input_user_data, userInfo); } ISC_STATUS API_ROUTINE isc_modify_user(ISC_STATUS* status, const USER_SEC_DATA* input_user_data) { /************************************** * * i s c _ m o d i f y _ u s e r * ************************************** * * Functional description * Adds a user to the server's security * database. * Return 0 if the user was added * * Return > 0 if any error occurs. * **************************************/ Auth::StackUserData userInfo; userInfo.op = Auth::MOD_OPER; Firebird::LocalStatus s; Firebird::CheckStatusWrapper statusWrapper(&s); if (input_user_data->user_name) { Firebird::string work = input_user_data->user_name; if (work.length() > USERNAME_LENGTH) { return user_error(status, isc_usrname_too_long); } Firebird::string::size_type l = work.find(' '); if (l != Firebird::string::npos) { work.resize(l); } userInfo.user.set(&statusWrapper, work.c_str()); check(&statusWrapper); userInfo.user.setEntered(&statusWrapper, 1); check(&statusWrapper); } else { return user_error(status, isc_usrname_required); } if (input_user_data->password) { userInfo.pass.set(&statusWrapper, input_user_data->password); check(&statusWrapper); userInfo.pass.setEntered(&statusWrapper, 1); check(&statusWrapper); } else { return user_error(status, isc_password_required); } copyField(userInfo.u, input_user_data->uid, input_user_data->sec_flags & sec_uid_spec); copyField(userInfo.g, input_user_data->gid, input_user_data->sec_flags & sec_gid_spec); copyField(userInfo.group, input_user_data->group_name, input_user_data->sec_flags & sec_group_name_spec); copyField(userInfo.first, input_user_data->first_name, input_user_data->sec_flags & sec_first_name_spec); copyField(userInfo.middle, input_user_data->middle_name, input_user_data->sec_flags & sec_middle_name_spec); copyField(userInfo.last, input_user_data->last_name, input_user_data->sec_flags & sec_last_name_spec); return executeSecurityCommand(status, input_user_data, userInfo); } static ISC_STATUS executeSecurityCommand(ISC_STATUS* status, const USER_SEC_DATA* input_user_data, Auth::UserData& userInfo ) { /************************************** * * e x e c u t e S e c u r i t y C o m m a n d * ************************************** * * Functional description * * Executes command according to input_user_data * and userInfo. Calls service manager to do job. **************************************/ isc_svc_handle handle = attachRemoteServiceManager(status, input_user_data->dba_user_name, input_user_data->dba_password, false, input_user_data->protocol, input_user_data->server); if (handle) { callRemoteServiceManager(status, handle, userInfo, NULL); makePermanentVector(status); ISC_STATUS_ARRAY user_status; detachRemoteServiceManager(user_status, handle); } return status[1]; }
28.435071
109
0.679756
[ "vector" ]
427187a8512070a2945a21aaa73153c7fd1283a4
7,981
hh
C++
src/ExecutableFormats/PEFFFile.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
1
2018-03-20T13:06:16.000Z
2018-03-20T13:06:16.000Z
src/ExecutableFormats/PEFFFile.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
null
null
null
src/ExecutableFormats/PEFFFile.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
null
null
null
#pragma once #include <inttypes.h> #include <map> #include <phosg/Encoding.hh> #include <memory> #include <vector> #include "../Emulators/MemoryContext.hh" //////////////////////////////////////////////////////////////////////////////// // Overall structure // PEFF files have, in this order: // - PEFFHeader // - PEFFSectionHeader[PEFFHeader.section_count] // - Section name table // - Section contents struct PEFFHeader { be_uint32_t magic1; // 'Joy!' be_uint32_t magic2; // 'peff' be_uint32_t arch; // 'pwpc' or 'm68k' be_uint32_t format_version; be_uint32_t timestamp; be_uint32_t old_def_version; be_uint32_t old_imp_version; be_uint32_t current_version; be_uint16_t section_count; // total section count be_uint16_t inst_section_count; // sections required for execution be_uint32_t reserved; } __attribute__((packed)); enum class PEFFSectionKind { EXECUTABLE_READONLY = 0, // uncompressed, read-only, executable UNPACKED_DATA = 1, // uncompressed, read/write, followed by zeroes if needed PATTERN_DATA = 2, CONSTANT = 3, // uncompressed, read-only, non-executable LOADER = 4, // imports, exports, entry points DEBUG_RESERVED = 5, // reserved EXECUTABLE_READWRITE = 6, // uncompressed (?), read/write, executable EXCEPTION_RESERVED = 7, // reserved TRACEBACK_RESERVED = 8, // reserved }; const char* name_for_section_kind(PEFFSectionKind k); enum PEFFShareKind { PROCESS = 1, // shared within each process, copied for other processes GLOBAL = 4, // shared with all processes PROTECTED = 5, // shared with all processes, read-only unless privileged mode }; const char* name_for_share_kind(PEFFShareKind k); struct PEFFSectionHeader { be_int32_t name_offset; // -1 = no name be_uint32_t default_address; be_uint32_t total_size; be_uint32_t unpacked_size; be_uint32_t packed_size; be_uint32_t container_offset; uint8_t section_kind; // PEFFSectionKind enum uint8_t share_kind; uint8_t alignment; uint8_t reserved; } __attribute__((packed)); //////////////////////////////////////////////////////////////////////////////// // Loader section structure // The loader section has, in this order: // - PEFFLoaderSectionHeader // - PEFFLoaderImportLibrary[header.imported_lib_count] // - PEFFLoaderImportSymbol[header.imported_symbol_count] // - PEFFLoaderRelocationHeader[header.rel_section_count] // - Relocations // - String table // - Export hash table // - Export key table // - Exported symbol table struct PEFFLoaderSectionHeader { be_int32_t main_symbol_section_index; // -1 if no main symbol be_uint32_t main_symbol_offset; // offset within the section be_int32_t init_symbol_section_index; // -1 if no init symbol be_uint32_t init_symbol_offset; // offset within the section be_int32_t term_symbol_section_index; // -1 if no term symbol be_uint32_t term_symbol_offset; // offset within the section be_uint32_t imported_lib_count; be_uint32_t imported_symbol_count; be_uint32_t rel_section_count; // number of sections containing relocations be_uint32_t rel_commands_offset; // from beginning of loader section be_uint32_t string_table_offset; // from beginning of loader section be_uint32_t export_hash_offset; // from beginning of loader section be_uint32_t export_hash_power; // number of entries is 2^export_hash_power be_uint32_t exported_symbol_count; } __attribute__((packed)); enum PEFFImportLibraryFlags { // If library not found, don't fail - just set all import addrs to zero WEAK_IMPORT = 0x40, // Library must be initialized before the client fragment EARLY_INIT_REQUIRED = 0x80, }; struct PEFFLoaderImportLibrary { be_uint32_t name_offset; // from beginning of loader string table be_uint32_t old_imp_version; be_uint32_t current_version; be_uint32_t imported_symbol_count; // number of symbols imported from this lib be_uint32_t start_index; // first import's index in imported symbol table uint8_t options; // bits in PEFFImportLibraryFlags uint8_t reserved1; be_uint16_t reserved2; } __attribute__((packed)); enum PEFFLoaderImportSymbolType { CODE = 0, DATA = 1, TVECT = 2, TOC = 3, GLUE = 4, }; enum PEFFLoaderImportSymbolFlags { WEAK = 0x80, }; struct PEFFLoaderImportSymbol { be_uint32_t u; inline uint8_t flags() const { return (this->u >> 28) & 0x0F; } inline uint8_t type() const { return (this->u >> 24) & 0x0F; } inline uint32_t name_offset() const { return this->u & 0x00FFFFFF; } } __attribute__((packed)); struct PEFFLoaderRelocationHeader { be_uint16_t section_index; be_uint16_t reserved; // Some relocation commands are multiple words, so this isn't necessarily the // same as the command count be_uint32_t word_count; be_uint32_t start_offset; } __attribute__((packed)); struct PEFFLoaderExportHashEntry { be_uint32_t u; inline uint16_t chain_count() const { return (this->u >> 18) & 0x3FFF; } inline uint16_t start_index() const { return this->u & 0x3FFFF; } } __attribute__((packed)); struct PEFFLoaderExportHashKey { be_uint16_t symbol_length; be_uint16_t hash; } __attribute__((packed)); struct PEFFLoaderExportSymbol { be_uint32_t type_and_name; be_uint32_t value; // usually offset from section start be_uint16_t section_index; inline uint8_t flags() const { return (this->type_and_name >> 28) & 0x0F; } inline uint8_t type() const { return (this->type_and_name >> 24) & 0x0F; } inline uint32_t name_offset() const { return this->type_and_name & 0x00FFFFFF; } } __attribute__((packed)); class PEFFFile { public: explicit PEFFFile(const char* filename); PEFFFile(const char* filename, const std::string& data); PEFFFile(const char* filename, const void* data, size_t size); ~PEFFFile() = default; void print(FILE* stream, const std::multimap<uint32_t, std::string>* labels = nullptr) const; void load_into(const std::string& lib_name, std::shared_ptr<MemoryContext> mem, uint32_t base_addr = 0); struct ExportSymbol { std::string name; uint16_t section_index; uint32_t value; uint8_t flags; uint8_t type; void print(FILE* stream) const; }; struct ImportSymbol { std::string lib_name; std::string name; uint8_t flags; uint8_t type; void print(FILE* stream) const; }; inline const std::map<std::string, ExportSymbol> exports() const { return this->export_symbols; } inline const std::vector<ImportSymbol> imports() const { return this->import_symbols; } inline const ExportSymbol& main() const { return this->main_symbol; } inline const ExportSymbol& init() const { return this->init_symbol; } inline const ExportSymbol& term() const { return this->term_symbol; } inline bool is_ppc() const { return this->arch_is_ppc; } private: void parse(const void* data, size_t size); void parse_loader_section(const void* data, size_t size); const std::string filename; struct Section { std::string name; uint32_t default_address; uint32_t total_size; uint32_t unpacked_size; uint32_t packed_size; PEFFSectionKind section_kind; PEFFShareKind share_kind; uint8_t alignment; std::string data; std::string relocation_program; }; uint32_t file_timestamp; uint32_t old_def_version; uint32_t old_imp_version; uint32_t current_version; bool arch_is_ppc; // If the name is blank for any of these, they aren't exported ExportSymbol main_symbol; ExportSymbol init_symbol; ExportSymbol term_symbol; std::vector<Section> sections; std::map<std::string, ExportSymbol> export_symbols; std::vector<ImportSymbol> import_symbols; };
28.812274
96
0.697156
[ "vector" ]
42749b72f7585a28df0fffe92d73d1d47e06c41c
1,706
hpp
C++
inc/map.hpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
7
2019-05-18T06:59:03.000Z
2020-08-01T01:50:55.000Z
inc/map.hpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
null
null
null
inc/map.hpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
null
null
null
// Copyright 2019 Dave Moore // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. struct Tile { bool explored; // has the player already seen this tile ? Tile() : explored(false) {} }; class Map { public : int width,height; Map(int width, int height); ~Map(); bool isWall(int x, int y) const; bool isInFov(int x, int y) const; bool isExplored(int x, int y) const; void computeFov(); void render() const; protected : Tile *tiles; TCODMap *map; friend class BspListener; void dig(int x1, int y1, int x2, int y2); void createRoom(bool first, int x1, int y1, int x2, int y2); private: const int offsetx = 82; const int offsety = 1; };
37.911111
120
0.722157
[ "render" ]
4277a3627e81ffc9f1aa045cd1a53f5232524618
4,648
cpp
C++
src/spectrast/SpectraSTSearchOutput.cpp
lkszmn/spectrast
f028aafcea5045e3cb5837c337f4fa90c90993f3
[ "Zlib", "MIT" ]
null
null
null
src/spectrast/SpectraSTSearchOutput.cpp
lkszmn/spectrast
f028aafcea5045e3cb5837c337f4fa90c90993f3
[ "Zlib", "MIT" ]
null
null
null
src/spectrast/SpectraSTSearchOutput.cpp
lkszmn/spectrast
f028aafcea5045e3cb5837c337f4fa90c90993f3
[ "Zlib", "MIT" ]
3
2019-10-30T13:08:05.000Z
2022-02-22T19:16:31.000Z
#include "SpectraSTSearchOutput.hpp" #include "SpectraSTTxtSearchOutput.hpp" #include "SpectraSTXlsSearchOutput.hpp" #include "SpectraSTPepXMLSearchOutput.hpp" #include "SpectraSTHtmlSearchOutput.hpp" #include "SpectraSTLog.hpp" #include "FileUtils.hpp" #include <iostream> /* Program : Spectrast Author : Henry Lam <hlam@systemsbiology.org> Date : 03.06.06 Copyright (C) 2006 Henry Lam This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA Henry Lam Institute for Systems Biology 401 Terry Avenue North Seattle, WA 98109 USA hlam@systemsbiology.org */ /* Class: SpectraSTSearchOutput * * Abstract base class for an outputter. Subclass for different output formats. * */ extern SpectraSTLog* g_log; // constructor SpectraSTSearchOutput::SpectraSTSearchOutput(string outputFileName, string searchFileExt, SpectraSTSearchParams& searchParams) : m_outputFileName(outputFileName), m_fout(NULL), m_searchFileExt(searchFileExt), m_searchParams(searchParams), m_instrInfo(NULL), m_query("") { getPath(outputFileName, m_outputPath); // don't open the files yet, wait until it is needed -- when OpenFile() is called. } // destructor SpectraSTSearchOutput::~SpectraSTSearchOutput() { if (m_instrInfo) { delete (m_instrInfo); } if (m_fout) { delete (m_fout); } } // openFile - opens the file for output void SpectraSTSearchOutput::openFile() { if (m_fout) return; // already open m_fout = new ofstream(); if (!myFileOpen(*m_fout, m_outputFileName)) { g_log->error("SEARCH", "Cannot open file \"" + m_outputFileName + "\" for writing search results. Exiting."); g_log->crash(); } } // closeFile - closes the file for output void SpectraSTSearchOutput::closeFile() { if (m_fout) { delete (m_fout); m_fout = NULL; } } string SpectraSTSearchOutput::getOutputFileName() { return (m_outputFileName); } string SpectraSTSearchOutput::getOutputPath() { return (m_outputPath); } // createSpectraSTSearchOutput - "factory" to create proper output object for different formats. Modify this if you implement // a new outputter! SpectraSTSearchOutput* SpectraSTSearchOutput::createSpectraSTSearchOutput(string searchFileName, SpectraSTSearchParams& searchParams) { FileName fn; parseFileName(searchFileName, fn); string outputDirectory(fn.path); if (!(searchParams.outputDirectory.empty())) { outputDirectory = searchParams.outputDirectory; } string ext(searchParams.outputExtension); if (ext == "nxls") ext = "xls"; if (ext == "ntxt") ext = "txt"; string outputFileName(outputDirectory + fn.name + "." + ext); makeFullPath(outputFileName); /* if (searchParams.saveSpectra) { makeDir(outputDirectory + fn.name + ".match/"); makeDir(outputDirectory + fn.name + ".query/"); } */ if (searchParams.outputExtension == "txt") { return (new SpectraSTTxtSearchOutput(outputFileName, fn.ext, searchParams)); } else if (searchParams.outputExtension == "ntxt") { return (new SpectraSTTxtSearchOutput(outputFileName, fn.ext, searchParams, false)); } else if (searchParams.outputExtension == "xls") { return (new SpectraSTXlsSearchOutput(outputFileName, fn.ext, searchParams)); } else if (searchParams.outputExtension == "nxls") { return (new SpectraSTXlsSearchOutput(outputFileName, fn.ext, searchParams, false)); } else if (searchParams.outputExtension == "xml" || searchParams.outputExtension == "pepXML" || searchParams.outputExtension == "pep.xml") { return (new SpectraSTPepXMLSearchOutput(outputFileName, fn.ext, searchParams, fn.path)); } else if (searchParams.outputExtension == "html") { return (new SpectraSTHtmlSearchOutput(outputFileName, fn.ext, searchParams)); } else { // unknown output type. should never happen. return (new SpectraSTPepXMLSearchOutput(outputFileName, fn.ext, searchParams, fn.path)); } return (new SpectraSTPepXMLSearchOutput(outputFileName, fn.ext, searchParams, fn.path)); }
30.379085
142
0.736661
[ "object" ]
427b8217456c165f4ba8884fbb689043bb76ccbd
330,388
cc
C++
deps/v8/src/runtime/runtime.cc
vblanca/vbl
e7dec60a63b9171465fd4037a04aeb709198aea2
[ "Artistic-2.0" ]
1
2019-04-15T16:35:15.000Z
2019-04-15T16:35:15.000Z
deps/v8/src/runtime/runtime.cc
vblanca/vbl
e7dec60a63b9171465fd4037a04aeb709198aea2
[ "Artistic-2.0" ]
null
null
null
deps/v8/src/runtime/runtime.cc
vblanca/vbl
e7dec60a63b9171465fd4037a04aeb709198aea2
[ "Artistic-2.0" ]
null
null
null
// Copyright 2012 the V8 project 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 <stdlib.h> #include <limits> #include "src/v8.h" #include "src/accessors.h" #include "src/allocation-site-scopes.h" #include "src/api.h" #include "src/arguments.h" #include "src/bailout-reason.h" #include "src/base/cpu.h" #include "src/base/platform/platform.h" #include "src/bootstrapper.h" #include "src/codegen.h" #include "src/compilation-cache.h" #include "src/compiler.h" #include "src/conversions.h" #include "src/cpu-profiler.h" #include "src/date.h" #include "src/dateparser-inl.h" #include "src/debug.h" #include "src/deoptimizer.h" #include "src/execution.h" #include "src/full-codegen.h" #include "src/global-handles.h" #include "src/isolate-inl.h" #include "src/liveedit.h" #include "src/misc-intrinsics.h" #include "src/parser.h" #include "src/prototype.h" #include "src/runtime/runtime.h" #include "src/runtime/runtime-utils.h" #include "src/runtime-profiler.h" #include "src/scopeinfo.h" #include "src/smart-pointers.h" #include "src/utils.h" #include "src/v8threads.h" #include "src/vm-state-inl.h" namespace v8 { namespace internal { // Header of runtime functions. #define F(name, number_of_args, result_size) \ Object* Runtime_##name(int args_length, Object** args_object, \ Isolate* isolate); #define P(name, number_of_args, result_size) \ ObjectPair Runtime_##name(int args_length, Object** args_object, \ Isolate* isolate); #define I(name, number_of_args, result_size) \ Object* RuntimeReference_##name(int args_length, Object** args_object, \ Isolate* isolate); RUNTIME_FUNCTION_LIST_RETURN_OBJECT(F) RUNTIME_FUNCTION_LIST_RETURN_PAIR(P) INLINE_OPTIMIZED_FUNCTION_LIST(F) INLINE_FUNCTION_LIST(I) #undef I #undef F #undef P static Handle<Map> ComputeObjectLiteralMap( Handle<Context> context, Handle<FixedArray> constant_properties, bool* is_result_from_cache) { Isolate* isolate = context->GetIsolate(); int properties_length = constant_properties->length(); int number_of_properties = properties_length / 2; // Check that there are only internal strings and array indices among keys. int number_of_string_keys = 0; for (int p = 0; p != properties_length; p += 2) { Object* key = constant_properties->get(p); uint32_t element_index = 0; if (key->IsInternalizedString()) { number_of_string_keys++; } else if (key->ToArrayIndex(&element_index)) { // An index key does not require space in the property backing store. number_of_properties--; } else { // Bail out as a non-internalized-string non-index key makes caching // impossible. // DCHECK to make sure that the if condition after the loop is false. DCHECK(number_of_string_keys != number_of_properties); break; } } // If we only have internalized strings and array indices among keys then we // can use the map cache in the native context. const int kMaxKeys = 10; if ((number_of_string_keys == number_of_properties) && (number_of_string_keys < kMaxKeys)) { // Create the fixed array with the key. Handle<FixedArray> keys = isolate->factory()->NewFixedArray(number_of_string_keys); if (number_of_string_keys > 0) { int index = 0; for (int p = 0; p < properties_length; p += 2) { Object* key = constant_properties->get(p); if (key->IsInternalizedString()) { keys->set(index++, key); } } DCHECK(index == number_of_string_keys); } *is_result_from_cache = true; return isolate->factory()->ObjectLiteralMapFromCache(context, keys); } *is_result_from_cache = false; return Map::Create(isolate, number_of_properties); } MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate( Isolate* isolate, Handle<FixedArray> literals, Handle<FixedArray> constant_properties); MUST_USE_RESULT static MaybeHandle<Object> CreateObjectLiteralBoilerplate( Isolate* isolate, Handle<FixedArray> literals, Handle<FixedArray> constant_properties, bool should_have_fast_elements, bool has_function_literal) { // Get the native context from the literals array. This is the // context in which the function was created and we use the object // function from this context to create the object literal. We do // not use the object function from the current native context // because this might be the object function from another context // which we should not have access to. Handle<Context> context = Handle<Context>(JSFunction::NativeContextFromLiterals(*literals)); // In case we have function literals, we want the object to be in // slow properties mode for now. We don't go in the map cache because // maps with constant functions can't be shared if the functions are // not the same (which is the common case). bool is_result_from_cache = false; Handle<Map> map = has_function_literal ? Handle<Map>(context->object_function()->initial_map()) : ComputeObjectLiteralMap(context, constant_properties, &is_result_from_cache); PretenureFlag pretenure_flag = isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED; Handle<JSObject> boilerplate = isolate->factory()->NewJSObjectFromMap(map, pretenure_flag); // Normalize the elements of the boilerplate to save space if needed. if (!should_have_fast_elements) JSObject::NormalizeElements(boilerplate); // Add the constant properties to the boilerplate. int length = constant_properties->length(); bool should_transform = !is_result_from_cache && boilerplate->HasFastProperties(); bool should_normalize = should_transform || has_function_literal; if (should_normalize) { // TODO(verwaest): We might not want to ever normalize here. JSObject::NormalizeProperties(boilerplate, KEEP_INOBJECT_PROPERTIES, length / 2); } // TODO(verwaest): Support tracking representations in the boilerplate. for (int index = 0; index < length; index += 2) { Handle<Object> key(constant_properties->get(index + 0), isolate); Handle<Object> value(constant_properties->get(index + 1), isolate); if (value->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle<FixedArray> array = Handle<FixedArray>::cast(value); ASSIGN_RETURN_ON_EXCEPTION( isolate, value, CreateLiteralBoilerplate(isolate, literals, array), Object); } MaybeHandle<Object> maybe_result; uint32_t element_index = 0; if (key->IsInternalizedString()) { if (Handle<String>::cast(key)->AsArrayIndex(&element_index)) { // Array index as string (uint32). if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate); maybe_result = JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY); } else { Handle<String> name(String::cast(*key)); DCHECK(!name->AsArrayIndex(&element_index)); maybe_result = JSObject::SetOwnPropertyIgnoreAttributes( boilerplate, name, value, NONE); } } else if (key->ToArrayIndex(&element_index)) { // Array index (uint32). if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate); maybe_result = JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY); } else { // Non-uint32 number. DCHECK(key->IsNumber()); double num = key->Number(); char arr[100]; Vector<char> buffer(arr, arraysize(arr)); const char* str = DoubleToCString(num, buffer); Handle<String> name = isolate->factory()->NewStringFromAsciiChecked(str); maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(boilerplate, name, value, NONE); } // If setting the property on the boilerplate throws an // exception, the exception is converted to an empty handle in // the handle based operations. In that case, we need to // convert back to an exception. RETURN_ON_EXCEPTION(isolate, maybe_result, Object); } // Transform to fast properties if necessary. For object literals with // containing function literals we defer this operation until after all // computed properties have been assigned so that we can generate // constant function properties. if (should_transform && !has_function_literal) { JSObject::MigrateSlowToFast(boilerplate, boilerplate->map()->unused_property_fields()); } return boilerplate; } MUST_USE_RESULT static MaybeHandle<Object> TransitionElements( Handle<Object> object, ElementsKind to_kind, Isolate* isolate) { HandleScope scope(isolate); if (!object->IsJSObject()) { isolate->ThrowIllegalOperation(); return MaybeHandle<Object>(); } ElementsKind from_kind = Handle<JSObject>::cast(object)->map()->elements_kind(); if (Map::IsValidElementsTransition(from_kind, to_kind)) { JSObject::TransitionElementsKind(Handle<JSObject>::cast(object), to_kind); return object; } isolate->ThrowIllegalOperation(); return MaybeHandle<Object>(); } MaybeHandle<Object> Runtime::CreateArrayLiteralBoilerplate( Isolate* isolate, Handle<FixedArray> literals, Handle<FixedArray> elements) { // Create the JSArray. Handle<JSFunction> constructor( JSFunction::NativeContextFromLiterals(*literals)->array_function()); PretenureFlag pretenure_flag = isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED; Handle<JSArray> object = Handle<JSArray>::cast( isolate->factory()->NewJSObject(constructor, pretenure_flag)); ElementsKind constant_elements_kind = static_cast<ElementsKind>(Smi::cast(elements->get(0))->value()); Handle<FixedArrayBase> constant_elements_values( FixedArrayBase::cast(elements->get(1))); { DisallowHeapAllocation no_gc; DCHECK(IsFastElementsKind(constant_elements_kind)); Context* native_context = isolate->context()->native_context(); Object* maps_array = native_context->js_array_maps(); DCHECK(!maps_array->IsUndefined()); Object* map = FixedArray::cast(maps_array)->get(constant_elements_kind); object->set_map(Map::cast(map)); } Handle<FixedArrayBase> copied_elements_values; if (IsFastDoubleElementsKind(constant_elements_kind)) { copied_elements_values = isolate->factory()->CopyFixedDoubleArray( Handle<FixedDoubleArray>::cast(constant_elements_values)); } else { DCHECK(IsFastSmiOrObjectElementsKind(constant_elements_kind)); const bool is_cow = (constant_elements_values->map() == isolate->heap()->fixed_cow_array_map()); if (is_cow) { copied_elements_values = constant_elements_values; #if DEBUG Handle<FixedArray> fixed_array_values = Handle<FixedArray>::cast(copied_elements_values); for (int i = 0; i < fixed_array_values->length(); i++) { DCHECK(!fixed_array_values->get(i)->IsFixedArray()); } #endif } else { Handle<FixedArray> fixed_array_values = Handle<FixedArray>::cast(constant_elements_values); Handle<FixedArray> fixed_array_values_copy = isolate->factory()->CopyFixedArray(fixed_array_values); copied_elements_values = fixed_array_values_copy; for (int i = 0; i < fixed_array_values->length(); i++) { if (fixed_array_values->get(i)->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle<FixedArray> fa(FixedArray::cast(fixed_array_values->get(i))); Handle<Object> result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, CreateLiteralBoilerplate(isolate, literals, fa), Object); fixed_array_values_copy->set(i, *result); } } } } object->set_elements(*copied_elements_values); object->set_length(Smi::FromInt(copied_elements_values->length())); JSObject::ValidateElements(object); return object; } MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate( Isolate* isolate, Handle<FixedArray> literals, Handle<FixedArray> array) { Handle<FixedArray> elements = CompileTimeValue::GetElements(array); const bool kHasNoFunctionLiteral = false; switch (CompileTimeValue::GetLiteralType(array)) { case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, true, kHasNoFunctionLiteral); case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, false, kHasNoFunctionLiteral); case CompileTimeValue::ARRAY_LITERAL: return Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements); default: UNREACHABLE(); return MaybeHandle<Object>(); } } RUNTIME_FUNCTION(Runtime_CreateObjectLiteral) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0; bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0; RUNTIME_ASSERT(literals_index >= 0 && literals_index < literals->length()); // Check if boilerplate exists. If not, create it first. Handle<Object> literal_site(literals->get(literals_index), isolate); Handle<AllocationSite> site; Handle<JSObject> boilerplate; if (*literal_site == isolate->heap()->undefined_value()) { Handle<Object> raw_boilerplate; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, raw_boilerplate, CreateObjectLiteralBoilerplate(isolate, literals, constant_properties, should_have_fast_elements, has_function_literal)); boilerplate = Handle<JSObject>::cast(raw_boilerplate); AllocationSiteCreationContext creation_context(isolate); site = creation_context.EnterNewScope(); RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::DeepWalk(boilerplate, &creation_context)); creation_context.ExitScope(site, boilerplate); // Update the functions literal and return the boilerplate. literals->set(literals_index, *site); } else { site = Handle<AllocationSite>::cast(literal_site); boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()), isolate); } AllocationSiteUsageContext usage_context(isolate, site, true); usage_context.EnterNewScope(); MaybeHandle<Object> maybe_copy = JSObject::DeepCopy(boilerplate, &usage_context); usage_context.ExitScope(site, boilerplate); Handle<Object> copy; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, copy, maybe_copy); return *copy; } MUST_USE_RESULT static MaybeHandle<AllocationSite> GetLiteralAllocationSite( Isolate* isolate, Handle<FixedArray> literals, int literals_index, Handle<FixedArray> elements) { // Check if boilerplate exists. If not, create it first. Handle<Object> literal_site(literals->get(literals_index), isolate); Handle<AllocationSite> site; if (*literal_site == isolate->heap()->undefined_value()) { DCHECK(*elements != isolate->heap()->empty_fixed_array()); Handle<Object> boilerplate; ASSIGN_RETURN_ON_EXCEPTION( isolate, boilerplate, Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements), AllocationSite); AllocationSiteCreationContext creation_context(isolate); site = creation_context.EnterNewScope(); if (JSObject::DeepWalk(Handle<JSObject>::cast(boilerplate), &creation_context).is_null()) { return Handle<AllocationSite>::null(); } creation_context.ExitScope(site, Handle<JSObject>::cast(boilerplate)); literals->set(literals_index, *site); } else { site = Handle<AllocationSite>::cast(literal_site); } return site; } static MaybeHandle<JSObject> CreateArrayLiteralImpl(Isolate* isolate, Handle<FixedArray> literals, int literals_index, Handle<FixedArray> elements, int flags) { RUNTIME_ASSERT_HANDLIFIED( literals_index >= 0 && literals_index < literals->length(), JSObject); Handle<AllocationSite> site; ASSIGN_RETURN_ON_EXCEPTION( isolate, site, GetLiteralAllocationSite(isolate, literals, literals_index, elements), JSObject); bool enable_mementos = (flags & ArrayLiteral::kDisableMementos) == 0; Handle<JSObject> boilerplate(JSObject::cast(site->transition_info())); AllocationSiteUsageContext usage_context(isolate, site, enable_mementos); usage_context.EnterNewScope(); JSObject::DeepCopyHints hints = (flags & ArrayLiteral::kShallowElements) == 0 ? JSObject::kNoHints : JSObject::kObjectIsShallow; MaybeHandle<JSObject> copy = JSObject::DeepCopy(boilerplate, &usage_context, hints); usage_context.ExitScope(site, boilerplate); return copy; } RUNTIME_FUNCTION(Runtime_CreateArrayLiteral) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); Handle<JSObject> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, CreateArrayLiteralImpl(isolate, literals, literals_index, elements, flags)); return *result; } RUNTIME_FUNCTION(Runtime_CreateArrayLiteralStubBailout) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2); Handle<JSObject> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, CreateArrayLiteralImpl(isolate, literals, literals_index, elements, ArrayLiteral::kShallowElements)); return *result; } RUNTIME_FUNCTION(Runtime_CreateSymbol) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, name, 0); RUNTIME_ASSERT(name->IsString() || name->IsUndefined()); Handle<Symbol> symbol = isolate->factory()->NewSymbol(); if (name->IsString()) symbol->set_name(*name); return *symbol; } RUNTIME_FUNCTION(Runtime_CreatePrivateSymbol) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, name, 0); RUNTIME_ASSERT(name->IsString() || name->IsUndefined()); Handle<Symbol> symbol = isolate->factory()->NewPrivateSymbol(); if (name->IsString()) symbol->set_name(*name); return *symbol; } RUNTIME_FUNCTION(Runtime_CreatePrivateOwnSymbol) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, name, 0); RUNTIME_ASSERT(name->IsString() || name->IsUndefined()); Handle<Symbol> symbol = isolate->factory()->NewPrivateOwnSymbol(); if (name->IsString()) symbol->set_name(*name); return *symbol; } RUNTIME_FUNCTION(Runtime_CreateGlobalPrivateOwnSymbol) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(String, name, 0); Handle<JSObject> registry = isolate->GetSymbolRegistry(); Handle<String> part = isolate->factory()->private_intern_string(); Handle<Object> privates; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, privates, Object::GetPropertyOrElement(registry, part)); Handle<Object> symbol; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, symbol, Object::GetPropertyOrElement(privates, name)); if (!symbol->IsSymbol()) { DCHECK(symbol->IsUndefined()); symbol = isolate->factory()->NewPrivateSymbol(); Handle<Symbol>::cast(symbol)->set_name(*name); Handle<Symbol>::cast(symbol)->set_is_own(true); JSObject::SetProperty(Handle<JSObject>::cast(privates), name, symbol, STRICT).Assert(); } return *symbol; } RUNTIME_FUNCTION(Runtime_NewSymbolWrapper) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Symbol, symbol, 0); return *Object::ToObject(isolate, symbol).ToHandleChecked(); } RUNTIME_FUNCTION(Runtime_SymbolDescription) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Symbol, symbol, 0); return symbol->name(); } RUNTIME_FUNCTION(Runtime_SymbolRegistry) { HandleScope scope(isolate); DCHECK(args.length() == 0); return *isolate->GetSymbolRegistry(); } RUNTIME_FUNCTION(Runtime_SymbolIsPrivate) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Symbol, symbol, 0); return isolate->heap()->ToBoolean(symbol->is_private()); } RUNTIME_FUNCTION(Runtime_CreateJSProxy) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1); if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value(); return *isolate->factory()->NewJSProxy(handler, prototype); } RUNTIME_FUNCTION(Runtime_CreateJSFunctionProxy) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0); CONVERT_ARG_HANDLE_CHECKED(Object, call_trap, 1); RUNTIME_ASSERT(call_trap->IsJSFunction() || call_trap->IsJSFunctionProxy()); CONVERT_ARG_HANDLE_CHECKED(JSFunction, construct_trap, 2); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 3); if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value(); return *isolate->factory()->NewJSFunctionProxy(handler, call_trap, construct_trap, prototype); } RUNTIME_FUNCTION(Runtime_IsJSProxy) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSProxy()); } RUNTIME_FUNCTION(Runtime_IsJSFunctionProxy) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy()); } RUNTIME_FUNCTION(Runtime_GetHandler) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSProxy, proxy, 0); return proxy->handler(); } RUNTIME_FUNCTION(Runtime_GetCallTrap) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->call_trap(); } RUNTIME_FUNCTION(Runtime_GetConstructTrap) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->construct_trap(); } RUNTIME_FUNCTION(Runtime_Fix) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, 0); JSProxy::Fix(proxy); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_GetPrototype) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0); // We don't expect access checks to be needed on JSProxy objects. DCHECK(!obj->IsAccessCheckNeeded() || obj->IsJSObject()); PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER); do { if (PrototypeIterator::GetCurrent(iter)->IsAccessCheckNeeded() && !isolate->MayNamedAccess( Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), isolate->factory()->proto_string(), v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck( Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), v8::ACCESS_GET); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return isolate->heap()->undefined_value(); } iter.AdvanceIgnoringProxies(); if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) { return *PrototypeIterator::GetCurrent(iter); } } while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN)); return *PrototypeIterator::GetCurrent(iter); } static inline Handle<Object> GetPrototypeSkipHiddenPrototypes( Isolate* isolate, Handle<Object> receiver) { PrototypeIterator iter(isolate, receiver); while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN)) { if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) { return PrototypeIterator::GetCurrent(iter); } iter.Advance(); } return PrototypeIterator::GetCurrent(iter); } RUNTIME_FUNCTION(Runtime_InternalSetPrototype) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1); DCHECK(!obj->IsAccessCheckNeeded()); DCHECK(!obj->map()->is_observed()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetPrototype(obj, prototype, false)); return *result; } RUNTIME_FUNCTION(Runtime_SetPrototype) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1); if (obj->IsAccessCheckNeeded() && !isolate->MayNamedAccess(obj, isolate->factory()->proto_string(), v8::ACCESS_SET)) { isolate->ReportFailedAccessCheck(obj, v8::ACCESS_SET); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return isolate->heap()->undefined_value(); } if (obj->map()->is_observed()) { Handle<Object> old_value = GetPrototypeSkipHiddenPrototypes(isolate, obj); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetPrototype(obj, prototype, true)); Handle<Object> new_value = GetPrototypeSkipHiddenPrototypes(isolate, obj); if (!new_value->SameValue(*old_value)) { JSObject::EnqueueChangeRecord( obj, "setPrototype", isolate->factory()->proto_string(), old_value); } return *result; } Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetPrototype(obj, prototype, true)); return *result; } RUNTIME_FUNCTION(Runtime_IsInPrototypeChain) { HandleScope shs(isolate); DCHECK(args.length() == 2); // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8). CONVERT_ARG_HANDLE_CHECKED(Object, O, 0); CONVERT_ARG_HANDLE_CHECKED(Object, V, 1); PrototypeIterator iter(isolate, V, PrototypeIterator::START_AT_RECEIVER); while (true) { iter.AdvanceIgnoringProxies(); if (iter.IsAtEnd()) return isolate->heap()->false_value(); if (iter.IsAtEnd(O)) return isolate->heap()->true_value(); } } // Enumerator used as indices into the array returned from GetOwnProperty enum PropertyDescriptorIndices { IS_ACCESSOR_INDEX, VALUE_INDEX, GETTER_INDEX, SETTER_INDEX, WRITABLE_INDEX, ENUMERABLE_INDEX, CONFIGURABLE_INDEX, DESCRIPTOR_SIZE }; MUST_USE_RESULT static MaybeHandle<Object> GetOwnProperty(Isolate* isolate, Handle<JSObject> obj, Handle<Name> name) { Heap* heap = isolate->heap(); Factory* factory = isolate->factory(); PropertyAttributes attrs; uint32_t index = 0; Handle<Object> value; MaybeHandle<AccessorPair> maybe_accessors; // TODO(verwaest): Unify once indexed properties can be handled by the // LookupIterator. if (name->AsArrayIndex(&index)) { // Get attributes. Maybe<PropertyAttributes> maybe = JSReceiver::GetOwnElementAttribute(obj, index); if (!maybe.has_value) return MaybeHandle<Object>(); attrs = maybe.value; if (attrs == ABSENT) return factory->undefined_value(); // Get AccessorPair if present. maybe_accessors = JSObject::GetOwnElementAccessorPair(obj, index); // Get value if not an AccessorPair. if (maybe_accessors.is_null()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, value, Runtime::GetElementOrCharAt(isolate, obj, index), Object); } } else { // Get attributes. LookupIterator it(obj, name, LookupIterator::HIDDEN); Maybe<PropertyAttributes> maybe = JSObject::GetPropertyAttributes(&it); if (!maybe.has_value) return MaybeHandle<Object>(); attrs = maybe.value; if (attrs == ABSENT) return factory->undefined_value(); // Get AccessorPair if present. if (it.state() == LookupIterator::ACCESSOR && it.GetAccessors()->IsAccessorPair()) { maybe_accessors = Handle<AccessorPair>::cast(it.GetAccessors()); } // Get value if not an AccessorPair. if (maybe_accessors.is_null()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, value, Object::GetProperty(&it), Object); } } DCHECK(!isolate->has_pending_exception()); Handle<FixedArray> elms = factory->NewFixedArray(DESCRIPTOR_SIZE); elms->set(ENUMERABLE_INDEX, heap->ToBoolean((attrs & DONT_ENUM) == 0)); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean((attrs & DONT_DELETE) == 0)); elms->set(IS_ACCESSOR_INDEX, heap->ToBoolean(!maybe_accessors.is_null())); Handle<AccessorPair> accessors; if (maybe_accessors.ToHandle(&accessors)) { Handle<Object> getter(accessors->GetComponent(ACCESSOR_GETTER), isolate); Handle<Object> setter(accessors->GetComponent(ACCESSOR_SETTER), isolate); elms->set(GETTER_INDEX, *getter); elms->set(SETTER_INDEX, *setter); } else { elms->set(WRITABLE_INDEX, heap->ToBoolean((attrs & READ_ONLY) == 0)); elms->set(VALUE_INDEX, *value); } return factory->NewJSArrayWithElements(elms); } // Returns an array with the property description: // if args[1] is not a property on args[0] // returns undefined // if args[1] is a data property on args[0] // [false, value, Writeable, Enumerable, Configurable] // if args[1] is an accessor on args[0] // [true, GetFunction, SetFunction, Enumerable, Configurable] RUNTIME_FUNCTION(Runtime_GetOwnProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, GetOwnProperty(isolate, obj, name)); return *result; } RUNTIME_FUNCTION(Runtime_PreventExtensions) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::PreventExtensions(obj)); return *result; } RUNTIME_FUNCTION(Runtime_ToMethod) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1); Handle<JSFunction> clone = JSFunction::CloneClosure(fun); Handle<Symbol> home_object_symbol(isolate->heap()->home_object_symbol()); JSObject::SetOwnPropertyIgnoreAttributes(clone, home_object_symbol, home_object, DONT_ENUM).Assert(); return *clone; } RUNTIME_FUNCTION(Runtime_HomeObjectSymbol) { DCHECK(args.length() == 0); return isolate->heap()->home_object_symbol(); } RUNTIME_FUNCTION(Runtime_LoadFromSuper) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1); CONVERT_ARG_HANDLE_CHECKED(Name, name, 2); if (home_object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(home_object, name, v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_GET); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); } PrototypeIterator iter(isolate, home_object); Handle<Object> proto = PrototypeIterator::GetCurrent(iter); if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value(); LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto)); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, Object::GetProperty(&it)); return *result; } static Object* StoreToSuper(Isolate* isolate, Handle<JSObject> home_object, Handle<Object> receiver, Handle<Name> name, Handle<Object> value, StrictMode strict_mode) { if (home_object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(home_object, name, v8::ACCESS_SET)) { isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_SET); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); } PrototypeIterator iter(isolate, home_object); Handle<Object> proto = PrototypeIterator::GetCurrent(iter); if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value(); LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto)); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Object::SetProperty(&it, value, strict_mode, Object::CERTAINLY_NOT_STORE_FROM_KEYED, Object::SUPER_PROPERTY)); return *result; } RUNTIME_FUNCTION(Runtime_StoreToSuper_Strict) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_ARG_HANDLE_CHECKED(Name, name, 3); return StoreToSuper(isolate, home_object, receiver, name, value, STRICT); } RUNTIME_FUNCTION(Runtime_StoreToSuper_Sloppy) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_ARG_HANDLE_CHECKED(Name, name, 3); return StoreToSuper(isolate, home_object, receiver, name, value, SLOPPY); } RUNTIME_FUNCTION(Runtime_IsExtensible) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, obj, 0); if (obj->IsJSGlobalProxy()) { PrototypeIterator iter(isolate, obj); if (iter.IsAtEnd()) return isolate->heap()->false_value(); DCHECK(iter.GetCurrent()->IsJSGlobalObject()); obj = JSObject::cast(iter.GetCurrent()); } return isolate->heap()->ToBoolean(obj->map()->is_extensible()); } RUNTIME_FUNCTION(Runtime_CreateApiFunction) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(FunctionTemplateInfo, data, 0); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1); return *isolate->factory()->CreateApiFunction(data, prototype); } RUNTIME_FUNCTION(Runtime_IsTemplate) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, arg, 0); bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return isolate->heap()->ToBoolean(result); } RUNTIME_FUNCTION(Runtime_GetTemplateField) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(HeapObject, templ, 0); CONVERT_SMI_ARG_CHECKED(index, 1); int offset = index * kPointerSize + HeapObject::kHeaderSize; InstanceType type = templ->map()->instance_type(); RUNTIME_ASSERT(type == FUNCTION_TEMPLATE_INFO_TYPE || type == OBJECT_TEMPLATE_INFO_TYPE); RUNTIME_ASSERT(offset > 0); if (type == FUNCTION_TEMPLATE_INFO_TYPE) { RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize); } else { RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize); } return *HeapObject::RawField(templ, offset); } RUNTIME_FUNCTION(Runtime_DisableAccessChecks) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(HeapObject, object, 0); Handle<Map> old_map(object->map()); bool needs_access_checks = old_map->is_access_check_needed(); if (needs_access_checks) { // Copy map so it won't interfere constructor's initial map. Handle<Map> new_map = Map::Copy(old_map); new_map->set_is_access_check_needed(false); JSObject::MigrateToMap(Handle<JSObject>::cast(object), new_map); } return isolate->heap()->ToBoolean(needs_access_checks); } RUNTIME_FUNCTION(Runtime_EnableAccessChecks) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); Handle<Map> old_map(object->map()); RUNTIME_ASSERT(!old_map->is_access_check_needed()); // Copy map so it won't interfere constructor's initial map. Handle<Map> new_map = Map::Copy(old_map); new_map->set_is_access_check_needed(true); JSObject::MigrateToMap(object, new_map); return isolate->heap()->undefined_value(); } static Object* ThrowRedeclarationError(Isolate* isolate, Handle<String> name) { HandleScope scope(isolate); Handle<Object> args[1] = {name}; THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("var_redeclaration", HandleVector(args, 1))); } // May throw a RedeclarationError. static Object* DeclareGlobals(Isolate* isolate, Handle<GlobalObject> global, Handle<String> name, Handle<Object> value, PropertyAttributes attr, bool is_var, bool is_const, bool is_function) { // Do the lookup own properties only, see ES5 erratum. LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR); Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it); if (!maybe.has_value) return isolate->heap()->exception(); if (it.IsFound()) { PropertyAttributes old_attributes = maybe.value; // The name was declared before; check for conflicting re-declarations. if (is_const) return ThrowRedeclarationError(isolate, name); // Skip var re-declarations. if (is_var) return isolate->heap()->undefined_value(); DCHECK(is_function); if ((old_attributes & DONT_DELETE) != 0) { // Only allow reconfiguring globals to functions in user code (no // natives, which are marked as read-only). DCHECK((attr & READ_ONLY) == 0); // Check whether we can reconfigure the existing property into a // function. PropertyDetails old_details = it.property_details(); // TODO(verwaest): CALLBACKS invalidly includes ExecutableAccessInfo, // which are actually data properties, not accessor properties. if (old_details.IsReadOnly() || old_details.IsDontEnum() || old_details.type() == CALLBACKS) { return ThrowRedeclarationError(isolate, name); } // If the existing property is not configurable, keep its attributes. Do attr = old_attributes; } } // Define or redefine own property. RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes( global, name, value, attr)); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DeclareGlobals) { HandleScope scope(isolate); DCHECK(args.length() == 3); Handle<GlobalObject> global(isolate->global_object()); CONVERT_ARG_HANDLE_CHECKED(Context, context, 0); CONVERT_ARG_HANDLE_CHECKED(FixedArray, pairs, 1); CONVERT_SMI_ARG_CHECKED(flags, 2); // Traverse the name/value pairs and set the properties. int length = pairs->length(); for (int i = 0; i < length; i += 2) { HandleScope scope(isolate); Handle<String> name(String::cast(pairs->get(i))); Handle<Object> initial_value(pairs->get(i + 1), isolate); // We have to declare a global const property. To capture we only // assign to it when evaluating the assignment for "const x = // <expr>" the initial value is the hole. bool is_var = initial_value->IsUndefined(); bool is_const = initial_value->IsTheHole(); bool is_function = initial_value->IsSharedFunctionInfo(); DCHECK(is_var + is_const + is_function == 1); Handle<Object> value; if (is_function) { // Copy the function and update its context. Use it as value. Handle<SharedFunctionInfo> shared = Handle<SharedFunctionInfo>::cast(initial_value); Handle<JSFunction> function = isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context, TENURED); value = function; } else { value = isolate->factory()->undefined_value(); } // Compute the property attributes. According to ECMA-262, // the property must be non-configurable except in eval. bool is_native = DeclareGlobalsNativeFlag::decode(flags); bool is_eval = DeclareGlobalsEvalFlag::decode(flags); int attr = NONE; if (is_const) attr |= READ_ONLY; if (is_function && is_native) attr |= READ_ONLY; if (!is_const && !is_eval) attr |= DONT_DELETE; Object* result = DeclareGlobals(isolate, global, name, value, static_cast<PropertyAttributes>(attr), is_var, is_const, is_function); if (isolate->has_pending_exception()) return result; } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_InitializeVarGlobal) { HandleScope scope(isolate); // args[0] == name // args[1] == language_mode // args[2] == value (optional) // Determine if we need to assign to the variable if it already // exists (based on the number of arguments). RUNTIME_ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(String, name, 0); CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); Handle<GlobalObject> global(isolate->context()->global_object()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Object::SetProperty(global, name, value, strict_mode)); return *result; } RUNTIME_FUNCTION(Runtime_InitializeConstGlobal) { HandleScope handle_scope(isolate); // All constants are declared with an initial value. The name // of the constant is the first argument and the initial value // is the second. RUNTIME_ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, name, 0); CONVERT_ARG_HANDLE_CHECKED(Object, value, 1); Handle<GlobalObject> global = isolate->global_object(); // Lookup the property as own on the global object. LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR); Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it); DCHECK(maybe.has_value); PropertyAttributes old_attributes = maybe.value; PropertyAttributes attr = static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY); // Set the value if the property is either missing, or the property attributes // allow setting the value without invoking an accessor. if (it.IsFound()) { // Ignore if we can't reconfigure the value. if ((old_attributes & DONT_DELETE) != 0) { if ((old_attributes & READ_ONLY) != 0 || it.state() == LookupIterator::ACCESSOR) { return *value; } attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY); } } RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes( global, name, value, attr)); return *value; } RUNTIME_FUNCTION(Runtime_DeclareLookupSlot) { HandleScope scope(isolate); DCHECK(args.length() == 4); // Declarations are always made in a function, native, or global context. In // the case of eval code, the context passed is the context of the caller, // which may be some nested context and not the declaration context. CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 0); Handle<Context> context(context_arg->declaration_context()); CONVERT_ARG_HANDLE_CHECKED(String, name, 1); CONVERT_SMI_ARG_CHECKED(attr_arg, 2); PropertyAttributes attr = static_cast<PropertyAttributes>(attr_arg); RUNTIME_ASSERT(attr == READ_ONLY || attr == NONE); CONVERT_ARG_HANDLE_CHECKED(Object, initial_value, 3); // TODO(verwaest): Unify the encoding indicating "var" with DeclareGlobals. bool is_var = *initial_value == NULL; bool is_const = initial_value->IsTheHole(); bool is_function = initial_value->IsJSFunction(); DCHECK(is_var + is_const + is_function == 1); int index; PropertyAttributes attributes; ContextLookupFlags flags = DONT_FOLLOW_CHAINS; BindingFlags binding_flags; Handle<Object> holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); Handle<JSObject> object; Handle<Object> value = is_function ? initial_value : Handle<Object>::cast(isolate->factory()->undefined_value()); // TODO(verwaest): This case should probably not be covered by this function, // but by DeclareGlobals instead. if ((attributes != ABSENT && holder->IsJSGlobalObject()) || (context_arg->has_extension() && context_arg->extension()->IsJSGlobalObject())) { return DeclareGlobals(isolate, Handle<JSGlobalObject>::cast(holder), name, value, attr, is_var, is_const, is_function); } if (attributes != ABSENT) { // The name was declared before; check for conflicting re-declarations. if (is_const || (attributes & READ_ONLY) != 0) { return ThrowRedeclarationError(isolate, name); } // Skip var re-declarations. if (is_var) return isolate->heap()->undefined_value(); DCHECK(is_function); if (index >= 0) { DCHECK(holder.is_identical_to(context)); context->set(index, *initial_value); return isolate->heap()->undefined_value(); } object = Handle<JSObject>::cast(holder); } else if (context->has_extension()) { object = handle(JSObject::cast(context->extension())); DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject()); } else { DCHECK(context->IsFunctionContext()); object = isolate->factory()->NewJSObject(isolate->context_extension_function()); context->set_extension(*object); } RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes( object, name, value, attr)); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_InitializeLegacyConstLookupSlot) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(Object, value, 0); DCHECK(!value->IsTheHole()); // Initializations are always done in a function or native context. CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 1); Handle<Context> context(context_arg->declaration_context()); CONVERT_ARG_HANDLE_CHECKED(String, name, 2); int index; PropertyAttributes attributes; ContextLookupFlags flags = DONT_FOLLOW_CHAINS; BindingFlags binding_flags; Handle<Object> holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); if (index >= 0) { DCHECK(holder->IsContext()); // Property was found in a context. Perform the assignment if the constant // was uninitialized. Handle<Context> context = Handle<Context>::cast(holder); DCHECK((attributes & READ_ONLY) != 0); if (context->get(index)->IsTheHole()) context->set(index, *value); return *value; } PropertyAttributes attr = static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY); // Strict mode handling not needed (legacy const is disallowed in strict // mode). // The declared const was configurable, and may have been deleted in the // meanwhile. If so, re-introduce the variable in the context extension. DCHECK(context_arg->has_extension()); if (attributes == ABSENT) { holder = handle(context_arg->extension(), isolate); } else { // For JSContextExtensionObjects, the initializer can be run multiple times // if in a for loop: for (var i = 0; i < 2; i++) { const x = i; }. Only the // first assignment should go through. For JSGlobalObjects, additionally any // code can run in between that modifies the declared property. DCHECK(holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject()); LookupIterator it(holder, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR); Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it); if (!maybe.has_value) return isolate->heap()->exception(); PropertyAttributes old_attributes = maybe.value; // Ignore if we can't reconfigure the value. if ((old_attributes & DONT_DELETE) != 0) { if ((old_attributes & READ_ONLY) != 0 || it.state() == LookupIterator::ACCESSOR) { return *value; } attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY); } } RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::SetOwnPropertyIgnoreAttributes( Handle<JSObject>::cast(holder), name, value, attr)); return *value; } RUNTIME_FUNCTION(Runtime_OptimizeObjectForAddingMultipleProperties) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_SMI_ARG_CHECKED(properties, 1); // Conservative upper limit to prevent fuzz tests from going OOM. RUNTIME_ASSERT(properties <= 100000); if (object->HasFastProperties() && !object->IsJSGlobalProxy()) { JSObject::NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties); } return *object; } RUNTIME_FUNCTION(Runtime_FinishArrayPrototypeSetup) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSArray, prototype, 0); Object* length = prototype->length(); RUNTIME_ASSERT(length->IsSmi() && Smi::cast(length)->value() == 0); RUNTIME_ASSERT(prototype->HasFastSmiOrObjectElements()); // This is necessary to enable fast checks for absence of elements // on Array.prototype and below. prototype->set_elements(isolate->heap()->empty_fixed_array()); return Smi::FromInt(0); } static void InstallBuiltin(Isolate* isolate, Handle<JSObject> holder, const char* name, Builtins::Name builtin_name) { Handle<String> key = isolate->factory()->InternalizeUtf8String(name); Handle<Code> code(isolate->builtins()->builtin(builtin_name)); Handle<JSFunction> optimized = isolate->factory()->NewFunctionWithoutPrototype(key, code); optimized->shared()->DontAdaptArguments(); JSObject::AddProperty(holder, key, optimized, NONE); } RUNTIME_FUNCTION(Runtime_SpecialArrayFunctions) { HandleScope scope(isolate); DCHECK(args.length() == 0); Handle<JSObject> holder = isolate->factory()->NewJSObject(isolate->object_function()); InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop); InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush); InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift); InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift); InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice); InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice); InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat); return *holder; } RUNTIME_FUNCTION(Runtime_IsSloppyModeFunction) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, callable, 0); if (!callable->IsJSFunction()) { HandleScope scope(isolate); Handle<Object> delegate; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, delegate, Execution::TryGetFunctionDelegate( isolate, Handle<JSReceiver>(callable))); callable = JSFunction::cast(*delegate); } JSFunction* function = JSFunction::cast(callable); SharedFunctionInfo* shared = function->shared(); return isolate->heap()->ToBoolean(shared->strict_mode() == SLOPPY); } RUNTIME_FUNCTION(Runtime_GetDefaultReceiver) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, callable, 0); if (!callable->IsJSFunction()) { HandleScope scope(isolate); Handle<Object> delegate; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, delegate, Execution::TryGetFunctionDelegate( isolate, Handle<JSReceiver>(callable))); callable = JSFunction::cast(*delegate); } JSFunction* function = JSFunction::cast(callable); SharedFunctionInfo* shared = function->shared(); if (shared->native() || shared->strict_mode() == STRICT) { return isolate->heap()->undefined_value(); } // Returns undefined for strict or native functions, or // the associated global receiver for "normal" functions. return function->global_proxy(); } RUNTIME_FUNCTION(Runtime_FunctionGetName) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return f->shared()->name(); } RUNTIME_FUNCTION(Runtime_FunctionSetName) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(JSFunction, f, 0); CONVERT_ARG_CHECKED(String, name, 1); f->shared()->set_name(name); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionNameShouldPrintAsAnonymous) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean( f->shared()->name_should_print_as_anonymous()); } RUNTIME_FUNCTION(Runtime_FunctionMarkNameShouldPrintAsAnonymous) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); f->shared()->set_name_should_print_as_anonymous(true); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionIsGenerator) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->shared()->is_generator()); } RUNTIME_FUNCTION(Runtime_FunctionIsArrow) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->shared()->is_arrow()); } RUNTIME_FUNCTION(Runtime_FunctionIsConciseMethod) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->shared()->is_concise_method()); } RUNTIME_FUNCTION(Runtime_FunctionRemovePrototype) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); RUNTIME_ASSERT(f->RemovePrototype()); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionGetScript) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, fun, 0); Handle<Object> script = Handle<Object>(fun->shared()->script(), isolate); if (!script->IsScript()) return isolate->heap()->undefined_value(); return *Script::GetWrapper(Handle<Script>::cast(script)); } RUNTIME_FUNCTION(Runtime_FunctionGetSourceCode) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, f, 0); Handle<SharedFunctionInfo> shared(f->shared()); return *shared->GetSourceCode(); } RUNTIME_FUNCTION(Runtime_FunctionGetScriptSourcePosition) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, fun, 0); int pos = fun->shared()->start_position(); return Smi::FromInt(pos); } RUNTIME_FUNCTION(Runtime_FunctionGetPositionForOffset) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(Code, code, 0); CONVERT_NUMBER_CHECKED(int, offset, Int32, args[1]); RUNTIME_ASSERT(0 <= offset && offset < code->Size()); Address pc = code->address() + offset; return Smi::FromInt(code->SourcePosition(pc)); } RUNTIME_FUNCTION(Runtime_FunctionSetInstanceClassName) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(JSFunction, fun, 0); CONVERT_ARG_CHECKED(String, name, 1); fun->SetInstanceClassName(name); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionSetLength) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(JSFunction, fun, 0); CONVERT_SMI_ARG_CHECKED(length, 1); RUNTIME_ASSERT((length & 0xC0000000) == 0xC0000000 || (length & 0xC0000000) == 0x0); fun->shared()->set_length(length); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionSetPrototype) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); CONVERT_ARG_HANDLE_CHECKED(Object, value, 1); RUNTIME_ASSERT(fun->should_have_prototype()); Accessors::FunctionSetPrototype(fun, value); return args[0]; // return TOS } RUNTIME_FUNCTION(Runtime_FunctionIsAPIFunction) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->shared()->IsApiFunction()); } RUNTIME_FUNCTION(Runtime_FunctionIsBuiltin) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->IsBuiltin()); } RUNTIME_FUNCTION(Runtime_SetCode) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, target, 0); CONVERT_ARG_HANDLE_CHECKED(JSFunction, source, 1); Handle<SharedFunctionInfo> target_shared(target->shared()); Handle<SharedFunctionInfo> source_shared(source->shared()); RUNTIME_ASSERT(!source_shared->bound()); if (!Compiler::EnsureCompiled(source, KEEP_EXCEPTION)) { return isolate->heap()->exception(); } // Mark both, the source and the target, as un-flushable because the // shared unoptimized code makes them impossible to enqueue in a list. DCHECK(target_shared->code()->gc_metadata() == NULL); DCHECK(source_shared->code()->gc_metadata() == NULL); target_shared->set_dont_flush(true); source_shared->set_dont_flush(true); // Set the code, scope info, formal parameter count, and the length // of the target shared function info. target_shared->ReplaceCode(source_shared->code()); target_shared->set_scope_info(source_shared->scope_info()); target_shared->set_length(source_shared->length()); target_shared->set_feedback_vector(source_shared->feedback_vector()); target_shared->set_formal_parameter_count( source_shared->formal_parameter_count()); target_shared->set_script(source_shared->script()); target_shared->set_start_position_and_type( source_shared->start_position_and_type()); target_shared->set_end_position(source_shared->end_position()); bool was_native = target_shared->native(); target_shared->set_compiler_hints(source_shared->compiler_hints()); target_shared->set_native(was_native); target_shared->set_profiler_ticks(source_shared->profiler_ticks()); // Set the code of the target function. target->ReplaceCode(source_shared->code()); DCHECK(target->next_function_link()->IsUndefined()); // Make sure we get a fresh copy of the literal vector to avoid cross // context contamination. Handle<Context> context(source->context()); int number_of_literals = source->NumberOfLiterals(); Handle<FixedArray> literals = isolate->factory()->NewFixedArray(number_of_literals, TENURED); if (number_of_literals > 0) { literals->set(JSFunction::kLiteralNativeContextIndex, context->native_context()); } target->set_context(*context); target->set_literals(*literals); if (isolate->logger()->is_logging_code_events() || isolate->cpu_profiler()->is_profiling()) { isolate->logger()->LogExistingFunction(source_shared, Handle<Code>(source_shared->code())); } return *target; } RUNTIME_FUNCTION(Runtime_CreateJSGeneratorObject) { HandleScope scope(isolate); DCHECK(args.length() == 0); JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); Handle<JSFunction> function(frame->function()); RUNTIME_ASSERT(function->shared()->is_generator()); Handle<JSGeneratorObject> generator; if (frame->IsConstructor()) { generator = handle(JSGeneratorObject::cast(frame->receiver())); } else { generator = isolate->factory()->NewJSGeneratorObject(function); } generator->set_function(*function); generator->set_context(Context::cast(frame->context())); generator->set_receiver(frame->receiver()); generator->set_continuation(0); generator->set_operand_stack(isolate->heap()->empty_fixed_array()); generator->set_stack_handler_index(-1); return *generator; } RUNTIME_FUNCTION(Runtime_SuspendJSGeneratorObject) { HandleScope handle_scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator_object, 0); JavaScriptFrameIterator stack_iterator(isolate); JavaScriptFrame* frame = stack_iterator.frame(); RUNTIME_ASSERT(frame->function()->shared()->is_generator()); DCHECK_EQ(frame->function(), generator_object->function()); // The caller should have saved the context and continuation already. DCHECK_EQ(generator_object->context(), Context::cast(frame->context())); DCHECK_LT(0, generator_object->continuation()); // We expect there to be at least two values on the operand stack: the return // value of the yield expression, and the argument to this runtime call. // Neither of those should be saved. int operands_count = frame->ComputeOperandsCount(); DCHECK_GE(operands_count, 2); operands_count -= 2; if (operands_count == 0) { // Although it's semantically harmless to call this function with an // operands_count of zero, it is also unnecessary. DCHECK_EQ(generator_object->operand_stack(), isolate->heap()->empty_fixed_array()); DCHECK_EQ(generator_object->stack_handler_index(), -1); // If there are no operands on the stack, there shouldn't be a handler // active either. DCHECK(!frame->HasHandler()); } else { int stack_handler_index = -1; Handle<FixedArray> operand_stack = isolate->factory()->NewFixedArray(operands_count); frame->SaveOperandStack(*operand_stack, &stack_handler_index); generator_object->set_operand_stack(*operand_stack); generator_object->set_stack_handler_index(stack_handler_index); } return isolate->heap()->undefined_value(); } // Note that this function is the slow path for resuming generators. It is only // called if the suspended activation had operands on the stack, stack handlers // needing rewinding, or if the resume should throw an exception. The fast path // is handled directly in FullCodeGenerator::EmitGeneratorResume(), which is // inlined into GeneratorNext and GeneratorThrow. EmitGeneratorResumeResume is // called in any case, as it needs to reconstruct the stack frame and make space // for arguments and operands. RUNTIME_FUNCTION(Runtime_ResumeJSGeneratorObject) { SealHandleScope shs(isolate); DCHECK(args.length() == 3); CONVERT_ARG_CHECKED(JSGeneratorObject, generator_object, 0); CONVERT_ARG_CHECKED(Object, value, 1); CONVERT_SMI_ARG_CHECKED(resume_mode_int, 2); JavaScriptFrameIterator stack_iterator(isolate); JavaScriptFrame* frame = stack_iterator.frame(); DCHECK_EQ(frame->function(), generator_object->function()); DCHECK(frame->function()->is_compiled()); STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0); STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0); Address pc = generator_object->function()->code()->instruction_start(); int offset = generator_object->continuation(); DCHECK(offset > 0); frame->set_pc(pc + offset); if (FLAG_enable_ool_constant_pool) { frame->set_constant_pool( generator_object->function()->code()->constant_pool()); } generator_object->set_continuation(JSGeneratorObject::kGeneratorExecuting); FixedArray* operand_stack = generator_object->operand_stack(); int operands_count = operand_stack->length(); if (operands_count != 0) { frame->RestoreOperandStack(operand_stack, generator_object->stack_handler_index()); generator_object->set_operand_stack(isolate->heap()->empty_fixed_array()); generator_object->set_stack_handler_index(-1); } JSGeneratorObject::ResumeMode resume_mode = static_cast<JSGeneratorObject::ResumeMode>(resume_mode_int); switch (resume_mode) { case JSGeneratorObject::NEXT: return value; case JSGeneratorObject::THROW: return isolate->Throw(value); } UNREACHABLE(); return isolate->ThrowIllegalOperation(); } RUNTIME_FUNCTION(Runtime_ThrowGeneratorStateError) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); int continuation = generator->continuation(); const char* message = continuation == JSGeneratorObject::kGeneratorClosed ? "generator_finished" : "generator_running"; Vector<Handle<Object> > argv = HandleVector<Object>(NULL, 0); THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewError(message, argv)); } RUNTIME_FUNCTION(Runtime_ObjectFreeze) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); // %ObjectFreeze is a fast path and these cases are handled elsewhere. RUNTIME_ASSERT(!object->HasSloppyArgumentsElements() && !object->map()->is_observed() && !object->IsJSProxy()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::Freeze(object)); return *result; } // Returns a single character string where first character equals // string->Get(index). static Handle<Object> GetCharAt(Handle<String> string, uint32_t index) { if (index < static_cast<uint32_t>(string->length())) { Factory* factory = string->GetIsolate()->factory(); return factory->LookupSingleCharacterStringFromCode( String::Flatten(string)->Get(index)); } return Execution::CharAt(string, index); } MaybeHandle<Object> Runtime::GetElementOrCharAt(Isolate* isolate, Handle<Object> object, uint32_t index) { // Handle [] indexing on Strings if (object->IsString()) { Handle<Object> result = GetCharAt(Handle<String>::cast(object), index); if (!result->IsUndefined()) return result; } // Handle [] indexing on String objects if (object->IsStringObjectWithCharacterAt(index)) { Handle<JSValue> js_value = Handle<JSValue>::cast(object); Handle<Object> result = GetCharAt(Handle<String>(String::cast(js_value->value())), index); if (!result->IsUndefined()) return result; } Handle<Object> result; if (object->IsString() || object->IsNumber() || object->IsBoolean()) { PrototypeIterator iter(isolate, object); return Object::GetElement(isolate, PrototypeIterator::GetCurrent(iter), index); } else { return Object::GetElement(isolate, object, index); } } MUST_USE_RESULT static MaybeHandle<Name> ToName(Isolate* isolate, Handle<Object> key) { if (key->IsName()) { return Handle<Name>::cast(key); } else { Handle<Object> converted; ASSIGN_RETURN_ON_EXCEPTION(isolate, converted, Execution::ToString(isolate, key), Name); return Handle<Name>::cast(converted); } } MaybeHandle<Object> Runtime::HasObjectProperty(Isolate* isolate, Handle<JSReceiver> object, Handle<Object> key) { Maybe<bool> maybe; // Check if the given key is an array index. uint32_t index; if (key->ToArrayIndex(&index)) { maybe = JSReceiver::HasElement(object, index); } else { // Convert the key to a name - possibly by calling back into JavaScript. Handle<Name> name; ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object); maybe = JSReceiver::HasProperty(object, name); } if (!maybe.has_value) return MaybeHandle<Object>(); return isolate->factory()->ToBoolean(maybe.value); } MaybeHandle<Object> Runtime::GetObjectProperty(Isolate* isolate, Handle<Object> object, Handle<Object> key) { if (object->IsUndefined() || object->IsNull()) { Handle<Object> args[2] = {key, object}; THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_load", HandleVector(args, 2)), Object); } // Check if the given key is an array index. uint32_t index; if (key->ToArrayIndex(&index)) { return GetElementOrCharAt(isolate, object, index); } // Convert the key to a name - possibly by calling back into JavaScript. Handle<Name> name; ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object); // Check if the name is trivially convertible to an index and get // the element if so. if (name->AsArrayIndex(&index)) { return GetElementOrCharAt(isolate, object, index); } else { return Object::GetProperty(object, name); } } RUNTIME_FUNCTION(Runtime_GetProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Runtime::GetObjectProperty(isolate, object, key)); return *result; } // KeyedGetProperty is called from KeyedLoadIC::GenerateGeneric. RUNTIME_FUNCTION(Runtime_KeyedGetProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, receiver_obj, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key_obj, 1); // Fast cases for getting named properties of the receiver JSObject // itself. // // The global proxy objects has to be excluded since LookupOwn on // the global proxy object can return a valid result even though the // global proxy object never has properties. This is the case // because the global proxy object forwards everything to its hidden // prototype including own lookups. // // Additionally, we need to make sure that we do not cache results // for objects that require access checks. if (receiver_obj->IsJSObject()) { if (!receiver_obj->IsJSGlobalProxy() && !receiver_obj->IsAccessCheckNeeded() && key_obj->IsName()) { DisallowHeapAllocation no_allocation; Handle<JSObject> receiver = Handle<JSObject>::cast(receiver_obj); Handle<Name> key = Handle<Name>::cast(key_obj); if (receiver->HasFastProperties()) { // Attempt to use lookup cache. Handle<Map> receiver_map(receiver->map(), isolate); KeyedLookupCache* keyed_lookup_cache = isolate->keyed_lookup_cache(); int index = keyed_lookup_cache->Lookup(receiver_map, key); if (index != -1) { // Doubles are not cached, so raw read the value. return receiver->RawFastPropertyAt( FieldIndex::ForKeyedLookupCacheIndex(*receiver_map, index)); } // Lookup cache miss. Perform lookup and update the cache if // appropriate. LookupIterator it(receiver, key, LookupIterator::OWN); if (it.state() == LookupIterator::DATA && it.property_details().type() == FIELD) { FieldIndex field_index = it.GetFieldIndex(); // Do not track double fields in the keyed lookup cache. Reading // double values requires boxing. if (!it.representation().IsDouble()) { keyed_lookup_cache->Update(receiver_map, key, field_index.GetKeyedLookupCacheIndex()); } AllowHeapAllocation allow_allocation; return *JSObject::FastPropertyAt(receiver, it.representation(), field_index); } } else { // Attempt dictionary lookup. NameDictionary* dictionary = receiver->property_dictionary(); int entry = dictionary->FindEntry(key); if ((entry != NameDictionary::kNotFound) && (dictionary->DetailsAt(entry).type() == NORMAL)) { Object* value = dictionary->ValueAt(entry); if (!receiver->IsGlobalObject()) return value; value = PropertyCell::cast(value)->value(); if (!value->IsTheHole()) return value; // If value is the hole (meaning, absent) do the general lookup. } } } else if (key_obj->IsSmi()) { // JSObject without a name key. If the key is a Smi, check for a // definite out-of-bounds access to elements, which is a strong indicator // that subsequent accesses will also call the runtime. Proactively // transition elements to FAST_*_ELEMENTS to avoid excessive boxing of // doubles for those future calls in the case that the elements would // become FAST_DOUBLE_ELEMENTS. Handle<JSObject> js_object = Handle<JSObject>::cast(receiver_obj); ElementsKind elements_kind = js_object->GetElementsKind(); if (IsFastDoubleElementsKind(elements_kind)) { Handle<Smi> key = Handle<Smi>::cast(key_obj); if (key->value() >= js_object->elements()->length()) { if (IsFastHoleyElementsKind(elements_kind)) { elements_kind = FAST_HOLEY_ELEMENTS; } else { elements_kind = FAST_ELEMENTS; } RETURN_FAILURE_ON_EXCEPTION( isolate, TransitionElements(js_object, elements_kind, isolate)); } } else { DCHECK(IsFastSmiOrObjectElementsKind(elements_kind) || !IsFastElementsKind(elements_kind)); } } } else if (receiver_obj->IsString() && key_obj->IsSmi()) { // Fast case for string indexing using [] with a smi index. Handle<String> str = Handle<String>::cast(receiver_obj); int index = args.smi_at(1); if (index >= 0 && index < str->length()) { return *GetCharAt(str, index); } } // Fall back to GetObjectProperty. Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Runtime::GetObjectProperty(isolate, receiver_obj, key_obj)); return *result; } static bool IsValidAccessor(Handle<Object> obj) { return obj->IsUndefined() || obj->IsSpecFunction() || obj->IsNull(); } // Transform getter or setter into something DefineAccessor can handle. static Handle<Object> InstantiateAccessorComponent(Isolate* isolate, Handle<Object> component) { if (component->IsUndefined()) return isolate->factory()->undefined_value(); Handle<FunctionTemplateInfo> info = Handle<FunctionTemplateInfo>::cast(component); return Utils::OpenHandle(*Utils::ToLocal(info)->GetFunction()); } RUNTIME_FUNCTION(Runtime_DefineApiAccessorProperty) { HandleScope scope(isolate); DCHECK(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2); CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3); CONVERT_SMI_ARG_CHECKED(attribute, 4); RUNTIME_ASSERT(getter->IsUndefined() || getter->IsFunctionTemplateInfo()); RUNTIME_ASSERT(setter->IsUndefined() || setter->IsFunctionTemplateInfo()); RUNTIME_ASSERT(PropertyDetails::AttributesField::is_valid( static_cast<PropertyAttributes>(attribute))); RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::DefineAccessor( object, name, InstantiateAccessorComponent(isolate, getter), InstantiateAccessorComponent(isolate, setter), static_cast<PropertyAttributes>(attribute))); return isolate->heap()->undefined_value(); } // Implements part of 8.12.9 DefineOwnProperty. // There are 3 cases that lead here: // Step 4b - define a new accessor property. // Steps 9c & 12 - replace an existing data property with an accessor property. // Step 12 - update an existing accessor property with an accessor or generic // descriptor. RUNTIME_FUNCTION(Runtime_DefineAccessorPropertyUnchecked) { HandleScope scope(isolate); DCHECK(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); RUNTIME_ASSERT(!obj->IsNull()); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2); RUNTIME_ASSERT(IsValidAccessor(getter)); CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3); RUNTIME_ASSERT(IsValidAccessor(setter)); CONVERT_SMI_ARG_CHECKED(unchecked, 4); RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0); PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked); bool fast = obj->HasFastProperties(); RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::DefineAccessor(obj, name, getter, setter, attr)); if (fast) JSObject::MigrateSlowToFast(obj, 0); return isolate->heap()->undefined_value(); } // Implements part of 8.12.9 DefineOwnProperty. // There are 3 cases that lead here: // Step 4a - define a new data property. // Steps 9b & 12 - replace an existing accessor property with a data property. // Step 12 - update an existing data property with a data or generic // descriptor. RUNTIME_FUNCTION(Runtime_DefineDataPropertyUnchecked) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSObject, js_object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); CONVERT_ARG_HANDLE_CHECKED(Object, obj_value, 2); CONVERT_SMI_ARG_CHECKED(unchecked, 3); RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0); PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked); LookupIterator it(js_object, name, LookupIterator::OWN_SKIP_INTERCEPTOR); if (it.IsFound() && it.state() == LookupIterator::ACCESS_CHECK) { if (!isolate->MayNamedAccess(js_object, name, v8::ACCESS_SET)) { return isolate->heap()->undefined_value(); } it.Next(); } // Take special care when attributes are different and there is already // a property. if (it.state() == LookupIterator::ACCESSOR) { // Use IgnoreAttributes version since a readonly property may be // overridden and SetProperty does not allow this. Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetOwnPropertyIgnoreAttributes( js_object, name, obj_value, attr, JSObject::DONT_FORCE_FIELD)); return *result; } Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Runtime::DefineObjectProperty(js_object, name, obj_value, attr)); return *result; } // Return property without being observable by accessors or interceptors. RUNTIME_FUNCTION(Runtime_GetDataProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); return *JSObject::GetDataProperty(object, key); } MaybeHandle<Object> Runtime::SetObjectProperty(Isolate* isolate, Handle<Object> object, Handle<Object> key, Handle<Object> value, StrictMode strict_mode) { if (object->IsUndefined() || object->IsNull()) { Handle<Object> args[2] = {key, object}; THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_store", HandleVector(args, 2)), Object); } if (object->IsJSProxy()) { Handle<Object> name_object; if (key->IsSymbol()) { name_object = key; } else { ASSIGN_RETURN_ON_EXCEPTION(isolate, name_object, Execution::ToString(isolate, key), Object); } Handle<Name> name = Handle<Name>::cast(name_object); return Object::SetProperty(Handle<JSProxy>::cast(object), name, value, strict_mode); } // Check if the given key is an array index. uint32_t index; if (key->ToArrayIndex(&index)) { // TODO(verwaest): Support non-JSObject receivers. if (!object->IsJSObject()) return value; Handle<JSObject> js_object = Handle<JSObject>::cast(object); // In Firefox/SpiderMonkey, Safari and Opera you can access the characters // of a string using [] notation. We need to support this too in // JavaScript. // In the case of a String object we just need to redirect the assignment to // the underlying string if the index is in range. Since the underlying // string does nothing with the assignment then we can ignore such // assignments. if (js_object->IsStringObjectWithCharacterAt(index)) { return value; } JSObject::ValidateElements(js_object); if (js_object->HasExternalArrayElements() || js_object->HasFixedTypedArrayElements()) { if (!value->IsNumber() && !value->IsUndefined()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, value, Execution::ToNumber(isolate, value), Object); } } MaybeHandle<Object> result = JSObject::SetElement( js_object, index, value, NONE, strict_mode, true, SET_PROPERTY); JSObject::ValidateElements(js_object); return result.is_null() ? result : value; } if (key->IsName()) { Handle<Name> name = Handle<Name>::cast(key); if (name->AsArrayIndex(&index)) { // TODO(verwaest): Support non-JSObject receivers. if (!object->IsJSObject()) return value; Handle<JSObject> js_object = Handle<JSObject>::cast(object); if (js_object->HasExternalArrayElements()) { if (!value->IsNumber() && !value->IsUndefined()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, value, Execution::ToNumber(isolate, value), Object); } } return JSObject::SetElement(js_object, index, value, NONE, strict_mode, true, SET_PROPERTY); } else { if (name->IsString()) name = String::Flatten(Handle<String>::cast(name)); return Object::SetProperty(object, name, value, strict_mode); } } // Call-back into JavaScript to convert the key to a string. Handle<Object> converted; ASSIGN_RETURN_ON_EXCEPTION(isolate, converted, Execution::ToString(isolate, key), Object); Handle<String> name = Handle<String>::cast(converted); if (name->AsArrayIndex(&index)) { // TODO(verwaest): Support non-JSObject receivers. if (!object->IsJSObject()) return value; Handle<JSObject> js_object = Handle<JSObject>::cast(object); return JSObject::SetElement(js_object, index, value, NONE, strict_mode, true, SET_PROPERTY); } return Object::SetProperty(object, name, value, strict_mode); } MaybeHandle<Object> Runtime::DefineObjectProperty(Handle<JSObject> js_object, Handle<Object> key, Handle<Object> value, PropertyAttributes attr) { Isolate* isolate = js_object->GetIsolate(); // Check if the given key is an array index. uint32_t index; if (key->ToArrayIndex(&index)) { // In Firefox/SpiderMonkey, Safari and Opera you can access the characters // of a string using [] notation. We need to support this too in // JavaScript. // In the case of a String object we just need to redirect the assignment to // the underlying string if the index is in range. Since the underlying // string does nothing with the assignment then we can ignore such // assignments. if (js_object->IsStringObjectWithCharacterAt(index)) { return value; } return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false, DEFINE_PROPERTY); } if (key->IsName()) { Handle<Name> name = Handle<Name>::cast(key); if (name->AsArrayIndex(&index)) { return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false, DEFINE_PROPERTY); } else { if (name->IsString()) name = String::Flatten(Handle<String>::cast(name)); return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value, attr); } } // Call-back into JavaScript to convert the key to a string. Handle<Object> converted; ASSIGN_RETURN_ON_EXCEPTION(isolate, converted, Execution::ToString(isolate, key), Object); Handle<String> name = Handle<String>::cast(converted); if (name->AsArrayIndex(&index)) { return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false, DEFINE_PROPERTY); } else { return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value, attr); } } MaybeHandle<Object> Runtime::DeleteObjectProperty(Isolate* isolate, Handle<JSReceiver> receiver, Handle<Object> key, JSReceiver::DeleteMode mode) { // Check if the given key is an array index. uint32_t index; if (key->ToArrayIndex(&index)) { // In Firefox/SpiderMonkey, Safari and Opera you can access the // characters of a string using [] notation. In the case of a // String object we just need to redirect the deletion to the // underlying string if the index is in range. Since the // underlying string does nothing with the deletion, we can ignore // such deletions. if (receiver->IsStringObjectWithCharacterAt(index)) { return isolate->factory()->true_value(); } return JSReceiver::DeleteElement(receiver, index, mode); } Handle<Name> name; if (key->IsName()) { name = Handle<Name>::cast(key); } else { // Call-back into JavaScript to convert the key to a string. Handle<Object> converted; ASSIGN_RETURN_ON_EXCEPTION(isolate, converted, Execution::ToString(isolate, key), Object); name = Handle<String>::cast(converted); } if (name->IsString()) name = String::Flatten(Handle<String>::cast(name)); return JSReceiver::DeleteProperty(receiver, name, mode); } RUNTIME_FUNCTION(Runtime_SetHiddenProperty) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(String, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); RUNTIME_ASSERT(key->IsUniqueName()); return *JSObject::SetHiddenProperty(object, key, value); } RUNTIME_FUNCTION(Runtime_AddNamedProperty) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3); RUNTIME_ASSERT( (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0); // Compute attributes. PropertyAttributes attributes = static_cast<PropertyAttributes>(unchecked_attributes); #ifdef DEBUG uint32_t index = 0; DCHECK(!key->ToArrayIndex(&index)); LookupIterator it(object, key, LookupIterator::OWN_SKIP_INTERCEPTOR); Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it); if (!maybe.has_value) return isolate->heap()->exception(); RUNTIME_ASSERT(!it.IsFound()); #endif Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetOwnPropertyIgnoreAttributes(object, key, value, attributes)); return *result; } RUNTIME_FUNCTION(Runtime_AddPropertyForTemplate) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3); RUNTIME_ASSERT( (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0); // Compute attributes. PropertyAttributes attributes = static_cast<PropertyAttributes>(unchecked_attributes); #ifdef DEBUG bool duplicate; if (key->IsName()) { LookupIterator it(object, Handle<Name>::cast(key), LookupIterator::OWN_SKIP_INTERCEPTOR); Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it); DCHECK(maybe.has_value); duplicate = it.IsFound(); } else { uint32_t index = 0; RUNTIME_ASSERT(key->ToArrayIndex(&index)); Maybe<bool> maybe = JSReceiver::HasOwnElement(object, index); if (!maybe.has_value) return isolate->heap()->exception(); duplicate = maybe.value; } if (duplicate) { Handle<Object> args[1] = {key}; THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("duplicate_template_property", HandleVector(args, 1))); } #endif Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Runtime::DefineObjectProperty(object, key, value, attributes)); return *result; } RUNTIME_FUNCTION(Runtime_SetProperty) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode_arg, 3); StrictMode strict_mode = strict_mode_arg; Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Runtime::SetObjectProperty(isolate, object, key, value, strict_mode)); return *result; } // Adds an element to an array. // This is used to create an indexed data property into an array. RUNTIME_FUNCTION(Runtime_AddElement) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3); RUNTIME_ASSERT( (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0); // Compute attributes. PropertyAttributes attributes = static_cast<PropertyAttributes>(unchecked_attributes); uint32_t index = 0; key->ToArrayIndex(&index); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::SetElement(object, index, value, attributes, SLOPPY, false, DEFINE_PROPERTY)); return *result; } RUNTIME_FUNCTION(Runtime_TransitionElementsKind) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0); CONVERT_ARG_HANDLE_CHECKED(Map, map, 1); JSObject::TransitionElementsKind(array, map->elements_kind()); return *array; } // Set the native flag on the function. // This is used to decide if we should transform null and undefined // into the global object when doing call and apply. RUNTIME_FUNCTION(Runtime_SetNativeFlag) { SealHandleScope shs(isolate); RUNTIME_ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(Object, object, 0); if (object->IsJSFunction()) { JSFunction* func = JSFunction::cast(object); func->shared()->set_native(true); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_SetInlineBuiltinFlag) { SealHandleScope shs(isolate); RUNTIME_ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); if (object->IsJSFunction()) { JSFunction* func = JSFunction::cast(*object); func->shared()->set_inline_builtin(true); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_StoreArrayLiteralElement) { HandleScope scope(isolate); RUNTIME_ASSERT(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_SMI_ARG_CHECKED(store_index, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 3); CONVERT_SMI_ARG_CHECKED(literal_index, 4); Object* raw_literal_cell = literals->get(literal_index); JSArray* boilerplate = NULL; if (raw_literal_cell->IsAllocationSite()) { AllocationSite* site = AllocationSite::cast(raw_literal_cell); boilerplate = JSArray::cast(site->transition_info()); } else { boilerplate = JSArray::cast(raw_literal_cell); } Handle<JSArray> boilerplate_object(boilerplate); ElementsKind elements_kind = object->GetElementsKind(); DCHECK(IsFastElementsKind(elements_kind)); // Smis should never trigger transitions. DCHECK(!value->IsSmi()); if (value->IsNumber()) { DCHECK(IsFastSmiElementsKind(elements_kind)); ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind) ? FAST_HOLEY_DOUBLE_ELEMENTS : FAST_DOUBLE_ELEMENTS; if (IsMoreGeneralElementsKindTransition( boilerplate_object->GetElementsKind(), transitioned_kind)) { JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind); } JSObject::TransitionElementsKind(object, transitioned_kind); DCHECK(IsFastDoubleElementsKind(object->GetElementsKind())); FixedDoubleArray* double_array = FixedDoubleArray::cast(object->elements()); HeapNumber* number = HeapNumber::cast(*value); double_array->set(store_index, number->Number()); } else { if (!IsFastObjectElementsKind(elements_kind)) { ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind) ? FAST_HOLEY_ELEMENTS : FAST_ELEMENTS; JSObject::TransitionElementsKind(object, transitioned_kind); ElementsKind boilerplate_elements_kind = boilerplate_object->GetElementsKind(); if (IsMoreGeneralElementsKindTransition(boilerplate_elements_kind, transitioned_kind)) { JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind); } } FixedArray* object_array = FixedArray::cast(object->elements()); object_array->set(store_index, *value); } return *object; } // Check whether debugger and is about to step into the callback that is passed // to a built-in function such as Array.forEach. RUNTIME_FUNCTION(Runtime_DebugCallbackSupportsStepping) { DCHECK(args.length() == 1); if (!isolate->debug()->is_active() || !isolate->debug()->StepInActive()) { return isolate->heap()->false_value(); } CONVERT_ARG_CHECKED(Object, callback, 0); // We do not step into the callback if it's a builtin or not even a function. return isolate->heap()->ToBoolean(callback->IsJSFunction() && !JSFunction::cast(callback)->IsBuiltin()); } // Set one shot breakpoints for the callback function that is passed to a // built-in function such as Array.forEach to enable stepping into the callback. RUNTIME_FUNCTION(Runtime_DebugPrepareStepInIfStepping) { DCHECK(args.length() == 1); Debug* debug = isolate->debug(); if (!debug->IsStepping()) return isolate->heap()->undefined_value(); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); RUNTIME_ASSERT(object->IsJSFunction() || object->IsJSGeneratorObject()); Handle<JSFunction> fun; if (object->IsJSFunction()) { fun = Handle<JSFunction>::cast(object); } else { fun = Handle<JSFunction>( Handle<JSGeneratorObject>::cast(object)->function(), isolate); } // When leaving the function, step out has been activated, but not performed // if we do not leave the builtin. To be able to step into the function // again, we need to clear the step out at this point. debug->ClearStepOut(); debug->FloodWithOneShot(fun); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugPushPromise) { DCHECK(args.length() == 1); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0); isolate->PushPromise(promise); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugPopPromise) { DCHECK(args.length() == 0); SealHandleScope shs(isolate); isolate->PopPromise(); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugPromiseEvent) { DCHECK(args.length() == 1); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0); isolate->debug()->OnPromiseEvent(data); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugPromiseRejectEvent) { DCHECK(args.length() == 2); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0); CONVERT_ARG_HANDLE_CHECKED(Object, value, 1); isolate->debug()->OnPromiseReject(promise, value); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugAsyncTaskEvent) { DCHECK(args.length() == 1); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0); isolate->debug()->OnAsyncTaskEvent(data); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DeleteProperty) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 2); JSReceiver::DeleteMode delete_mode = strict_mode == STRICT ? JSReceiver::STRICT_DELETION : JSReceiver::NORMAL_DELETION; Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSReceiver::DeleteProperty(object, key, delete_mode)); return *result; } static Object* HasOwnPropertyImplementation(Isolate* isolate, Handle<JSObject> object, Handle<Name> key) { Maybe<bool> maybe = JSReceiver::HasOwnProperty(object, key); if (!maybe.has_value) return isolate->heap()->exception(); if (maybe.value) return isolate->heap()->true_value(); // Handle hidden prototypes. If there's a hidden prototype above this thing // then we have to check it for properties, because they are supposed to // look like they are on this object. PrototypeIterator iter(isolate, object); if (!iter.IsAtEnd() && Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)) ->map() ->is_hidden_prototype()) { // TODO(verwaest): The recursion is not necessary for keys that are array // indices. Removing this. return HasOwnPropertyImplementation( isolate, Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), key); } RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return isolate->heap()->false_value(); } RUNTIME_FUNCTION(Runtime_HasOwnProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0) CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); uint32_t index; const bool key_is_array_index = key->AsArrayIndex(&index); // Only JS objects can have properties. if (object->IsJSObject()) { Handle<JSObject> js_obj = Handle<JSObject>::cast(object); // Fast case: either the key is a real named property or it is not // an array index and there are no interceptors or hidden // prototypes. Maybe<bool> maybe = JSObject::HasRealNamedProperty(js_obj, key); if (!maybe.has_value) return isolate->heap()->exception(); DCHECK(!isolate->has_pending_exception()); if (maybe.value) { return isolate->heap()->true_value(); } Map* map = js_obj->map(); if (!key_is_array_index && !map->has_named_interceptor() && !HeapObject::cast(map->prototype())->map()->is_hidden_prototype()) { return isolate->heap()->false_value(); } // Slow case. return HasOwnPropertyImplementation(isolate, Handle<JSObject>(js_obj), Handle<Name>(key)); } else if (object->IsString() && key_is_array_index) { // Well, there is one exception: Handle [] on strings. Handle<String> string = Handle<String>::cast(object); if (index < static_cast<uint32_t>(string->length())) { return isolate->heap()->true_value(); } } return isolate->heap()->false_value(); } RUNTIME_FUNCTION(Runtime_HasProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); Maybe<bool> maybe = JSReceiver::HasProperty(receiver, key); if (!maybe.has_value) return isolate->heap()->exception(); return isolate->heap()->ToBoolean(maybe.value); } RUNTIME_FUNCTION(Runtime_HasElement) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0); CONVERT_SMI_ARG_CHECKED(index, 1); Maybe<bool> maybe = JSReceiver::HasElement(receiver, index); if (!maybe.has_value) return isolate->heap()->exception(); return isolate->heap()->ToBoolean(maybe.value); } RUNTIME_FUNCTION(Runtime_IsPropertyEnumerable) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, key, 1); Maybe<PropertyAttributes> maybe = JSReceiver::GetOwnPropertyAttributes(object, key); if (!maybe.has_value) return isolate->heap()->exception(); if (maybe.value == ABSENT) maybe.value = DONT_ENUM; return isolate->heap()->ToBoolean((maybe.value & DONT_ENUM) == 0); } RUNTIME_FUNCTION(Runtime_GetPropertyNames) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0); Handle<JSArray> result; isolate->counters()->for_in()->Increment(); Handle<FixedArray> elements; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, elements, JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS)); return *isolate->factory()->NewJSArrayWithElements(elements); } // Returns either a FixedArray as Runtime_GetPropertyNames, // or, if the given object has an enum cache that contains // all enumerable properties of the object and its prototypes // have none, the map of the object. This is used to speed up // the check for deletions during a for-in. RUNTIME_FUNCTION(Runtime_GetPropertyNamesFast) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, raw_object, 0); if (raw_object->IsSimpleEnum()) return raw_object->map(); HandleScope scope(isolate); Handle<JSReceiver> object(raw_object); Handle<FixedArray> content; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, content, JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS)); // Test again, since cache may have been built by preceding call. if (object->IsSimpleEnum()) return object->map(); return *content; } // Find the length of the prototype chain that is to be handled as one. If a // prototype object is hidden it is to be viewed as part of the the object it // is prototype for. static int OwnPrototypeChainLength(JSObject* obj) { int count = 1; for (PrototypeIterator iter(obj->GetIsolate(), obj); !iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN); iter.Advance()) { count++; } return count; } // Return the names of the own named properties. // args[0]: object // args[1]: PropertyAttributes as int RUNTIME_FUNCTION(Runtime_GetOwnPropertyNames) { HandleScope scope(isolate); DCHECK(args.length() == 2); if (!args[0]->IsJSObject()) { return isolate->heap()->undefined_value(); } CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_SMI_ARG_CHECKED(filter_value, 1); PropertyAttributes filter = static_cast<PropertyAttributes>(filter_value); // Skip the global proxy as it has no properties and always delegates to the // real global object. if (obj->IsJSGlobalProxy()) { // Only collect names if access is permitted. if (obj->IsAccessCheckNeeded() && !isolate->MayNamedAccess(obj, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(obj, v8::ACCESS_KEYS); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return *isolate->factory()->NewJSArray(0); } PrototypeIterator iter(isolate, obj); obj = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); } // Find the number of objects making up this. int length = OwnPrototypeChainLength(*obj); // Find the number of own properties for each of the objects. ScopedVector<int> own_property_count(length); int total_property_count = 0; { PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER); for (int i = 0; i < length; i++) { DCHECK(!iter.IsAtEnd()); Handle<JSObject> jsproto = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); // Only collect names if access is permitted. if (jsproto->IsAccessCheckNeeded() && !isolate->MayNamedAccess(jsproto, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(jsproto, v8::ACCESS_KEYS); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return *isolate->factory()->NewJSArray(0); } int n; n = jsproto->NumberOfOwnProperties(filter); own_property_count[i] = n; total_property_count += n; iter.Advance(); } } // Allocate an array with storage for all the property names. Handle<FixedArray> names = isolate->factory()->NewFixedArray(total_property_count); // Get the property names. int next_copy_index = 0; int hidden_strings = 0; { PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER); for (int i = 0; i < length; i++) { DCHECK(!iter.IsAtEnd()); Handle<JSObject> jsproto = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); jsproto->GetOwnPropertyNames(*names, next_copy_index, filter); if (i > 0) { // Names from hidden prototypes may already have been added // for inherited function template instances. Count the duplicates // and stub them out; the final copy pass at the end ignores holes. for (int j = next_copy_index; j < next_copy_index + own_property_count[i]; j++) { Object* name_from_hidden_proto = names->get(j); for (int k = 0; k < next_copy_index; k++) { if (names->get(k) != isolate->heap()->hidden_string()) { Object* name = names->get(k); if (name_from_hidden_proto == name) { names->set(j, isolate->heap()->hidden_string()); hidden_strings++; break; } } } } } next_copy_index += own_property_count[i]; // Hidden properties only show up if the filter does not skip strings. if ((filter & STRING) == 0 && JSObject::HasHiddenProperties(jsproto)) { hidden_strings++; } iter.Advance(); } } // Filter out name of hidden properties object and // hidden prototype duplicates. if (hidden_strings > 0) { Handle<FixedArray> old_names = names; names = isolate->factory()->NewFixedArray(names->length() - hidden_strings); int dest_pos = 0; for (int i = 0; i < total_property_count; i++) { Object* name = old_names->get(i); if (name == isolate->heap()->hidden_string()) { hidden_strings--; continue; } names->set(dest_pos++, name); } DCHECK_EQ(0, hidden_strings); } return *isolate->factory()->NewJSArrayWithElements(names); } // Return the names of the own indexed properties. // args[0]: object RUNTIME_FUNCTION(Runtime_GetOwnElementNames) { HandleScope scope(isolate); DCHECK(args.length() == 1); if (!args[0]->IsJSObject()) { return isolate->heap()->undefined_value(); } CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); int n = obj->NumberOfOwnElements(static_cast<PropertyAttributes>(NONE)); Handle<FixedArray> names = isolate->factory()->NewFixedArray(n); obj->GetOwnElementKeys(*names, static_cast<PropertyAttributes>(NONE)); return *isolate->factory()->NewJSArrayWithElements(names); } // Return information on whether an object has a named or indexed interceptor. // args[0]: object RUNTIME_FUNCTION(Runtime_GetInterceptorInfo) { HandleScope scope(isolate); DCHECK(args.length() == 1); if (!args[0]->IsJSObject()) { return Smi::FromInt(0); } CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); int result = 0; if (obj->HasNamedInterceptor()) result |= 2; if (obj->HasIndexedInterceptor()) result |= 1; return Smi::FromInt(result); } // Return property names from named interceptor. // args[0]: object RUNTIME_FUNCTION(Runtime_GetNamedInterceptorPropertyNames) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); if (obj->HasNamedInterceptor()) { Handle<JSObject> result; if (JSObject::GetKeysForNamedInterceptor(obj, obj).ToHandle(&result)) { return *result; } } return isolate->heap()->undefined_value(); } // Return element names from indexed interceptor. // args[0]: object RUNTIME_FUNCTION(Runtime_GetIndexedInterceptorElementNames) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); if (obj->HasIndexedInterceptor()) { Handle<JSObject> result; if (JSObject::GetKeysForIndexedInterceptor(obj, obj).ToHandle(&result)) { return *result; } } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_OwnKeys) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, raw_object, 0); Handle<JSObject> object(raw_object); if (object->IsJSGlobalProxy()) { // Do access checks before going to the global object. if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(object, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS); RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate); return *isolate->factory()->NewJSArray(0); } PrototypeIterator iter(isolate, object); // If proxy is detached we simply return an empty array. if (iter.IsAtEnd()) return *isolate->factory()->NewJSArray(0); object = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); } Handle<FixedArray> contents; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, contents, JSReceiver::GetKeys(object, JSReceiver::OWN_ONLY)); // Some fast paths through GetKeysInFixedArrayFor reuse a cached // property array and since the result is mutable we have to create // a fresh clone on each invocation. int length = contents->length(); Handle<FixedArray> copy = isolate->factory()->NewFixedArray(length); for (int i = 0; i < length; i++) { Object* entry = contents->get(i); if (entry->IsString()) { copy->set(i, entry); } else { DCHECK(entry->IsNumber()); HandleScope scope(isolate); Handle<Object> entry_handle(entry, isolate); Handle<Object> entry_str = isolate->factory()->NumberToString(entry_handle); copy->set(i, *entry_str); } } return *isolate->factory()->NewJSArrayWithElements(copy); } RUNTIME_FUNCTION(Runtime_GetArgumentsProperty) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, raw_key, 0); // Compute the frame holding the arguments. JavaScriptFrameIterator it(isolate); it.AdvanceToArgumentsFrame(); JavaScriptFrame* frame = it.frame(); // Get the actual number of provided arguments. const uint32_t n = frame->ComputeParametersCount(); // Try to convert the key to an index. If successful and within // index return the the argument from the frame. uint32_t index; if (raw_key->ToArrayIndex(&index) && index < n) { return frame->GetParameter(index); } HandleScope scope(isolate); if (raw_key->IsSymbol()) { Handle<Symbol> symbol = Handle<Symbol>::cast(raw_key); if (symbol->Equals(isolate->native_context()->iterator_symbol())) { return isolate->native_context()->array_values_iterator(); } // Lookup in the initial Object.prototype object. Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Object::GetProperty(isolate->initial_object_prototype(), Handle<Symbol>::cast(raw_key))); return *result; } // Convert the key to a string. Handle<Object> converted; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, converted, Execution::ToString(isolate, raw_key)); Handle<String> key = Handle<String>::cast(converted); // Try to convert the string key into an array index. if (key->AsArrayIndex(&index)) { if (index < n) { return frame->GetParameter(index); } else { Handle<Object> initial_prototype(isolate->initial_object_prototype()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Object::GetElement(isolate, initial_prototype, index)); return *result; } } // Handle special arguments properties. if (String::Equals(isolate->factory()->length_string(), key)) { return Smi::FromInt(n); } if (String::Equals(isolate->factory()->callee_string(), key)) { JSFunction* function = frame->function(); if (function->shared()->strict_mode() == STRICT) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("strict_arguments_callee", HandleVector<Object>(NULL, 0))); } return function; } // Lookup in the initial Object.prototype object. Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Object::GetProperty(isolate->initial_object_prototype(), key)); return *result; } RUNTIME_FUNCTION(Runtime_ToFastProperties) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); if (object->IsJSObject() && !object->IsGlobalObject()) { JSObject::MigrateSlowToFast(Handle<JSObject>::cast(object), 0); } return *object; } RUNTIME_FUNCTION(Runtime_ToBool) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, object, 0); return isolate->heap()->ToBoolean(object->BooleanValue()); } // Returns the type string of a value; see ECMA-262, 11.4.3 (p 47). // Possible optimizations: put the type string into the oddballs. RUNTIME_FUNCTION(Runtime_Typeof) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); if (obj->IsNumber()) return isolate->heap()->number_string(); HeapObject* heap_obj = HeapObject::cast(obj); // typeof an undetectable object is 'undefined' if (heap_obj->map()->is_undetectable()) { return isolate->heap()->undefined_string(); } InstanceType instance_type = heap_obj->map()->instance_type(); if (instance_type < FIRST_NONSTRING_TYPE) { return isolate->heap()->string_string(); } switch (instance_type) { case ODDBALL_TYPE: if (heap_obj->IsTrue() || heap_obj->IsFalse()) { return isolate->heap()->boolean_string(); } if (heap_obj->IsNull()) { return isolate->heap()->object_string(); } DCHECK(heap_obj->IsUndefined()); return isolate->heap()->undefined_string(); case SYMBOL_TYPE: return isolate->heap()->symbol_string(); case JS_FUNCTION_TYPE: case JS_FUNCTION_PROXY_TYPE: return isolate->heap()->function_string(); default: // For any kind of object not handled above, the spec rule for // host objects gives that it is okay to return "object" return isolate->heap()->object_string(); } } RUNTIME_FUNCTION(Runtime_Booleanize) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(Object, value_raw, 0); CONVERT_SMI_ARG_CHECKED(token_raw, 1); intptr_t value = reinterpret_cast<intptr_t>(value_raw); Token::Value token = static_cast<Token::Value>(token_raw); switch (token) { case Token::EQ: case Token::EQ_STRICT: return isolate->heap()->ToBoolean(value == 0); case Token::NE: case Token::NE_STRICT: return isolate->heap()->ToBoolean(value != 0); case Token::LT: return isolate->heap()->ToBoolean(value < 0); case Token::GT: return isolate->heap()->ToBoolean(value > 0); case Token::LTE: return isolate->heap()->ToBoolean(value <= 0); case Token::GTE: return isolate->heap()->ToBoolean(value >= 0); default: // This should only happen during natives fuzzing. return isolate->heap()->undefined_value(); } } RUNTIME_FUNCTION(Runtime_NewStringWrapper) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(String, value, 0); return *Object::ToObject(isolate, value).ToHandleChecked(); } RUNTIME_FUNCTION(Runtime_AllocateHeapNumber) { HandleScope scope(isolate); DCHECK(args.length() == 0); return *isolate->factory()->NewHeapNumber(0); } RUNTIME_FUNCTION(Runtime_DateMakeDay) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_SMI_ARG_CHECKED(year, 0); CONVERT_SMI_ARG_CHECKED(month, 1); int days = isolate->date_cache()->DaysFromYearMonth(year, month); RUNTIME_ASSERT(Smi::IsValid(days)); return Smi::FromInt(days); } RUNTIME_FUNCTION(Runtime_DateSetValue) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 0); CONVERT_DOUBLE_ARG_CHECKED(time, 1); CONVERT_SMI_ARG_CHECKED(is_utc, 2); DateCache* date_cache = isolate->date_cache(); Handle<Object> value; ; bool is_value_nan = false; if (std::isnan(time)) { value = isolate->factory()->nan_value(); is_value_nan = true; } else if (!is_utc && (time < -DateCache::kMaxTimeBeforeUTCInMs || time > DateCache::kMaxTimeBeforeUTCInMs)) { value = isolate->factory()->nan_value(); is_value_nan = true; } else { time = is_utc ? time : date_cache->ToUTC(static_cast<int64_t>(time)); if (time < -DateCache::kMaxTimeInMs || time > DateCache::kMaxTimeInMs) { value = isolate->factory()->nan_value(); is_value_nan = true; } else { value = isolate->factory()->NewNumber(DoubleToInteger(time)); } } date->SetValue(*value, is_value_nan); return *value; } static Handle<JSObject> NewSloppyArguments(Isolate* isolate, Handle<JSFunction> callee, Object** parameters, int argument_count) { Handle<JSObject> result = isolate->factory()->NewArgumentsObject(callee, argument_count); // Allocate the elements if needed. int parameter_count = callee->shared()->formal_parameter_count(); if (argument_count > 0) { if (parameter_count > 0) { int mapped_count = Min(argument_count, parameter_count); Handle<FixedArray> parameter_map = isolate->factory()->NewFixedArray(mapped_count + 2, NOT_TENURED); parameter_map->set_map(isolate->heap()->sloppy_arguments_elements_map()); Handle<Map> map = Map::Copy(handle(result->map())); map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS); result->set_map(*map); result->set_elements(*parameter_map); // Store the context and the arguments array at the beginning of the // parameter map. Handle<Context> context(isolate->context()); Handle<FixedArray> arguments = isolate->factory()->NewFixedArray(argument_count, NOT_TENURED); parameter_map->set(0, *context); parameter_map->set(1, *arguments); // Loop over the actual parameters backwards. int index = argument_count - 1; while (index >= mapped_count) { // These go directly in the arguments array and have no // corresponding slot in the parameter map. arguments->set(index, *(parameters - index - 1)); --index; } Handle<ScopeInfo> scope_info(callee->shared()->scope_info()); while (index >= 0) { // Detect duplicate names to the right in the parameter list. Handle<String> name(scope_info->ParameterName(index)); int context_local_count = scope_info->ContextLocalCount(); bool duplicate = false; for (int j = index + 1; j < parameter_count; ++j) { if (scope_info->ParameterName(j) == *name) { duplicate = true; break; } } if (duplicate) { // This goes directly in the arguments array with a hole in the // parameter map. arguments->set(index, *(parameters - index - 1)); parameter_map->set_the_hole(index + 2); } else { // The context index goes in the parameter map with a hole in the // arguments array. int context_index = -1; for (int j = 0; j < context_local_count; ++j) { if (scope_info->ContextLocalName(j) == *name) { context_index = j; break; } } DCHECK(context_index >= 0); arguments->set_the_hole(index); parameter_map->set( index + 2, Smi::FromInt(Context::MIN_CONTEXT_SLOTS + context_index)); } --index; } } else { // If there is no aliasing, the arguments object elements are not // special in any way. Handle<FixedArray> elements = isolate->factory()->NewFixedArray(argument_count, NOT_TENURED); result->set_elements(*elements); for (int i = 0; i < argument_count; ++i) { elements->set(i, *(parameters - i - 1)); } } } return result; } static Handle<JSObject> NewStrictArguments(Isolate* isolate, Handle<JSFunction> callee, Object** parameters, int argument_count) { Handle<JSObject> result = isolate->factory()->NewArgumentsObject(callee, argument_count); if (argument_count > 0) { Handle<FixedArray> array = isolate->factory()->NewUninitializedFixedArray(argument_count); DisallowHeapAllocation no_gc; WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc); for (int i = 0; i < argument_count; i++) { array->set(i, *--parameters, mode); } result->set_elements(*array); } return result; } RUNTIME_FUNCTION(Runtime_NewArguments) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0); JavaScriptFrameIterator it(isolate); // Find the frame that holds the actual arguments passed to the function. it.AdvanceToArgumentsFrame(); JavaScriptFrame* frame = it.frame(); // Determine parameter location on the stack and dispatch on language mode. int argument_count = frame->GetArgumentsLength(); Object** parameters = reinterpret_cast<Object**>(frame->GetParameterSlot(-1)); return callee->shared()->strict_mode() == STRICT ? *NewStrictArguments(isolate, callee, parameters, argument_count) : *NewSloppyArguments(isolate, callee, parameters, argument_count); } RUNTIME_FUNCTION(Runtime_NewSloppyArguments) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0); Object** parameters = reinterpret_cast<Object**>(args[1]); CONVERT_SMI_ARG_CHECKED(argument_count, 2); return *NewSloppyArguments(isolate, callee, parameters, argument_count); } RUNTIME_FUNCTION(Runtime_NewStrictArguments) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0) Object** parameters = reinterpret_cast<Object**>(args[1]); CONVERT_SMI_ARG_CHECKED(argument_count, 2); return *NewStrictArguments(isolate, callee, parameters, argument_count); } RUNTIME_FUNCTION(Runtime_NewClosureFromStubFailure) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0); Handle<Context> context(isolate->context()); PretenureFlag pretenure_flag = NOT_TENURED; return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context, pretenure_flag); } RUNTIME_FUNCTION(Runtime_NewClosure) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(Context, context, 0); CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 1); CONVERT_BOOLEAN_ARG_CHECKED(pretenure, 2); // The caller ensures that we pretenure closures that are assigned // directly to properties. PretenureFlag pretenure_flag = pretenure ? TENURED : NOT_TENURED; return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context, pretenure_flag); } // Find the arguments of the JavaScript function invocation that called // into C++ code. Collect these in a newly allocated array of handles (possibly // prefixed by a number of empty handles). static SmartArrayPointer<Handle<Object> > GetCallerArguments(Isolate* isolate, int prefix_argc, int* total_argc) { // Find frame containing arguments passed to the caller. JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); List<JSFunction*> functions(2); frame->GetFunctions(&functions); if (functions.length() > 1) { int inlined_jsframe_index = functions.length() - 1; JSFunction* inlined_function = functions[inlined_jsframe_index]; SlotRefValueBuilder slot_refs( frame, inlined_jsframe_index, inlined_function->shared()->formal_parameter_count()); int args_count = slot_refs.args_length(); *total_argc = prefix_argc + args_count; SmartArrayPointer<Handle<Object> > param_data( NewArray<Handle<Object> >(*total_argc)); slot_refs.Prepare(isolate); for (int i = 0; i < args_count; i++) { Handle<Object> val = slot_refs.GetNext(isolate, 0); param_data[prefix_argc + i] = val; } slot_refs.Finish(isolate); return param_data; } else { it.AdvanceToArgumentsFrame(); frame = it.frame(); int args_count = frame->ComputeParametersCount(); *total_argc = prefix_argc + args_count; SmartArrayPointer<Handle<Object> > param_data( NewArray<Handle<Object> >(*total_argc)); for (int i = 0; i < args_count; i++) { Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate); param_data[prefix_argc + i] = val; } return param_data; } } RUNTIME_FUNCTION(Runtime_FunctionBindArguments) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSFunction, bound_function, 0); CONVERT_ARG_HANDLE_CHECKED(Object, bindee, 1); CONVERT_ARG_HANDLE_CHECKED(Object, this_object, 2); CONVERT_NUMBER_ARG_HANDLE_CHECKED(new_length, 3); // TODO(lrn): Create bound function in C++ code from premade shared info. bound_function->shared()->set_bound(true); // Get all arguments of calling function (Function.prototype.bind). int argc = 0; SmartArrayPointer<Handle<Object> > arguments = GetCallerArguments(isolate, 0, &argc); // Don't count the this-arg. if (argc > 0) { RUNTIME_ASSERT(arguments[0].is_identical_to(this_object)); argc--; } else { RUNTIME_ASSERT(this_object->IsUndefined()); } // Initialize array of bindings (function, this, and any existing arguments // if the function was already bound). Handle<FixedArray> new_bindings; int i; if (bindee->IsJSFunction() && JSFunction::cast(*bindee)->shared()->bound()) { Handle<FixedArray> old_bindings( JSFunction::cast(*bindee)->function_bindings()); RUNTIME_ASSERT(old_bindings->length() > JSFunction::kBoundFunctionIndex); new_bindings = isolate->factory()->NewFixedArray(old_bindings->length() + argc); bindee = Handle<Object>(old_bindings->get(JSFunction::kBoundFunctionIndex), isolate); i = 0; for (int n = old_bindings->length(); i < n; i++) { new_bindings->set(i, old_bindings->get(i)); } } else { int array_size = JSFunction::kBoundArgumentsStartIndex + argc; new_bindings = isolate->factory()->NewFixedArray(array_size); new_bindings->set(JSFunction::kBoundFunctionIndex, *bindee); new_bindings->set(JSFunction::kBoundThisIndex, *this_object); i = 2; } // Copy arguments, skipping the first which is "this_arg". for (int j = 0; j < argc; j++, i++) { new_bindings->set(i, *arguments[j + 1]); } new_bindings->set_map_no_write_barrier( isolate->heap()->fixed_cow_array_map()); bound_function->set_function_bindings(*new_bindings); // Update length. Have to remove the prototype first so that map migration // is happy about the number of fields. RUNTIME_ASSERT(bound_function->RemovePrototype()); Handle<Map> bound_function_map( isolate->native_context()->bound_function_map()); JSObject::MigrateToMap(bound_function, bound_function_map); Handle<String> length_string = isolate->factory()->length_string(); PropertyAttributes attr = static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY); RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::SetOwnPropertyIgnoreAttributes( bound_function, length_string, new_length, attr)); return *bound_function; } RUNTIME_FUNCTION(Runtime_BoundFunctionGetBindings) { HandleScope handles(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, callable, 0); if (callable->IsJSFunction()) { Handle<JSFunction> function = Handle<JSFunction>::cast(callable); if (function->shared()->bound()) { Handle<FixedArray> bindings(function->function_bindings()); RUNTIME_ASSERT(bindings->map() == isolate->heap()->fixed_cow_array_map()); return *isolate->factory()->NewJSArrayWithElements(bindings); } } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_NewObjectFromBound) { HandleScope scope(isolate); DCHECK(args.length() == 1); // First argument is a function to use as a constructor. CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); RUNTIME_ASSERT(function->shared()->bound()); // The argument is a bound function. Extract its bound arguments // and callable. Handle<FixedArray> bound_args = Handle<FixedArray>(FixedArray::cast(function->function_bindings())); int bound_argc = bound_args->length() - JSFunction::kBoundArgumentsStartIndex; Handle<Object> bound_function( JSReceiver::cast(bound_args->get(JSFunction::kBoundFunctionIndex)), isolate); DCHECK(!bound_function->IsJSFunction() || !Handle<JSFunction>::cast(bound_function)->shared()->bound()); int total_argc = 0; SmartArrayPointer<Handle<Object> > param_data = GetCallerArguments(isolate, bound_argc, &total_argc); for (int i = 0; i < bound_argc; i++) { param_data[i] = Handle<Object>( bound_args->get(JSFunction::kBoundArgumentsStartIndex + i), isolate); } if (!bound_function->IsJSFunction()) { ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, bound_function, Execution::TryGetConstructorDelegate(isolate, bound_function)); } DCHECK(bound_function->IsJSFunction()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Execution::New(Handle<JSFunction>::cast(bound_function), total_argc, param_data.get())); return *result; } static Object* Runtime_NewObjectHelper(Isolate* isolate, Handle<Object> constructor, Handle<AllocationSite> site) { // If the constructor isn't a proper function we throw a type error. if (!constructor->IsJSFunction()) { Vector<Handle<Object> > arguments = HandleVector(&constructor, 1); THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewTypeError("not_constructor", arguments)); } Handle<JSFunction> function = Handle<JSFunction>::cast(constructor); // If function should not have prototype, construction is not allowed. In this // case generated code bailouts here, since function has no initial_map. if (!function->should_have_prototype() && !function->shared()->bound()) { Vector<Handle<Object> > arguments = HandleVector(&constructor, 1); THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewTypeError("not_constructor", arguments)); } Debug* debug = isolate->debug(); // Handle stepping into constructors if step into is active. if (debug->StepInActive()) { debug->HandleStepIn(function, Handle<Object>::null(), 0, true); } if (function->has_initial_map()) { if (function->initial_map()->instance_type() == JS_FUNCTION_TYPE) { // The 'Function' function ignores the receiver object when // called using 'new' and creates a new JSFunction object that // is returned. The receiver object is only used for error // reporting if an error occurs when constructing the new // JSFunction. Factory::NewJSObject() should not be used to // allocate JSFunctions since it does not properly initialize // the shared part of the function. Since the receiver is // ignored anyway, we use the global object as the receiver // instead of a new JSFunction object. This way, errors are // reported the same way whether or not 'Function' is called // using 'new'. return isolate->global_proxy(); } } // The function should be compiled for the optimization hints to be // available. Compiler::EnsureCompiled(function, CLEAR_EXCEPTION); Handle<JSObject> result; if (site.is_null()) { result = isolate->factory()->NewJSObject(function); } else { result = isolate->factory()->NewJSObjectWithMemento(function, site); } isolate->counters()->constructed_objects()->Increment(); isolate->counters()->constructed_objects_runtime()->Increment(); return *result; } RUNTIME_FUNCTION(Runtime_NewObject) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 0); return Runtime_NewObjectHelper(isolate, constructor, Handle<AllocationSite>::null()); } RUNTIME_FUNCTION(Runtime_NewObjectWithAllocationSite) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 1); CONVERT_ARG_HANDLE_CHECKED(Object, feedback, 0); Handle<AllocationSite> site; if (feedback->IsAllocationSite()) { // The feedback can be an AllocationSite or undefined. site = Handle<AllocationSite>::cast(feedback); } return Runtime_NewObjectHelper(isolate, constructor, site); } RUNTIME_FUNCTION(Runtime_FinalizeInstanceSize) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); function->CompleteInobjectSlackTracking(); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_CheckIsBootstrapping) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); RUNTIME_ASSERT(isolate->bootstrapper()->IsActive()); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_GetRootNaN) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); RUNTIME_ASSERT(isolate->bootstrapper()->IsActive()); return isolate->heap()->nan_value(); } RUNTIME_FUNCTION(Runtime_Call) { HandleScope scope(isolate); DCHECK(args.length() >= 2); int argc = args.length() - 2; CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1); Object* receiver = args[0]; // If there are too many arguments, allocate argv via malloc. const int argv_small_size = 10; Handle<Object> argv_small_buffer[argv_small_size]; SmartArrayPointer<Handle<Object> > argv_large_buffer; Handle<Object>* argv = argv_small_buffer; if (argc > argv_small_size) { argv = new Handle<Object>[argc]; if (argv == NULL) return isolate->StackOverflow(); argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv); } for (int i = 0; i < argc; ++i) { argv[i] = Handle<Object>(args[1 + i], isolate); } Handle<JSReceiver> hfun(fun); Handle<Object> hreceiver(receiver, isolate); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Execution::Call(isolate, hfun, hreceiver, argc, argv, true)); return *result; } RUNTIME_FUNCTION(Runtime_Apply) { HandleScope scope(isolate); DCHECK(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, fun, 0); CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, arguments, 2); CONVERT_INT32_ARG_CHECKED(offset, 3); CONVERT_INT32_ARG_CHECKED(argc, 4); RUNTIME_ASSERT(offset >= 0); // Loose upper bound to allow fuzzing. We'll most likely run out of // stack space before hitting this limit. static int kMaxArgc = 1000000; RUNTIME_ASSERT(argc >= 0 && argc <= kMaxArgc); // If there are too many arguments, allocate argv via malloc. const int argv_small_size = 10; Handle<Object> argv_small_buffer[argv_small_size]; SmartArrayPointer<Handle<Object> > argv_large_buffer; Handle<Object>* argv = argv_small_buffer; if (argc > argv_small_size) { argv = new Handle<Object>[argc]; if (argv == NULL) return isolate->StackOverflow(); argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv); } for (int i = 0; i < argc; ++i) { ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, argv[i], Object::GetElement(isolate, arguments, offset + i)); } Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, Execution::Call(isolate, fun, receiver, argc, argv, true)); return *result; } RUNTIME_FUNCTION(Runtime_GetFunctionDelegate) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); RUNTIME_ASSERT(!object->IsJSFunction()); return *Execution::GetFunctionDelegate(isolate, object); } RUNTIME_FUNCTION(Runtime_GetConstructorDelegate) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); RUNTIME_ASSERT(!object->IsJSFunction()); return *Execution::GetConstructorDelegate(isolate, object); } RUNTIME_FUNCTION(Runtime_NewGlobalContext) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1); Handle<Context> result = isolate->factory()->NewGlobalContext(function, scope_info); DCHECK(function->context() == isolate->context()); DCHECK(function->context()->global_object() == result->global_object()); result->global_object()->set_global_context(*result); return *result; } RUNTIME_FUNCTION(Runtime_NewFunctionContext) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); DCHECK(function->context() == isolate->context()); int length = function->shared()->scope_info()->ContextLength(); return *isolate->factory()->NewFunctionContext(length, function); } RUNTIME_FUNCTION(Runtime_PushWithContext) { HandleScope scope(isolate); DCHECK(args.length() == 2); Handle<JSReceiver> extension_object; if (args[0]->IsJSReceiver()) { extension_object = args.at<JSReceiver>(0); } else { // Try to convert the object to a proper JavaScript object. MaybeHandle<JSReceiver> maybe_object = Object::ToObject(isolate, args.at<Object>(0)); if (!maybe_object.ToHandle(&extension_object)) { Handle<Object> handle = args.at<Object>(0); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("with_expression", HandleVector(&handle, 1))); } } Handle<JSFunction> function; if (args[1]->IsSmi()) { // A smi sentinel indicates a context nested inside global code rather // than some function. There is a canonical empty function that can be // gotten from the native context. function = handle(isolate->native_context()->closure()); } else { function = args.at<JSFunction>(1); } Handle<Context> current(isolate->context()); Handle<Context> context = isolate->factory()->NewWithContext(function, current, extension_object); isolate->set_context(*context); return *context; } RUNTIME_FUNCTION(Runtime_PushCatchContext) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(String, name, 0); CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 1); Handle<JSFunction> function; if (args[2]->IsSmi()) { // A smi sentinel indicates a context nested inside global code rather // than some function. There is a canonical empty function that can be // gotten from the native context. function = handle(isolate->native_context()->closure()); } else { function = args.at<JSFunction>(2); } Handle<Context> current(isolate->context()); Handle<Context> context = isolate->factory()->NewCatchContext( function, current, name, thrown_object); isolate->set_context(*context); return *context; } RUNTIME_FUNCTION(Runtime_PushBlockContext) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0); Handle<JSFunction> function; if (args[1]->IsSmi()) { // A smi sentinel indicates a context nested inside global code rather // than some function. There is a canonical empty function that can be // gotten from the native context. function = handle(isolate->native_context()->closure()); } else { function = args.at<JSFunction>(1); } Handle<Context> current(isolate->context()); Handle<Context> context = isolate->factory()->NewBlockContext(function, current, scope_info); isolate->set_context(*context); return *context; } RUNTIME_FUNCTION(Runtime_IsJSModule) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSModule()); } RUNTIME_FUNCTION(Runtime_PushModuleContext) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_SMI_ARG_CHECKED(index, 0); if (!args[1]->IsScopeInfo()) { // Module already initialized. Find hosting context and retrieve context. Context* host = Context::cast(isolate->context())->global_context(); Context* context = Context::cast(host->get(index)); DCHECK(context->previous() == isolate->context()); isolate->set_context(context); return context; } CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1); // Allocate module context. HandleScope scope(isolate); Factory* factory = isolate->factory(); Handle<Context> context = factory->NewModuleContext(scope_info); Handle<JSModule> module = factory->NewJSModule(context, scope_info); context->set_module(*module); Context* previous = isolate->context(); context->set_previous(previous); context->set_closure(previous->closure()); context->set_global_object(previous->global_object()); isolate->set_context(*context); // Find hosting scope and initialize internal variable holding module there. previous->global_context()->set(index, *context); return *context; } RUNTIME_FUNCTION(Runtime_DeclareModules) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, descriptions, 0); Context* host_context = isolate->context(); for (int i = 0; i < descriptions->length(); ++i) { Handle<ModuleInfo> description(ModuleInfo::cast(descriptions->get(i))); int host_index = description->host_index(); Handle<Context> context(Context::cast(host_context->get(host_index))); Handle<JSModule> module(context->module()); for (int j = 0; j < description->length(); ++j) { Handle<String> name(description->name(j)); VariableMode mode = description->mode(j); int index = description->index(j); switch (mode) { case VAR: case LET: case CONST: case CONST_LEGACY: { PropertyAttributes attr = IsImmutableVariableMode(mode) ? FROZEN : SEALED; Handle<AccessorInfo> info = Accessors::MakeModuleExport(name, index, attr); Handle<Object> result = JSObject::SetAccessor(module, info).ToHandleChecked(); DCHECK(!result->IsUndefined()); USE(result); break; } case MODULE: { Object* referenced_context = Context::cast(host_context)->get(index); Handle<JSModule> value(Context::cast(referenced_context)->module()); JSObject::SetOwnPropertyIgnoreAttributes(module, name, value, FROZEN) .Assert(); break; } case INTERNAL: case TEMPORARY: case DYNAMIC: case DYNAMIC_GLOBAL: case DYNAMIC_LOCAL: UNREACHABLE(); } } JSObject::PreventExtensions(module).Assert(); } DCHECK(!isolate->has_pending_exception()); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Context, context, 0); CONVERT_ARG_HANDLE_CHECKED(String, name, 1); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; BindingFlags binding_flags; Handle<Object> holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); // If the slot was not found the result is true. if (holder.is_null()) { return isolate->heap()->true_value(); } // If the slot was found in a context, it should be DONT_DELETE. if (holder->IsContext()) { return isolate->heap()->false_value(); } // The slot was found in a JSObject, either a context extension object, // the global object, or the subject of a with. Try to delete it // (respecting DONT_DELETE). Handle<JSObject> object = Handle<JSObject>::cast(holder); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSReceiver::DeleteProperty(object, name)); return *result; } static Object* ComputeReceiverForNonGlobal(Isolate* isolate, JSObject* holder) { DCHECK(!holder->IsGlobalObject()); Context* top = isolate->context(); // Get the context extension function. JSFunction* context_extension_function = top->native_context()->context_extension_function(); // If the holder isn't a context extension object, we just return it // as the receiver. This allows arguments objects to be used as // receivers, but only if they are put in the context scope chain // explicitly via a with-statement. Object* constructor = holder->map()->constructor(); if (constructor != context_extension_function) return holder; // Fall back to using the global object as the implicit receiver if // the property turns out to be a local variable allocated in a // context extension object - introduced via eval. return isolate->heap()->undefined_value(); } static ObjectPair LoadLookupSlotHelper(Arguments args, Isolate* isolate, bool throw_error) { HandleScope scope(isolate); DCHECK_EQ(2, args.length()); if (!args[0]->IsContext() || !args[1]->IsString()) { return MakePair(isolate->ThrowIllegalOperation(), NULL); } Handle<Context> context = args.at<Context>(0); Handle<String> name = args.at<String>(1); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; BindingFlags binding_flags; Handle<Object> holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); if (isolate->has_pending_exception()) { return MakePair(isolate->heap()->exception(), NULL); } // If the index is non-negative, the slot has been found in a context. if (index >= 0) { DCHECK(holder->IsContext()); // If the "property" we were looking for is a local variable, the // receiver is the global object; see ECMA-262, 3rd., 10.1.6 and 10.2.3. Handle<Object> receiver = isolate->factory()->undefined_value(); Object* value = Context::cast(*holder)->get(index); // Check for uninitialized bindings. switch (binding_flags) { case MUTABLE_CHECK_INITIALIZED: case IMMUTABLE_CHECK_INITIALIZED_HARMONY: if (value->IsTheHole()) { Handle<Object> error; MaybeHandle<Object> maybe_error = isolate->factory()->NewReferenceError("not_defined", HandleVector(&name, 1)); if (maybe_error.ToHandle(&error)) isolate->Throw(*error); return MakePair(isolate->heap()->exception(), NULL); } // FALLTHROUGH case MUTABLE_IS_INITIALIZED: case IMMUTABLE_IS_INITIALIZED: case IMMUTABLE_IS_INITIALIZED_HARMONY: DCHECK(!value->IsTheHole()); return MakePair(value, *receiver); case IMMUTABLE_CHECK_INITIALIZED: if (value->IsTheHole()) { DCHECK((attributes & READ_ONLY) != 0); value = isolate->heap()->undefined_value(); } return MakePair(value, *receiver); case MISSING_BINDING: UNREACHABLE(); return MakePair(NULL, NULL); } } // Otherwise, if the slot was found the holder is a context extension // object, subject of a with, or a global object. We read the named // property from it. if (!holder.is_null()) { Handle<JSReceiver> object = Handle<JSReceiver>::cast(holder); #ifdef DEBUG if (!object->IsJSProxy()) { Maybe<bool> maybe = JSReceiver::HasProperty(object, name); DCHECK(maybe.has_value); DCHECK(maybe.value); } #endif // GetProperty below can cause GC. Handle<Object> receiver_handle( object->IsGlobalObject() ? Object::cast(isolate->heap()->undefined_value()) : object->IsJSProxy() ? static_cast<Object*>(*object) : ComputeReceiverForNonGlobal( isolate, JSObject::cast(*object)), isolate); // No need to unhole the value here. This is taken care of by the // GetProperty function. Handle<Object> value; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(object, name), MakePair(isolate->heap()->exception(), NULL)); return MakePair(*value, *receiver_handle); } if (throw_error) { // The property doesn't exist - throw exception. Handle<Object> error; MaybeHandle<Object> maybe_error = isolate->factory()->NewReferenceError( "not_defined", HandleVector(&name, 1)); if (maybe_error.ToHandle(&error)) isolate->Throw(*error); return MakePair(isolate->heap()->exception(), NULL); } else { // The property doesn't exist - return undefined. return MakePair(isolate->heap()->undefined_value(), isolate->heap()->undefined_value()); } } RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlot) { return LoadLookupSlotHelper(args, isolate, true); } RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotNoReferenceError) { return LoadLookupSlotHelper(args, isolate, false); } RUNTIME_FUNCTION(Runtime_StoreLookupSlot) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(Object, value, 0); CONVERT_ARG_HANDLE_CHECKED(Context, context, 1); CONVERT_ARG_HANDLE_CHECKED(String, name, 2); CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 3); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; BindingFlags binding_flags; Handle<Object> holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); // In case of JSProxy, an exception might have been thrown. if (isolate->has_pending_exception()) return isolate->heap()->exception(); // The property was found in a context slot. if (index >= 0) { if ((attributes & READ_ONLY) == 0) { Handle<Context>::cast(holder)->set(index, *value); } else if (strict_mode == STRICT) { // Setting read only property in strict mode. THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("strict_cannot_assign", HandleVector(&name, 1))); } return *value; } // Slow case: The property is not in a context slot. It is either in a // context extension object, a property of the subject of a with, or a // property of the global object. Handle<JSReceiver> object; if (attributes != ABSENT) { // The property exists on the holder. object = Handle<JSReceiver>::cast(holder); } else if (strict_mode == STRICT) { // If absent in strict mode: throw. THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewReferenceError("not_defined", HandleVector(&name, 1))); } else { // If absent in sloppy mode: add the property to the global object. object = Handle<JSReceiver>(context->global_object()); } RETURN_FAILURE_ON_EXCEPTION( isolate, Object::SetProperty(object, name, value, strict_mode)); return *value; } RUNTIME_FUNCTION(Runtime_Throw) { HandleScope scope(isolate); DCHECK(args.length() == 1); return isolate->Throw(args[0]); } RUNTIME_FUNCTION(Runtime_ReThrow) { HandleScope scope(isolate); DCHECK(args.length() == 1); return isolate->ReThrow(args[0]); } RUNTIME_FUNCTION(Runtime_PromoteScheduledException) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); return isolate->PromoteScheduledException(); } RUNTIME_FUNCTION(Runtime_ThrowReferenceError) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, name, 0); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewReferenceError("not_defined", HandleVector(&name, 1))); } RUNTIME_FUNCTION(Runtime_ThrowNonMethodError) { HandleScope scope(isolate); DCHECK(args.length() == 0); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewReferenceError("non_method", HandleVector<Object>(NULL, 0))); } RUNTIME_FUNCTION(Runtime_ThrowUnsupportedSuperError) { HandleScope scope(isolate); DCHECK(args.length() == 0); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewReferenceError("unsupported_super", HandleVector<Object>(NULL, 0))); } RUNTIME_FUNCTION(Runtime_ThrowNotDateError) { HandleScope scope(isolate); DCHECK(args.length() == 0); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("not_date_object", HandleVector<Object>(NULL, 0))); } RUNTIME_FUNCTION(Runtime_StackGuard) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); // First check if this is a real stack overflow. StackLimitCheck check(isolate); if (check.JsHasOverflowed()) { return isolate->StackOverflow(); } return isolate->stack_guard()->HandleInterrupts(); } RUNTIME_FUNCTION(Runtime_Interrupt) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); return isolate->stack_guard()->HandleInterrupts(); } static int StackSize(Isolate* isolate) { int n = 0; for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) n++; return n; } static void PrintTransition(Isolate* isolate, Object* result) { // indentation { const int nmax = 80; int n = StackSize(isolate); if (n <= nmax) PrintF("%4d:%*s", n, n, ""); else PrintF("%4d:%*s", n, nmax, "..."); } if (result == NULL) { JavaScriptFrame::PrintTop(isolate, stdout, true, false); PrintF(" {\n"); } else { // function result PrintF("} -> "); result->ShortPrint(); PrintF("\n"); } } RUNTIME_FUNCTION(Runtime_TraceEnter) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); PrintTransition(isolate, NULL); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_TraceExit) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); PrintTransition(isolate, obj); return obj; // return TOS } RUNTIME_FUNCTION(Runtime_DateCurrentTime) { HandleScope scope(isolate); DCHECK(args.length() == 0); if (FLAG_log_timer_events) LOG(isolate, CurrentTimeEvent()); // According to ECMA-262, section 15.9.1, page 117, the precision of // the number in a Date object representing a particular instant in // time is milliseconds. Therefore, we floor the result of getting // the OS time. double millis; if (FLAG_verify_predictable) { millis = 1388534400000.0; // Jan 1 2014 00:00:00 GMT+0000 millis += Floor(isolate->heap()->synthetic_time()); } else { millis = Floor(base::OS::TimeCurrentMillis()); } return *isolate->factory()->NewNumber(millis); } RUNTIME_FUNCTION(Runtime_DateParseString) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, str, 0); CONVERT_ARG_HANDLE_CHECKED(JSArray, output, 1); RUNTIME_ASSERT(output->HasFastElements()); JSObject::EnsureCanContainHeapObjectElements(output); RUNTIME_ASSERT(output->HasFastObjectElements()); Handle<FixedArray> output_array(FixedArray::cast(output->elements())); RUNTIME_ASSERT(output_array->length() >= DateParser::OUTPUT_SIZE); str = String::Flatten(str); DisallowHeapAllocation no_gc; bool result; String::FlatContent str_content = str->GetFlatContent(); if (str_content.IsOneByte()) { result = DateParser::Parse(str_content.ToOneByteVector(), *output_array, isolate->unicode_cache()); } else { DCHECK(str_content.IsTwoByte()); result = DateParser::Parse(str_content.ToUC16Vector(), *output_array, isolate->unicode_cache()); } if (result) { return *output; } else { return isolate->heap()->null_value(); } } RUNTIME_FUNCTION(Runtime_DateLocalTimezone) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_DOUBLE_ARG_CHECKED(x, 0); RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs && x <= DateCache::kMaxTimeBeforeUTCInMs); const char* zone = isolate->date_cache()->LocalTimezone(static_cast<int64_t>(x)); Handle<String> result = isolate->factory()->NewStringFromUtf8(CStrVector(zone)).ToHandleChecked(); return *result; } RUNTIME_FUNCTION(Runtime_DateToUTC) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_DOUBLE_ARG_CHECKED(x, 0); RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs && x <= DateCache::kMaxTimeBeforeUTCInMs); int64_t time = isolate->date_cache()->ToUTC(static_cast<int64_t>(x)); return *isolate->factory()->NewNumber(static_cast<double>(time)); } RUNTIME_FUNCTION(Runtime_DateCacheVersion) { HandleScope hs(isolate); DCHECK(args.length() == 0); if (!isolate->eternal_handles()->Exists(EternalHandles::DATE_CACHE_VERSION)) { Handle<FixedArray> date_cache_version = isolate->factory()->NewFixedArray(1, TENURED); date_cache_version->set(0, Smi::FromInt(0)); isolate->eternal_handles()->CreateSingleton( isolate, *date_cache_version, EternalHandles::DATE_CACHE_VERSION); } Handle<FixedArray> date_cache_version = Handle<FixedArray>::cast(isolate->eternal_handles()->GetSingleton( EternalHandles::DATE_CACHE_VERSION)); // Return result as a JS array. Handle<JSObject> result = isolate->factory()->NewJSObject(isolate->array_function()); JSArray::SetContent(Handle<JSArray>::cast(result), date_cache_version); return *result; } RUNTIME_FUNCTION(Runtime_GlobalProxy) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, global, 0); if (!global->IsJSGlobalObject()) return isolate->heap()->null_value(); return JSGlobalObject::cast(global)->global_proxy(); } RUNTIME_FUNCTION(Runtime_IsAttachedGlobal) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, global, 0); if (!global->IsJSGlobalObject()) return isolate->heap()->false_value(); return isolate->heap()->ToBoolean( !JSGlobalObject::cast(global)->IsDetached()); } RUNTIME_FUNCTION(Runtime_AllocateInNewSpace) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_SMI_ARG_CHECKED(size, 0); RUNTIME_ASSERT(IsAligned(size, kPointerSize)); RUNTIME_ASSERT(size > 0); RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize); return *isolate->factory()->NewFillerObject(size, false, NEW_SPACE); } RUNTIME_FUNCTION(Runtime_AllocateInTargetSpace) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_SMI_ARG_CHECKED(size, 0); CONVERT_SMI_ARG_CHECKED(flags, 1); RUNTIME_ASSERT(IsAligned(size, kPointerSize)); RUNTIME_ASSERT(size > 0); RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize); bool double_align = AllocateDoubleAlignFlag::decode(flags); AllocationSpace space = AllocateTargetSpace::decode(flags); return *isolate->factory()->NewFillerObject(size, double_align, space); } // Push an object unto an array of objects if it is not already in the // array. Returns true if the element was pushed on the stack and // false otherwise. RUNTIME_FUNCTION(Runtime_PushIfAbsent) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, element, 1); RUNTIME_ASSERT(array->HasFastSmiOrObjectElements()); int length = Smi::cast(array->length())->value(); FixedArray* elements = FixedArray::cast(array->elements()); for (int i = 0; i < length; i++) { if (elements->get(i) == *element) return isolate->heap()->false_value(); } // Strict not needed. Used for cycle detection in Array join implementation. RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::SetFastElement(array, length, element, SLOPPY, true)); return isolate->heap()->true_value(); } /** * A simple visitor visits every element of Array's. * The backend storage can be a fixed array for fast elements case, * or a dictionary for sparse array. Since Dictionary is a subtype * of FixedArray, the class can be used by both fast and slow cases. * The second parameter of the constructor, fast_elements, specifies * whether the storage is a FixedArray or Dictionary. * * An index limit is used to deal with the situation that a result array * length overflows 32-bit non-negative integer. */ class ArrayConcatVisitor { public: ArrayConcatVisitor(Isolate* isolate, Handle<FixedArray> storage, bool fast_elements) : isolate_(isolate), storage_(Handle<FixedArray>::cast( isolate->global_handles()->Create(*storage))), index_offset_(0u), fast_elements_(fast_elements), exceeds_array_limit_(false) {} ~ArrayConcatVisitor() { clear_storage(); } void visit(uint32_t i, Handle<Object> elm) { if (i > JSObject::kMaxElementCount - index_offset_) { exceeds_array_limit_ = true; return; } uint32_t index = index_offset_ + i; if (fast_elements_) { if (index < static_cast<uint32_t>(storage_->length())) { storage_->set(index, *elm); return; } // Our initial estimate of length was foiled, possibly by // getters on the arrays increasing the length of later arrays // during iteration. // This shouldn't happen in anything but pathological cases. SetDictionaryMode(); // Fall-through to dictionary mode. } DCHECK(!fast_elements_); Handle<SeededNumberDictionary> dict( SeededNumberDictionary::cast(*storage_)); Handle<SeededNumberDictionary> result = SeededNumberDictionary::AtNumberPut(dict, index, elm); if (!result.is_identical_to(dict)) { // Dictionary needed to grow. clear_storage(); set_storage(*result); } } void increase_index_offset(uint32_t delta) { if (JSObject::kMaxElementCount - index_offset_ < delta) { index_offset_ = JSObject::kMaxElementCount; } else { index_offset_ += delta; } // If the initial length estimate was off (see special case in visit()), // but the array blowing the limit didn't contain elements beyond the // provided-for index range, go to dictionary mode now. if (fast_elements_ && index_offset_ > static_cast<uint32_t>(FixedArrayBase::cast(*storage_)->length())) { SetDictionaryMode(); } } bool exceeds_array_limit() { return exceeds_array_limit_; } Handle<JSArray> ToArray() { Handle<JSArray> array = isolate_->factory()->NewJSArray(0); Handle<Object> length = isolate_->factory()->NewNumber(static_cast<double>(index_offset_)); Handle<Map> map = JSObject::GetElementsTransitionMap( array, fast_elements_ ? FAST_HOLEY_ELEMENTS : DICTIONARY_ELEMENTS); array->set_map(*map); array->set_length(*length); array->set_elements(*storage_); return array; } private: // Convert storage to dictionary mode. void SetDictionaryMode() { DCHECK(fast_elements_); Handle<FixedArray> current_storage(*storage_); Handle<SeededNumberDictionary> slow_storage( SeededNumberDictionary::New(isolate_, current_storage->length())); uint32_t current_length = static_cast<uint32_t>(current_storage->length()); for (uint32_t i = 0; i < current_length; i++) { HandleScope loop_scope(isolate_); Handle<Object> element(current_storage->get(i), isolate_); if (!element->IsTheHole()) { Handle<SeededNumberDictionary> new_storage = SeededNumberDictionary::AtNumberPut(slow_storage, i, element); if (!new_storage.is_identical_to(slow_storage)) { slow_storage = loop_scope.CloseAndEscape(new_storage); } } } clear_storage(); set_storage(*slow_storage); fast_elements_ = false; } inline void clear_storage() { GlobalHandles::Destroy(Handle<Object>::cast(storage_).location()); } inline void set_storage(FixedArray* storage) { storage_ = Handle<FixedArray>::cast(isolate_->global_handles()->Create(storage)); } Isolate* isolate_; Handle<FixedArray> storage_; // Always a global handle. // Index after last seen index. Always less than or equal to // JSObject::kMaxElementCount. uint32_t index_offset_; bool fast_elements_ : 1; bool exceeds_array_limit_ : 1; }; static uint32_t EstimateElementCount(Handle<JSArray> array) { uint32_t length = static_cast<uint32_t>(array->length()->Number()); int element_count = 0; switch (array->GetElementsKind()) { case FAST_SMI_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_ELEMENTS: { // Fast elements can't have lengths that are not representable by // a 32-bit signed integer. DCHECK(static_cast<int32_t>(FixedArray::kMaxLength) >= 0); int fast_length = static_cast<int>(length); Handle<FixedArray> elements(FixedArray::cast(array->elements())); for (int i = 0; i < fast_length; i++) { if (!elements->get(i)->IsTheHole()) element_count++; } break; } case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: { // Fast elements can't have lengths that are not representable by // a 32-bit signed integer. DCHECK(static_cast<int32_t>(FixedDoubleArray::kMaxLength) >= 0); int fast_length = static_cast<int>(length); if (array->elements()->IsFixedArray()) { DCHECK(FixedArray::cast(array->elements())->length() == 0); break; } Handle<FixedDoubleArray> elements( FixedDoubleArray::cast(array->elements())); for (int i = 0; i < fast_length; i++) { if (!elements->is_the_hole(i)) element_count++; } break; } case DICTIONARY_ELEMENTS: { Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(array->elements())); int capacity = dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Handle<Object> key(dictionary->KeyAt(i), array->GetIsolate()); if (dictionary->IsKey(*key)) { element_count++; } } break; } case SLOPPY_ARGUMENTS_ELEMENTS: #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ELEMENTS: \ case TYPE##_ELEMENTS: TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE // External arrays are always dense. return length; } // As an estimate, we assume that the prototype doesn't contain any // inherited elements. return element_count; } template <class ExternalArrayClass, class ElementType> static void IterateExternalArrayElements(Isolate* isolate, Handle<JSObject> receiver, bool elements_are_ints, bool elements_are_guaranteed_smis, ArrayConcatVisitor* visitor) { Handle<ExternalArrayClass> array( ExternalArrayClass::cast(receiver->elements())); uint32_t len = static_cast<uint32_t>(array->length()); DCHECK(visitor != NULL); if (elements_are_ints) { if (elements_are_guaranteed_smis) { for (uint32_t j = 0; j < len; j++) { HandleScope loop_scope(isolate); Handle<Smi> e(Smi::FromInt(static_cast<int>(array->get_scalar(j))), isolate); visitor->visit(j, e); } } else { for (uint32_t j = 0; j < len; j++) { HandleScope loop_scope(isolate); int64_t val = static_cast<int64_t>(array->get_scalar(j)); if (Smi::IsValid(static_cast<intptr_t>(val))) { Handle<Smi> e(Smi::FromInt(static_cast<int>(val)), isolate); visitor->visit(j, e); } else { Handle<Object> e = isolate->factory()->NewNumber(static_cast<ElementType>(val)); visitor->visit(j, e); } } } } else { for (uint32_t j = 0; j < len; j++) { HandleScope loop_scope(isolate); Handle<Object> e = isolate->factory()->NewNumber(array->get_scalar(j)); visitor->visit(j, e); } } } // Used for sorting indices in a List<uint32_t>. static int compareUInt32(const uint32_t* ap, const uint32_t* bp) { uint32_t a = *ap; uint32_t b = *bp; return (a == b) ? 0 : (a < b) ? -1 : 1; } static void CollectElementIndices(Handle<JSObject> object, uint32_t range, List<uint32_t>* indices) { Isolate* isolate = object->GetIsolate(); ElementsKind kind = object->GetElementsKind(); switch (kind) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_ELEMENTS: { Handle<FixedArray> elements(FixedArray::cast(object->elements())); uint32_t length = static_cast<uint32_t>(elements->length()); if (range < length) length = range; for (uint32_t i = 0; i < length; i++) { if (!elements->get(i)->IsTheHole()) { indices->Add(i); } } break; } case FAST_HOLEY_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: { if (object->elements()->IsFixedArray()) { DCHECK(object->elements()->length() == 0); break; } Handle<FixedDoubleArray> elements( FixedDoubleArray::cast(object->elements())); uint32_t length = static_cast<uint32_t>(elements->length()); if (range < length) length = range; for (uint32_t i = 0; i < length; i++) { if (!elements->is_the_hole(i)) { indices->Add(i); } } break; } case DICTIONARY_ELEMENTS: { Handle<SeededNumberDictionary> dict( SeededNumberDictionary::cast(object->elements())); uint32_t capacity = dict->Capacity(); for (uint32_t j = 0; j < capacity; j++) { HandleScope loop_scope(isolate); Handle<Object> k(dict->KeyAt(j), isolate); if (dict->IsKey(*k)) { DCHECK(k->IsNumber()); uint32_t index = static_cast<uint32_t>(k->Number()); if (index < range) { indices->Add(index); } } } break; } #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: \ case EXTERNAL_##TYPE##_ELEMENTS: TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE { uint32_t length = static_cast<uint32_t>( FixedArrayBase::cast(object->elements())->length()); if (range <= length) { length = range; // We will add all indices, so we might as well clear it first // and avoid duplicates. indices->Clear(); } for (uint32_t i = 0; i < length; i++) { indices->Add(i); } if (length == range) return; // All indices accounted for already. break; } case SLOPPY_ARGUMENTS_ELEMENTS: { MaybeHandle<Object> length_obj = Object::GetProperty(object, isolate->factory()->length_string()); double length_num = length_obj.ToHandleChecked()->Number(); uint32_t length = static_cast<uint32_t>(DoubleToInt32(length_num)); ElementsAccessor* accessor = object->GetElementsAccessor(); for (uint32_t i = 0; i < length; i++) { if (accessor->HasElement(object, object, i)) { indices->Add(i); } } break; } } PrototypeIterator iter(isolate, object); if (!iter.IsAtEnd()) { // The prototype will usually have no inherited element indices, // but we have to check. CollectElementIndices( Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), range, indices); } } /** * A helper function that visits elements of a JSArray in numerical * order. * * The visitor argument called for each existing element in the array * with the element index and the element's value. * Afterwards it increments the base-index of the visitor by the array * length. * Returns false if any access threw an exception, otherwise true. */ static bool IterateElements(Isolate* isolate, Handle<JSArray> receiver, ArrayConcatVisitor* visitor) { uint32_t length = static_cast<uint32_t>(receiver->length()->Number()); switch (receiver->GetElementsKind()) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_ELEMENTS: { // Run through the elements FixedArray and use HasElement and GetElement // to check the prototype for missing elements. Handle<FixedArray> elements(FixedArray::cast(receiver->elements())); int fast_length = static_cast<int>(length); DCHECK(fast_length <= elements->length()); for (int j = 0; j < fast_length; j++) { HandleScope loop_scope(isolate); Handle<Object> element_value(elements->get(j), isolate); if (!element_value->IsTheHole()) { visitor->visit(j, element_value); } else { Maybe<bool> maybe = JSReceiver::HasElement(receiver, j); if (!maybe.has_value) return false; if (maybe.value) { // Call GetElement on receiver, not its prototype, or getters won't // have the correct receiver. ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_value, Object::GetElement(isolate, receiver, j), false); visitor->visit(j, element_value); } } } break; } case FAST_HOLEY_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: { // Empty array is FixedArray but not FixedDoubleArray. if (length == 0) break; // Run through the elements FixedArray and use HasElement and GetElement // to check the prototype for missing elements. if (receiver->elements()->IsFixedArray()) { DCHECK(receiver->elements()->length() == 0); break; } Handle<FixedDoubleArray> elements( FixedDoubleArray::cast(receiver->elements())); int fast_length = static_cast<int>(length); DCHECK(fast_length <= elements->length()); for (int j = 0; j < fast_length; j++) { HandleScope loop_scope(isolate); if (!elements->is_the_hole(j)) { double double_value = elements->get_scalar(j); Handle<Object> element_value = isolate->factory()->NewNumber(double_value); visitor->visit(j, element_value); } else { Maybe<bool> maybe = JSReceiver::HasElement(receiver, j); if (!maybe.has_value) return false; if (maybe.value) { // Call GetElement on receiver, not its prototype, or getters won't // have the correct receiver. Handle<Object> element_value; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_value, Object::GetElement(isolate, receiver, j), false); visitor->visit(j, element_value); } } } break; } case DICTIONARY_ELEMENTS: { Handle<SeededNumberDictionary> dict(receiver->element_dictionary()); List<uint32_t> indices(dict->Capacity() / 2); // Collect all indices in the object and the prototypes less // than length. This might introduce duplicates in the indices list. CollectElementIndices(receiver, length, &indices); indices.Sort(&compareUInt32); int j = 0; int n = indices.length(); while (j < n) { HandleScope loop_scope(isolate); uint32_t index = indices[j]; Handle<Object> element; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element, Object::GetElement(isolate, receiver, index), false); visitor->visit(index, element); // Skip to next different index (i.e., omit duplicates). do { j++; } while (j < n && indices[j] == index); } break; } case EXTERNAL_UINT8_CLAMPED_ELEMENTS: { Handle<ExternalUint8ClampedArray> pixels( ExternalUint8ClampedArray::cast(receiver->elements())); for (uint32_t j = 0; j < length; j++) { Handle<Smi> e(Smi::FromInt(pixels->get_scalar(j)), isolate); visitor->visit(j, e); } break; } case EXTERNAL_INT8_ELEMENTS: { IterateExternalArrayElements<ExternalInt8Array, int8_t>( isolate, receiver, true, true, visitor); break; } case EXTERNAL_UINT8_ELEMENTS: { IterateExternalArrayElements<ExternalUint8Array, uint8_t>( isolate, receiver, true, true, visitor); break; } case EXTERNAL_INT16_ELEMENTS: { IterateExternalArrayElements<ExternalInt16Array, int16_t>( isolate, receiver, true, true, visitor); break; } case EXTERNAL_UINT16_ELEMENTS: { IterateExternalArrayElements<ExternalUint16Array, uint16_t>( isolate, receiver, true, true, visitor); break; } case EXTERNAL_INT32_ELEMENTS: { IterateExternalArrayElements<ExternalInt32Array, int32_t>( isolate, receiver, true, false, visitor); break; } case EXTERNAL_UINT32_ELEMENTS: { IterateExternalArrayElements<ExternalUint32Array, uint32_t>( isolate, receiver, true, false, visitor); break; } case EXTERNAL_FLOAT32_ELEMENTS: { IterateExternalArrayElements<ExternalFloat32Array, float>( isolate, receiver, false, false, visitor); break; } case EXTERNAL_FLOAT64_ELEMENTS: { IterateExternalArrayElements<ExternalFloat64Array, double>( isolate, receiver, false, false, visitor); break; } default: UNREACHABLE(); break; } visitor->increase_index_offset(length); return true; } /** * Array::concat implementation. * See ECMAScript 262, 15.4.4.4. * TODO(581): Fix non-compliance for very large concatenations and update to * following the ECMAScript 5 specification. */ RUNTIME_FUNCTION(Runtime_ArrayConcat) { HandleScope handle_scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSArray, arguments, 0); int argument_count = static_cast<int>(arguments->length()->Number()); RUNTIME_ASSERT(arguments->HasFastObjectElements()); Handle<FixedArray> elements(FixedArray::cast(arguments->elements())); // Pass 1: estimate the length and number of elements of the result. // The actual length can be larger if any of the arguments have getters // that mutate other arguments (but will otherwise be precise). // The number of elements is precise if there are no inherited elements. ElementsKind kind = FAST_SMI_ELEMENTS; uint32_t estimate_result_length = 0; uint32_t estimate_nof_elements = 0; for (int i = 0; i < argument_count; i++) { HandleScope loop_scope(isolate); Handle<Object> obj(elements->get(i), isolate); uint32_t length_estimate; uint32_t element_estimate; if (obj->IsJSArray()) { Handle<JSArray> array(Handle<JSArray>::cast(obj)); length_estimate = static_cast<uint32_t>(array->length()->Number()); if (length_estimate != 0) { ElementsKind array_kind = GetPackedElementsKind(array->map()->elements_kind()); if (IsMoreGeneralElementsKindTransition(kind, array_kind)) { kind = array_kind; } } element_estimate = EstimateElementCount(array); } else { if (obj->IsHeapObject()) { if (obj->IsNumber()) { if (IsMoreGeneralElementsKindTransition(kind, FAST_DOUBLE_ELEMENTS)) { kind = FAST_DOUBLE_ELEMENTS; } } else if (IsMoreGeneralElementsKindTransition(kind, FAST_ELEMENTS)) { kind = FAST_ELEMENTS; } } length_estimate = 1; element_estimate = 1; } // Avoid overflows by capping at kMaxElementCount. if (JSObject::kMaxElementCount - estimate_result_length < length_estimate) { estimate_result_length = JSObject::kMaxElementCount; } else { estimate_result_length += length_estimate; } if (JSObject::kMaxElementCount - estimate_nof_elements < element_estimate) { estimate_nof_elements = JSObject::kMaxElementCount; } else { estimate_nof_elements += element_estimate; } } // If estimated number of elements is more than half of length, a // fixed array (fast case) is more time and space-efficient than a // dictionary. bool fast_case = (estimate_nof_elements * 2) >= estimate_result_length; if (fast_case && kind == FAST_DOUBLE_ELEMENTS) { Handle<FixedArrayBase> storage = isolate->factory()->NewFixedDoubleArray(estimate_result_length); int j = 0; bool failure = false; if (estimate_result_length > 0) { Handle<FixedDoubleArray> double_storage = Handle<FixedDoubleArray>::cast(storage); for (int i = 0; i < argument_count; i++) { Handle<Object> obj(elements->get(i), isolate); if (obj->IsSmi()) { double_storage->set(j, Smi::cast(*obj)->value()); j++; } else if (obj->IsNumber()) { double_storage->set(j, obj->Number()); j++; } else { JSArray* array = JSArray::cast(*obj); uint32_t length = static_cast<uint32_t>(array->length()->Number()); switch (array->map()->elements_kind()) { case FAST_HOLEY_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: { // Empty array is FixedArray but not FixedDoubleArray. if (length == 0) break; FixedDoubleArray* elements = FixedDoubleArray::cast(array->elements()); for (uint32_t i = 0; i < length; i++) { if (elements->is_the_hole(i)) { // TODO(jkummerow/verwaest): We could be a bit more clever // here: Check if there are no elements/getters on the // prototype chain, and if so, allow creation of a holey // result array. // Same thing below (holey smi case). failure = true; break; } double double_value = elements->get_scalar(i); double_storage->set(j, double_value); j++; } break; } case FAST_HOLEY_SMI_ELEMENTS: case FAST_SMI_ELEMENTS: { FixedArray* elements(FixedArray::cast(array->elements())); for (uint32_t i = 0; i < length; i++) { Object* element = elements->get(i); if (element->IsTheHole()) { failure = true; break; } int32_t int_value = Smi::cast(element)->value(); double_storage->set(j, int_value); j++; } break; } case FAST_HOLEY_ELEMENTS: case FAST_ELEMENTS: DCHECK_EQ(0, length); break; default: UNREACHABLE(); } } if (failure) break; } } if (!failure) { Handle<JSArray> array = isolate->factory()->NewJSArray(0); Smi* length = Smi::FromInt(j); Handle<Map> map; map = JSObject::GetElementsTransitionMap(array, kind); array->set_map(*map); array->set_length(length); array->set_elements(*storage); return *array; } // In case of failure, fall through. } Handle<FixedArray> storage; if (fast_case) { // The backing storage array must have non-existing elements to preserve // holes across concat operations. storage = isolate->factory()->NewFixedArrayWithHoles(estimate_result_length); } else { // TODO(126): move 25% pre-allocation logic into Dictionary::Allocate uint32_t at_least_space_for = estimate_nof_elements + (estimate_nof_elements >> 2); storage = Handle<FixedArray>::cast( SeededNumberDictionary::New(isolate, at_least_space_for)); } ArrayConcatVisitor visitor(isolate, storage, fast_case); for (int i = 0; i < argument_count; i++) { Handle<Object> obj(elements->get(i), isolate); if (obj->IsJSArray()) { Handle<JSArray> array = Handle<JSArray>::cast(obj); if (!IterateElements(isolate, array, &visitor)) { return isolate->heap()->exception(); } } else { visitor.visit(0, obj); visitor.increase_index_offset(1); } } if (visitor.exceeds_array_limit()) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewRangeError("invalid_array_length", HandleVector<Object>(NULL, 0))); } return *visitor.ToArray(); } // Moves all own elements of an object, that are below a limit, to positions // starting at zero. All undefined values are placed after non-undefined values, // and are followed by non-existing element. Does not change the length // property. // Returns the number of non-undefined elements collected. // Returns -1 if hole removal is not supported by this method. RUNTIME_FUNCTION(Runtime_RemoveArrayHoles) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]); return *JSObject::PrepareElementsForSort(object, limit); } // Move contents of argument 0 (an array) to argument 1 (an array) RUNTIME_FUNCTION(Runtime_MoveArrayContents) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, from, 0); CONVERT_ARG_HANDLE_CHECKED(JSArray, to, 1); JSObject::ValidateElements(from); JSObject::ValidateElements(to); Handle<FixedArrayBase> new_elements(from->elements()); ElementsKind from_kind = from->GetElementsKind(); Handle<Map> new_map = JSObject::GetElementsTransitionMap(to, from_kind); JSObject::SetMapAndElements(to, new_map, new_elements); to->set_length(from->length()); JSObject::ResetElements(from); from->set_length(Smi::FromInt(0)); JSObject::ValidateElements(to); return *to; } // How many elements does this object/array have? RUNTIME_FUNCTION(Runtime_EstimateNumberOfElements) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0); Handle<FixedArrayBase> elements(array->elements(), isolate); SealHandleScope shs(isolate); if (elements->IsDictionary()) { int result = Handle<SeededNumberDictionary>::cast(elements)->NumberOfElements(); return Smi::FromInt(result); } else { DCHECK(array->length()->IsSmi()); // For packed elements, we know the exact number of elements int length = elements->length(); ElementsKind kind = array->GetElementsKind(); if (IsFastPackedElementsKind(kind)) { return Smi::FromInt(length); } // For holey elements, take samples from the buffer checking for holes // to generate the estimate. const int kNumberOfHoleCheckSamples = 97; int increment = (length < kNumberOfHoleCheckSamples) ? 1 : static_cast<int>(length / kNumberOfHoleCheckSamples); ElementsAccessor* accessor = array->GetElementsAccessor(); int holes = 0; for (int i = 0; i < length; i += increment) { if (!accessor->HasElement(array, array, i, elements)) { ++holes; } } int estimate = static_cast<int>((kNumberOfHoleCheckSamples - holes) / kNumberOfHoleCheckSamples * length); return Smi::FromInt(estimate); } } // Returns an array that tells you where in the [0, length) interval an array // might have elements. Can either return an array of keys (positive integers // or undefined) or a number representing the positive length of an interval // starting at index 0. // Intervals can span over some keys that are not in the object. RUNTIME_FUNCTION(Runtime_GetArrayKeys) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0); CONVERT_NUMBER_CHECKED(uint32_t, length, Uint32, args[1]); if (array->elements()->IsDictionary()) { Handle<FixedArray> keys = isolate->factory()->empty_fixed_array(); for (PrototypeIterator iter(isolate, array, PrototypeIterator::START_AT_RECEIVER); !iter.IsAtEnd(); iter.Advance()) { if (PrototypeIterator::GetCurrent(iter)->IsJSProxy() || JSObject::cast(*PrototypeIterator::GetCurrent(iter)) ->HasIndexedInterceptor()) { // Bail out if we find a proxy or interceptor, likely not worth // collecting keys in that case. return *isolate->factory()->NewNumberFromUint(length); } Handle<JSObject> current = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); Handle<FixedArray> current_keys = isolate->factory()->NewFixedArray(current->NumberOfOwnElements(NONE)); current->GetOwnElementKeys(*current_keys, NONE); ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, keys, FixedArray::UnionOfKeys(keys, current_keys)); } // Erase any keys >= length. // TODO(adamk): Remove this step when the contract of %GetArrayKeys // is changed to let this happen on the JS side. for (int i = 0; i < keys->length(); i++) { if (NumberToUint32(keys->get(i)) >= length) keys->set_undefined(i); } return *isolate->factory()->NewJSArrayWithElements(keys); } else { RUNTIME_ASSERT(array->HasFastSmiOrObjectElements() || array->HasFastDoubleElements()); uint32_t actual_length = static_cast<uint32_t>(array->elements()->length()); return *isolate->factory()->NewNumberFromUint(Min(actual_length, length)); } } RUNTIME_FUNCTION(Runtime_LookupAccessor) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); CONVERT_SMI_ARG_CHECKED(flag, 2); AccessorComponent component = flag == 0 ? ACCESSOR_GETTER : ACCESSOR_SETTER; if (!receiver->IsJSObject()) return isolate->heap()->undefined_value(); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::GetAccessor(Handle<JSObject>::cast(receiver), name, component)); return *result; } RUNTIME_FUNCTION(Runtime_DebugBreak) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); isolate->debug()->HandleDebugBreak(); return isolate->heap()->undefined_value(); } // Helper functions for wrapping and unwrapping stack frame ids. static Smi* WrapFrameId(StackFrame::Id id) { DCHECK(IsAligned(OffsetFrom(id), static_cast<intptr_t>(4))); return Smi::FromInt(id >> 2); } static StackFrame::Id UnwrapFrameId(int wrapped) { return static_cast<StackFrame::Id>(wrapped << 2); } // Adds a JavaScript function as a debug event listener. // args[0]: debug event listener function to set or null or undefined for // clearing the event listener function // args[1]: object supplied during callback RUNTIME_FUNCTION(Runtime_SetDebugEventListener) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); RUNTIME_ASSERT(args[0]->IsJSFunction() || args[0]->IsUndefined() || args[0]->IsNull()); CONVERT_ARG_HANDLE_CHECKED(Object, callback, 0); CONVERT_ARG_HANDLE_CHECKED(Object, data, 1); isolate->debug()->SetEventListener(callback, data); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_Break) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); isolate->stack_guard()->RequestDebugBreak(); return isolate->heap()->undefined_value(); } static Handle<Object> DebugGetProperty(LookupIterator* it, bool* has_caught = NULL) { for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::ACCESS_CHECK: // Ignore access checks. break; case LookupIterator::INTERCEPTOR: case LookupIterator::JSPROXY: return it->isolate()->factory()->undefined_value(); case LookupIterator::ACCESSOR: { Handle<Object> accessors = it->GetAccessors(); if (!accessors->IsAccessorInfo()) { return it->isolate()->factory()->undefined_value(); } MaybeHandle<Object> maybe_result = JSObject::GetPropertyWithAccessor( it->GetReceiver(), it->name(), it->GetHolder<JSObject>(), accessors); Handle<Object> result; if (!maybe_result.ToHandle(&result)) { result = handle(it->isolate()->pending_exception(), it->isolate()); it->isolate()->clear_pending_exception(); if (has_caught != NULL) *has_caught = true; } return result; } case LookupIterator::DATA: return it->GetDataValue(); } } return it->isolate()->factory()->undefined_value(); } // Get debugger related details for an object property, in the following format: // 0: Property value // 1: Property details // 2: Property value is exception // 3: Getter function if defined // 4: Setter function if defined // Items 2-4 are only filled if the property has either a getter or a setter. RUNTIME_FUNCTION(Runtime_DebugGetPropertyDetails) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); // Make sure to set the current context to the context before the debugger was // entered (if the debugger is entered). The reason for switching context here // is that for some property lookups (accessors and interceptors) callbacks // into the embedding application can occour, and the embedding application // could have the assumption that its own native context is the current // context and not some internal debugger context. SaveContext save(isolate); if (isolate->debug()->in_debug_scope()) { isolate->set_context(*isolate->debug()->debugger_entry()->GetContext()); } // Check if the name is trivially convertible to an index and get the element // if so. uint32_t index; if (name->AsArrayIndex(&index)) { Handle<FixedArray> details = isolate->factory()->NewFixedArray(2); Handle<Object> element_or_char; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, element_or_char, Runtime::GetElementOrCharAt(isolate, obj, index)); details->set(0, *element_or_char); details->set(1, PropertyDetails(NONE, NORMAL, Representation::None()).AsSmi()); return *isolate->factory()->NewJSArrayWithElements(details); } LookupIterator it(obj, name, LookupIterator::HIDDEN); bool has_caught = false; Handle<Object> value = DebugGetProperty(&it, &has_caught); if (!it.IsFound()) return isolate->heap()->undefined_value(); Handle<Object> maybe_pair; if (it.state() == LookupIterator::ACCESSOR) { maybe_pair = it.GetAccessors(); } // If the callback object is a fixed array then it contains JavaScript // getter and/or setter. bool has_js_accessors = !maybe_pair.is_null() && maybe_pair->IsAccessorPair(); Handle<FixedArray> details = isolate->factory()->NewFixedArray(has_js_accessors ? 6 : 3); details->set(0, *value); // TODO(verwaest): Get rid of this random way of handling interceptors. PropertyDetails d = it.state() == LookupIterator::INTERCEPTOR ? PropertyDetails(NONE, NORMAL, 0) : it.property_details(); details->set(1, d.AsSmi()); details->set( 2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR)); if (has_js_accessors) { AccessorPair* accessors = AccessorPair::cast(*maybe_pair); details->set(3, isolate->heap()->ToBoolean(has_caught)); details->set(4, accessors->GetComponent(ACCESSOR_GETTER)); details->set(5, accessors->GetComponent(ACCESSOR_SETTER)); } return *isolate->factory()->NewJSArrayWithElements(details); } RUNTIME_FUNCTION(Runtime_DebugGetProperty) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); LookupIterator it(obj, name); return *DebugGetProperty(&it); } // Return the property type calculated from the property details. // args[0]: smi with property details. RUNTIME_FUNCTION(Runtime_DebugPropertyTypeFromDetails) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_PROPERTY_DETAILS_CHECKED(details, 0); return Smi::FromInt(static_cast<int>(details.type())); } // Return the property attribute calculated from the property details. // args[0]: smi with property details. RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_PROPERTY_DETAILS_CHECKED(details, 0); return Smi::FromInt(static_cast<int>(details.attributes())); } // Return the property insertion index calculated from the property details. // args[0]: smi with property details. RUNTIME_FUNCTION(Runtime_DebugPropertyIndexFromDetails) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_PROPERTY_DETAILS_CHECKED(details, 0); // TODO(verwaest): Depends on the type of details. return Smi::FromInt(details.dictionary_index()); } // Return property value from named interceptor. // args[0]: object // args[1]: property name RUNTIME_FUNCTION(Runtime_DebugNamedInterceptorPropertyValue) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); RUNTIME_ASSERT(obj->HasNamedInterceptor()); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::GetProperty(obj, name)); return *result; } // Return element value from indexed interceptor. // args[0]: object // args[1]: index RUNTIME_FUNCTION(Runtime_DebugIndexedInterceptorElementValue) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); RUNTIME_ASSERT(obj->HasIndexedInterceptor()); CONVERT_NUMBER_CHECKED(uint32_t, index, Uint32, args[1]); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, JSObject::GetElementWithInterceptor(obj, obj, index)); return *result; } static bool CheckExecutionState(Isolate* isolate, int break_id) { return !isolate->debug()->debug_context().is_null() && isolate->debug()->break_id() != 0 && isolate->debug()->break_id() == break_id; } RUNTIME_FUNCTION(Runtime_CheckExecutionState) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); return isolate->heap()->true_value(); } RUNTIME_FUNCTION(Runtime_GetFrameCount) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); // Count all frames which are relevant to debugging stack trace. int n = 0; StackFrame::Id id = isolate->debug()->break_frame_id(); if (id == StackFrame::NO_ID) { // If there is no JavaScript stack frame count is 0. return Smi::FromInt(0); } for (JavaScriptFrameIterator it(isolate, id); !it.done(); it.Advance()) { List<FrameSummary> frames(FLAG_max_inlining_levels + 1); it.frame()->Summarize(&frames); for (int i = frames.length() - 1; i >= 0; i--) { // Omit functions from native scripts. if (!frames[i].function()->IsFromNativeScript()) n++; } } return Smi::FromInt(n); } class FrameInspector { public: FrameInspector(JavaScriptFrame* frame, int inlined_jsframe_index, Isolate* isolate) : frame_(frame), deoptimized_frame_(NULL), isolate_(isolate) { // Calculate the deoptimized frame. if (frame->is_optimized()) { deoptimized_frame_ = Deoptimizer::DebuggerInspectableFrame( frame, inlined_jsframe_index, isolate); } has_adapted_arguments_ = frame_->has_adapted_arguments(); is_bottommost_ = inlined_jsframe_index == 0; is_optimized_ = frame_->is_optimized(); } ~FrameInspector() { // Get rid of the calculated deoptimized frame if any. if (deoptimized_frame_ != NULL) { Deoptimizer::DeleteDebuggerInspectableFrame(deoptimized_frame_, isolate_); } } int GetParametersCount() { return is_optimized_ ? deoptimized_frame_->parameters_count() : frame_->ComputeParametersCount(); } int expression_count() { return deoptimized_frame_->expression_count(); } Object* GetFunction() { return is_optimized_ ? deoptimized_frame_->GetFunction() : frame_->function(); } Object* GetParameter(int index) { return is_optimized_ ? deoptimized_frame_->GetParameter(index) : frame_->GetParameter(index); } Object* GetExpression(int index) { return is_optimized_ ? deoptimized_frame_->GetExpression(index) : frame_->GetExpression(index); } int GetSourcePosition() { return is_optimized_ ? deoptimized_frame_->GetSourcePosition() : frame_->LookupCode()->SourcePosition(frame_->pc()); } bool IsConstructor() { return is_optimized_ && !is_bottommost_ ? deoptimized_frame_->HasConstructStub() : frame_->IsConstructor(); } Object* GetContext() { return is_optimized_ ? deoptimized_frame_->GetContext() : frame_->context(); } // To inspect all the provided arguments the frame might need to be // replaced with the arguments frame. void SetArgumentsFrame(JavaScriptFrame* frame) { DCHECK(has_adapted_arguments_); frame_ = frame; is_optimized_ = frame_->is_optimized(); DCHECK(!is_optimized_); } private: JavaScriptFrame* frame_; DeoptimizedFrameInfo* deoptimized_frame_; Isolate* isolate_; bool is_optimized_; bool is_bottommost_; bool has_adapted_arguments_; DISALLOW_COPY_AND_ASSIGN(FrameInspector); }; static const int kFrameDetailsFrameIdIndex = 0; static const int kFrameDetailsReceiverIndex = 1; static const int kFrameDetailsFunctionIndex = 2; static const int kFrameDetailsArgumentCountIndex = 3; static const int kFrameDetailsLocalCountIndex = 4; static const int kFrameDetailsSourcePositionIndex = 5; static const int kFrameDetailsConstructCallIndex = 6; static const int kFrameDetailsAtReturnIndex = 7; static const int kFrameDetailsFlagsIndex = 8; static const int kFrameDetailsFirstDynamicIndex = 9; static SaveContext* FindSavedContextForFrame(Isolate* isolate, JavaScriptFrame* frame) { SaveContext* save = isolate->save_context(); while (save != NULL && !save->IsBelowFrame(frame)) { save = save->prev(); } DCHECK(save != NULL); return save; } // Advances the iterator to the frame that matches the index and returns the // inlined frame index, or -1 if not found. Skips native JS functions. static int FindIndexedNonNativeFrame(JavaScriptFrameIterator* it, int index) { int count = -1; for (; !it->done(); it->Advance()) { List<FrameSummary> frames(FLAG_max_inlining_levels + 1); it->frame()->Summarize(&frames); for (int i = frames.length() - 1; i >= 0; i--) { // Omit functions from native scripts. if (frames[i].function()->IsFromNativeScript()) continue; if (++count == index) return i; } } return -1; } // Return an array with frame details // args[0]: number: break id // args[1]: number: frame index // // The array returned contains the following information: // 0: Frame id // 1: Receiver // 2: Function // 3: Argument count // 4: Local count // 5: Source position // 6: Constructor call // 7: Is at return // 8: Flags // Arguments name, value // Locals name, value // Return value if any RUNTIME_FUNCTION(Runtime_GetFrameDetails) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]); Heap* heap = isolate->heap(); // Find the relevant frame with the requested index. StackFrame::Id id = isolate->debug()->break_frame_id(); if (id == StackFrame::NO_ID) { // If there are no JavaScript stack frames return undefined. return heap->undefined_value(); } JavaScriptFrameIterator it(isolate, id); // Inlined frame index in optimized frame, starting from outer function. int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index); if (inlined_jsframe_index == -1) return heap->undefined_value(); FrameInspector frame_inspector(it.frame(), inlined_jsframe_index, isolate); bool is_optimized = it.frame()->is_optimized(); // Traverse the saved contexts chain to find the active context for the // selected frame. SaveContext* save = FindSavedContextForFrame(isolate, it.frame()); // Get the frame id. Handle<Object> frame_id(WrapFrameId(it.frame()->id()), isolate); // Find source position in unoptimized code. int position = frame_inspector.GetSourcePosition(); // Check for constructor frame. bool constructor = frame_inspector.IsConstructor(); // Get scope info and read from it for local variable information. Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction())); Handle<SharedFunctionInfo> shared(function->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); DCHECK(*scope_info != ScopeInfo::Empty(isolate)); // Get the locals names and values into a temporary array. int local_count = scope_info->LocalCount(); for (int slot = 0; slot < scope_info->LocalCount(); ++slot) { // Hide compiler-introduced temporary variables, whether on the stack or on // the context. if (scope_info->LocalIsSynthetic(slot)) local_count--; } Handle<FixedArray> locals = isolate->factory()->NewFixedArray(local_count * 2); // Fill in the values of the locals. int local = 0; int i = 0; for (; i < scope_info->StackLocalCount(); ++i) { // Use the value from the stack. if (scope_info->LocalIsSynthetic(i)) continue; locals->set(local * 2, scope_info->LocalName(i)); locals->set(local * 2 + 1, frame_inspector.GetExpression(i)); local++; } if (local < local_count) { // Get the context containing declarations. Handle<Context> context( Context::cast(frame_inspector.GetContext())->declaration_context()); for (; i < scope_info->LocalCount(); ++i) { if (scope_info->LocalIsSynthetic(i)) continue; Handle<String> name(scope_info->LocalName(i)); VariableMode mode; InitializationFlag init_flag; MaybeAssignedFlag maybe_assigned_flag; locals->set(local * 2, *name); int context_slot_index = ScopeInfo::ContextSlotIndex( scope_info, name, &mode, &init_flag, &maybe_assigned_flag); Object* value = context->get(context_slot_index); locals->set(local * 2 + 1, value); local++; } } // Check whether this frame is positioned at return. If not top // frame or if the frame is optimized it cannot be at a return. bool at_return = false; if (!is_optimized && index == 0) { at_return = isolate->debug()->IsBreakAtReturn(it.frame()); } // If positioned just before return find the value to be returned and add it // to the frame information. Handle<Object> return_value = isolate->factory()->undefined_value(); if (at_return) { StackFrameIterator it2(isolate); Address internal_frame_sp = NULL; while (!it2.done()) { if (it2.frame()->is_internal()) { internal_frame_sp = it2.frame()->sp(); } else { if (it2.frame()->is_java_script()) { if (it2.frame()->id() == it.frame()->id()) { // The internal frame just before the JavaScript frame contains the // value to return on top. A debug break at return will create an // internal frame to store the return value (eax/rax/r0) before // entering the debug break exit frame. if (internal_frame_sp != NULL) { return_value = Handle<Object>(Memory::Object_at(internal_frame_sp), isolate); break; } } } // Indicate that the previous frame was not an internal frame. internal_frame_sp = NULL; } it2.Advance(); } } // Now advance to the arguments adapter frame (if any). It contains all // the provided parameters whereas the function frame always have the number // of arguments matching the functions parameters. The rest of the // information (except for what is collected above) is the same. if ((inlined_jsframe_index == 0) && it.frame()->has_adapted_arguments()) { it.AdvanceToArgumentsFrame(); frame_inspector.SetArgumentsFrame(it.frame()); } // Find the number of arguments to fill. At least fill the number of // parameters for the function and fill more if more parameters are provided. int argument_count = scope_info->ParameterCount(); if (argument_count < frame_inspector.GetParametersCount()) { argument_count = frame_inspector.GetParametersCount(); } // Calculate the size of the result. int details_size = kFrameDetailsFirstDynamicIndex + 2 * (argument_count + local_count) + (at_return ? 1 : 0); Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size); // Add the frame id. details->set(kFrameDetailsFrameIdIndex, *frame_id); // Add the function (same as in function frame). details->set(kFrameDetailsFunctionIndex, frame_inspector.GetFunction()); // Add the arguments count. details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count)); // Add the locals count details->set(kFrameDetailsLocalCountIndex, Smi::FromInt(local_count)); // Add the source position. if (position != RelocInfo::kNoPosition) { details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position)); } else { details->set(kFrameDetailsSourcePositionIndex, heap->undefined_value()); } // Add the constructor information. details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(constructor)); // Add the at return information. details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(at_return)); // Add flags to indicate information on whether this frame is // bit 0: invoked in the debugger context. // bit 1: optimized frame. // bit 2: inlined in optimized frame int flags = 0; if (*save->context() == *isolate->debug()->debug_context()) { flags |= 1 << 0; } if (is_optimized) { flags |= 1 << 1; flags |= inlined_jsframe_index << 2; } details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags)); // Fill the dynamic part. int details_index = kFrameDetailsFirstDynamicIndex; // Add arguments name and value. for (int i = 0; i < argument_count; i++) { // Name of the argument. if (i < scope_info->ParameterCount()) { details->set(details_index++, scope_info->ParameterName(i)); } else { details->set(details_index++, heap->undefined_value()); } // Parameter value. if (i < frame_inspector.GetParametersCount()) { // Get the value from the stack. details->set(details_index++, frame_inspector.GetParameter(i)); } else { details->set(details_index++, heap->undefined_value()); } } // Add locals name and value from the temporary copy from the function frame. for (int i = 0; i < local_count * 2; i++) { details->set(details_index++, locals->get(i)); } // Add the value being returned. if (at_return) { details->set(details_index++, *return_value); } // Add the receiver (same as in function frame). // THIS MUST BE DONE LAST SINCE WE MIGHT ADVANCE // THE FRAME ITERATOR TO WRAP THE RECEIVER. Handle<Object> receiver(it.frame()->receiver(), isolate); if (!receiver->IsJSObject() && shared->strict_mode() == SLOPPY && !function->IsBuiltin()) { // If the receiver is not a JSObject and the function is not a // builtin or strict-mode we have hit an optimization where a // value object is not converted into a wrapped JS objects. To // hide this optimization from the debugger, we wrap the receiver // by creating correct wrapper object based on the calling frame's // native context. it.Advance(); if (receiver->IsUndefined()) { receiver = handle(function->global_proxy()); } else { Context* context = Context::cast(it.frame()->context()); Handle<Context> native_context(Context::cast(context->native_context())); if (!Object::ToObject(isolate, receiver, native_context) .ToHandle(&receiver)) { // This only happens if the receiver is forcibly set in %_CallFunction. return heap->undefined_value(); } } } details->set(kFrameDetailsReceiverIndex, *receiver); DCHECK_EQ(details_size, details_index); return *isolate->factory()->NewJSArrayWithElements(details); } static bool ParameterIsShadowedByContextLocal(Handle<ScopeInfo> info, Handle<String> parameter_name) { VariableMode mode; InitializationFlag init_flag; MaybeAssignedFlag maybe_assigned_flag; return ScopeInfo::ContextSlotIndex(info, parameter_name, &mode, &init_flag, &maybe_assigned_flag) != -1; } // Create a plain JSObject which materializes the local scope for the specified // frame. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeStackLocalsWithFrameInspector( Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function, FrameInspector* frame_inspector) { Handle<SharedFunctionInfo> shared(function->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); // First fill all parameters. for (int i = 0; i < scope_info->ParameterCount(); ++i) { // Do not materialize the parameter if it is shadowed by a context local. Handle<String> name(scope_info->ParameterName(i)); if (ParameterIsShadowedByContextLocal(scope_info, name)) continue; HandleScope scope(isolate); Handle<Object> value(i < frame_inspector->GetParametersCount() ? frame_inspector->GetParameter(i) : isolate->heap()->undefined_value(), isolate); DCHECK(!value->IsTheHole()); RETURN_ON_EXCEPTION(isolate, Runtime::SetObjectProperty( isolate, target, name, value, SLOPPY), JSObject); } // Second fill all stack locals. for (int i = 0; i < scope_info->StackLocalCount(); ++i) { if (scope_info->LocalIsSynthetic(i)) continue; Handle<String> name(scope_info->StackLocalName(i)); Handle<Object> value(frame_inspector->GetExpression(i), isolate); if (value->IsTheHole()) continue; RETURN_ON_EXCEPTION(isolate, Runtime::SetObjectProperty( isolate, target, name, value, SLOPPY), JSObject); } return target; } static void UpdateStackLocalsFromMaterializedObject(Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function, JavaScriptFrame* frame, int inlined_jsframe_index) { if (inlined_jsframe_index != 0 || frame->is_optimized()) { // Optimized frames are not supported. // TODO(yangguo): make sure all code deoptimized when debugger is active // and assert that this cannot happen. return; } Handle<SharedFunctionInfo> shared(function->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); // Parameters. for (int i = 0; i < scope_info->ParameterCount(); ++i) { // Shadowed parameters were not materialized. Handle<String> name(scope_info->ParameterName(i)); if (ParameterIsShadowedByContextLocal(scope_info, name)) continue; DCHECK(!frame->GetParameter(i)->IsTheHole()); HandleScope scope(isolate); Handle<Object> value = Object::GetPropertyOrElement(target, name).ToHandleChecked(); frame->SetParameterValue(i, *value); } // Stack locals. for (int i = 0; i < scope_info->StackLocalCount(); ++i) { if (scope_info->LocalIsSynthetic(i)) continue; if (frame->GetExpression(i)->IsTheHole()) continue; HandleScope scope(isolate); Handle<Object> value = Object::GetPropertyOrElement( target, handle(scope_info->StackLocalName(i), isolate)).ToHandleChecked(); frame->SetExpression(i, *value); } } MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalContext( Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function, JavaScriptFrame* frame) { HandleScope scope(isolate); Handle<SharedFunctionInfo> shared(function->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); if (!scope_info->HasContext()) return target; // Third fill all context locals. Handle<Context> frame_context(Context::cast(frame->context())); Handle<Context> function_context(frame_context->declaration_context()); if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, function_context, target)) { return MaybeHandle<JSObject>(); } // Finally copy any properties from the function context extension. // These will be variables introduced by eval. if (function_context->closure() == *function) { if (function_context->has_extension() && !function_context->IsNativeContext()) { Handle<JSObject> ext(JSObject::cast(function_context->extension())); Handle<FixedArray> keys; ASSIGN_RETURN_ON_EXCEPTION( isolate, keys, JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS), JSObject); for (int i = 0; i < keys->length(); i++) { // Names of variables introduced by eval are strings. DCHECK(keys->get(i)->IsString()); Handle<String> key(String::cast(keys->get(i))); Handle<Object> value; ASSIGN_RETURN_ON_EXCEPTION( isolate, value, Object::GetPropertyOrElement(ext, key), JSObject); RETURN_ON_EXCEPTION(isolate, Runtime::SetObjectProperty( isolate, target, key, value, SLOPPY), JSObject); } } } return target; } MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalScope( Isolate* isolate, JavaScriptFrame* frame, int inlined_jsframe_index) { FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate); Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction())); Handle<JSObject> local_scope = isolate->factory()->NewJSObject(isolate->object_function()); ASSIGN_RETURN_ON_EXCEPTION( isolate, local_scope, MaterializeStackLocalsWithFrameInspector(isolate, local_scope, function, &frame_inspector), JSObject); return MaterializeLocalContext(isolate, local_scope, function, frame); } // Set the context local variable value. static bool SetContextLocalValue(Isolate* isolate, Handle<ScopeInfo> scope_info, Handle<Context> context, Handle<String> variable_name, Handle<Object> new_value) { for (int i = 0; i < scope_info->ContextLocalCount(); i++) { Handle<String> next_name(scope_info->ContextLocalName(i)); if (String::Equals(variable_name, next_name)) { VariableMode mode; InitializationFlag init_flag; MaybeAssignedFlag maybe_assigned_flag; int context_index = ScopeInfo::ContextSlotIndex( scope_info, next_name, &mode, &init_flag, &maybe_assigned_flag); context->set(context_index, *new_value); return true; } } return false; } static bool SetLocalVariableValue(Isolate* isolate, JavaScriptFrame* frame, int inlined_jsframe_index, Handle<String> variable_name, Handle<Object> new_value) { if (inlined_jsframe_index != 0 || frame->is_optimized()) { // Optimized frames are not supported. return false; } Handle<JSFunction> function(frame->function()); Handle<SharedFunctionInfo> shared(function->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); bool default_result = false; // Parameters. for (int i = 0; i < scope_info->ParameterCount(); ++i) { HandleScope scope(isolate); if (String::Equals(handle(scope_info->ParameterName(i)), variable_name)) { frame->SetParameterValue(i, *new_value); // Argument might be shadowed in heap context, don't stop here. default_result = true; } } // Stack locals. for (int i = 0; i < scope_info->StackLocalCount(); ++i) { HandleScope scope(isolate); if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) { frame->SetExpression(i, *new_value); return true; } } if (scope_info->HasContext()) { // Context locals. Handle<Context> frame_context(Context::cast(frame->context())); Handle<Context> function_context(frame_context->declaration_context()); if (SetContextLocalValue(isolate, scope_info, function_context, variable_name, new_value)) { return true; } // Function context extension. These are variables introduced by eval. if (function_context->closure() == *function) { if (function_context->has_extension() && !function_context->IsNativeContext()) { Handle<JSObject> ext(JSObject::cast(function_context->extension())); Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name); DCHECK(maybe.has_value); if (maybe.value) { // We don't expect this to do anything except replacing // property value. Runtime::SetObjectProperty(isolate, ext, variable_name, new_value, SLOPPY).Assert(); return true; } } } } return default_result; } // Create a plain JSObject which materializes the closure content for the // context. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeClosure( Isolate* isolate, Handle<Context> context) { DCHECK(context->IsFunctionContext()); Handle<SharedFunctionInfo> shared(context->closure()->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); // Allocate and initialize a JSObject with all the content of this function // closure. Handle<JSObject> closure_scope = isolate->factory()->NewJSObject(isolate->object_function()); // Fill all context locals to the context extension. if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context, closure_scope)) { return MaybeHandle<JSObject>(); } // Finally copy any properties from the function context extension. This will // be variables introduced by eval. if (context->has_extension()) { Handle<JSObject> ext(JSObject::cast(context->extension())); Handle<FixedArray> keys; ASSIGN_RETURN_ON_EXCEPTION( isolate, keys, JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS), JSObject); for (int i = 0; i < keys->length(); i++) { HandleScope scope(isolate); // Names of variables introduced by eval are strings. DCHECK(keys->get(i)->IsString()); Handle<String> key(String::cast(keys->get(i))); Handle<Object> value; ASSIGN_RETURN_ON_EXCEPTION( isolate, value, Object::GetPropertyOrElement(ext, key), JSObject); RETURN_ON_EXCEPTION(isolate, Runtime::DefineObjectProperty( closure_scope, key, value, NONE), JSObject); } } return closure_scope; } // This method copies structure of MaterializeClosure method above. static bool SetClosureVariableValue(Isolate* isolate, Handle<Context> context, Handle<String> variable_name, Handle<Object> new_value) { DCHECK(context->IsFunctionContext()); Handle<SharedFunctionInfo> shared(context->closure()->shared()); Handle<ScopeInfo> scope_info(shared->scope_info()); // Context locals to the context extension. if (SetContextLocalValue(isolate, scope_info, context, variable_name, new_value)) { return true; } // Properties from the function context extension. This will // be variables introduced by eval. if (context->has_extension()) { Handle<JSObject> ext(JSObject::cast(context->extension())); Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name); DCHECK(maybe.has_value); if (maybe.value) { // We don't expect this to do anything except replacing property value. Runtime::DefineObjectProperty(ext, variable_name, new_value, NONE) .Assert(); return true; } } return false; } // Create a plain JSObject which materializes the scope for the specified // catch context. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeCatchScope( Isolate* isolate, Handle<Context> context) { DCHECK(context->IsCatchContext()); Handle<String> name(String::cast(context->extension())); Handle<Object> thrown_object(context->get(Context::THROWN_OBJECT_INDEX), isolate); Handle<JSObject> catch_scope = isolate->factory()->NewJSObject(isolate->object_function()); RETURN_ON_EXCEPTION(isolate, Runtime::DefineObjectProperty( catch_scope, name, thrown_object, NONE), JSObject); return catch_scope; } static bool SetCatchVariableValue(Isolate* isolate, Handle<Context> context, Handle<String> variable_name, Handle<Object> new_value) { DCHECK(context->IsCatchContext()); Handle<String> name(String::cast(context->extension())); if (!String::Equals(name, variable_name)) { return false; } context->set(Context::THROWN_OBJECT_INDEX, *new_value); return true; } // Create a plain JSObject which materializes the block scope for the specified // block context. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeBlockScope( Isolate* isolate, Handle<Context> context) { DCHECK(context->IsBlockContext()); Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension())); // Allocate and initialize a JSObject with all the arguments, stack locals // heap locals and extension properties of the debugged function. Handle<JSObject> block_scope = isolate->factory()->NewJSObject(isolate->object_function()); // Fill all context locals. if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context, block_scope)) { return MaybeHandle<JSObject>(); } return block_scope; } // Create a plain JSObject which materializes the module scope for the specified // module context. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeModuleScope( Isolate* isolate, Handle<Context> context) { DCHECK(context->IsModuleContext()); Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension())); // Allocate and initialize a JSObject with all the members of the debugged // module. Handle<JSObject> module_scope = isolate->factory()->NewJSObject(isolate->object_function()); // Fill all context locals. if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context, module_scope)) { return MaybeHandle<JSObject>(); } return module_scope; } // Iterate over the actual scopes visible from a stack frame or from a closure. // The iteration proceeds from the innermost visible nested scope outwards. // All scopes are backed by an actual context except the local scope, // which is inserted "artificially" in the context chain. class ScopeIterator { public: enum ScopeType { ScopeTypeGlobal = 0, ScopeTypeLocal, ScopeTypeWith, ScopeTypeClosure, ScopeTypeCatch, ScopeTypeBlock, ScopeTypeModule }; ScopeIterator(Isolate* isolate, JavaScriptFrame* frame, int inlined_jsframe_index, bool ignore_nested_scopes = false) : isolate_(isolate), frame_(frame), inlined_jsframe_index_(inlined_jsframe_index), function_(frame->function()), context_(Context::cast(frame->context())), nested_scope_chain_(4), failed_(false) { // Catch the case when the debugger stops in an internal function. Handle<SharedFunctionInfo> shared_info(function_->shared()); Handle<ScopeInfo> scope_info(shared_info->scope_info()); if (shared_info->script() == isolate->heap()->undefined_value()) { while (context_->closure() == *function_) { context_ = Handle<Context>(context_->previous(), isolate_); } return; } // Get the debug info (create it if it does not exist). if (!isolate->debug()->EnsureDebugInfo(shared_info, function_)) { // Return if ensuring debug info failed. return; } // Currently it takes too much time to find nested scopes due to script // parsing. Sometimes we want to run the ScopeIterator as fast as possible // (for example, while collecting async call stacks on every // addEventListener call), even if we drop some nested scopes. // Later we may optimize getting the nested scopes (cache the result?) // and include nested scopes into the "fast" iteration case as well. if (!ignore_nested_scopes) { Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared_info); // Find the break point where execution has stopped. BreakLocationIterator break_location_iterator(debug_info, ALL_BREAK_LOCATIONS); // pc points to the instruction after the current one, possibly a break // location as well. So the "- 1" to exclude it from the search. break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1); // Within the return sequence at the moment it is not possible to // get a source position which is consistent with the current scope chain. // Thus all nested with, catch and block contexts are skipped and we only // provide the function scope. ignore_nested_scopes = break_location_iterator.IsExit(); } if (ignore_nested_scopes) { if (scope_info->HasContext()) { context_ = Handle<Context>(context_->declaration_context(), isolate_); } else { while (context_->closure() == *function_) { context_ = Handle<Context>(context_->previous(), isolate_); } } if (scope_info->scope_type() == FUNCTION_SCOPE) { nested_scope_chain_.Add(scope_info); } } else { // Reparse the code and analyze the scopes. Handle<Script> script(Script::cast(shared_info->script())); Scope* scope = NULL; // Check whether we are in global, eval or function code. Handle<ScopeInfo> scope_info(shared_info->scope_info()); if (scope_info->scope_type() != FUNCTION_SCOPE) { // Global or eval code. CompilationInfoWithZone info(script); if (scope_info->scope_type() == GLOBAL_SCOPE) { info.MarkAsGlobal(); } else { DCHECK(scope_info->scope_type() == EVAL_SCOPE); info.MarkAsEval(); info.SetContext(Handle<Context>(function_->context())); } if (Parser::Parse(&info) && Scope::Analyze(&info)) { scope = info.function()->scope(); } RetrieveScopeChain(scope, shared_info); } else { // Function code CompilationInfoWithZone info(shared_info); if (Parser::Parse(&info) && Scope::Analyze(&info)) { scope = info.function()->scope(); } RetrieveScopeChain(scope, shared_info); } } } ScopeIterator(Isolate* isolate, Handle<JSFunction> function) : isolate_(isolate), frame_(NULL), inlined_jsframe_index_(0), function_(function), context_(function->context()), failed_(false) { if (function->IsBuiltin()) { context_ = Handle<Context>(); } } // More scopes? bool Done() { DCHECK(!failed_); return context_.is_null(); } bool Failed() { return failed_; } // Move to the next scope. void Next() { DCHECK(!failed_); ScopeType scope_type = Type(); if (scope_type == ScopeTypeGlobal) { // The global scope is always the last in the chain. DCHECK(context_->IsNativeContext()); context_ = Handle<Context>(); return; } if (nested_scope_chain_.is_empty()) { context_ = Handle<Context>(context_->previous(), isolate_); } else { if (nested_scope_chain_.last()->HasContext()) { DCHECK(context_->previous() != NULL); context_ = Handle<Context>(context_->previous(), isolate_); } nested_scope_chain_.RemoveLast(); } } // Return the type of the current scope. ScopeType Type() { DCHECK(!failed_); if (!nested_scope_chain_.is_empty()) { Handle<ScopeInfo> scope_info = nested_scope_chain_.last(); switch (scope_info->scope_type()) { case FUNCTION_SCOPE: DCHECK(context_->IsFunctionContext() || !scope_info->HasContext()); return ScopeTypeLocal; case MODULE_SCOPE: DCHECK(context_->IsModuleContext()); return ScopeTypeModule; case GLOBAL_SCOPE: DCHECK(context_->IsNativeContext()); return ScopeTypeGlobal; case WITH_SCOPE: DCHECK(context_->IsWithContext()); return ScopeTypeWith; case CATCH_SCOPE: DCHECK(context_->IsCatchContext()); return ScopeTypeCatch; case BLOCK_SCOPE: DCHECK(!scope_info->HasContext() || context_->IsBlockContext()); return ScopeTypeBlock; case EVAL_SCOPE: UNREACHABLE(); } } if (context_->IsNativeContext()) { DCHECK(context_->global_object()->IsGlobalObject()); return ScopeTypeGlobal; } if (context_->IsFunctionContext()) { return ScopeTypeClosure; } if (context_->IsCatchContext()) { return ScopeTypeCatch; } if (context_->IsBlockContext()) { return ScopeTypeBlock; } if (context_->IsModuleContext()) { return ScopeTypeModule; } DCHECK(context_->IsWithContext()); return ScopeTypeWith; } // Return the JavaScript object with the content of the current scope. MaybeHandle<JSObject> ScopeObject() { DCHECK(!failed_); switch (Type()) { case ScopeIterator::ScopeTypeGlobal: return Handle<JSObject>(CurrentContext()->global_object()); case ScopeIterator::ScopeTypeLocal: // Materialize the content of the local scope into a JSObject. DCHECK(nested_scope_chain_.length() == 1); return MaterializeLocalScope(isolate_, frame_, inlined_jsframe_index_); case ScopeIterator::ScopeTypeWith: // Return the with object. return Handle<JSObject>(JSObject::cast(CurrentContext()->extension())); case ScopeIterator::ScopeTypeCatch: return MaterializeCatchScope(isolate_, CurrentContext()); case ScopeIterator::ScopeTypeClosure: // Materialize the content of the closure scope into a JSObject. return MaterializeClosure(isolate_, CurrentContext()); case ScopeIterator::ScopeTypeBlock: return MaterializeBlockScope(isolate_, CurrentContext()); case ScopeIterator::ScopeTypeModule: return MaterializeModuleScope(isolate_, CurrentContext()); } UNREACHABLE(); return Handle<JSObject>(); } bool SetVariableValue(Handle<String> variable_name, Handle<Object> new_value) { DCHECK(!failed_); switch (Type()) { case ScopeIterator::ScopeTypeGlobal: break; case ScopeIterator::ScopeTypeLocal: return SetLocalVariableValue(isolate_, frame_, inlined_jsframe_index_, variable_name, new_value); case ScopeIterator::ScopeTypeWith: break; case ScopeIterator::ScopeTypeCatch: return SetCatchVariableValue(isolate_, CurrentContext(), variable_name, new_value); case ScopeIterator::ScopeTypeClosure: return SetClosureVariableValue(isolate_, CurrentContext(), variable_name, new_value); case ScopeIterator::ScopeTypeBlock: // TODO(2399): should we implement it? break; case ScopeIterator::ScopeTypeModule: // TODO(2399): should we implement it? break; } return false; } Handle<ScopeInfo> CurrentScopeInfo() { DCHECK(!failed_); if (!nested_scope_chain_.is_empty()) { return nested_scope_chain_.last(); } else if (context_->IsBlockContext()) { return Handle<ScopeInfo>(ScopeInfo::cast(context_->extension())); } else if (context_->IsFunctionContext()) { return Handle<ScopeInfo>(context_->closure()->shared()->scope_info()); } return Handle<ScopeInfo>::null(); } // Return the context for this scope. For the local context there might not // be an actual context. Handle<Context> CurrentContext() { DCHECK(!failed_); if (Type() == ScopeTypeGlobal || nested_scope_chain_.is_empty()) { return context_; } else if (nested_scope_chain_.last()->HasContext()) { return context_; } else { return Handle<Context>(); } } #ifdef DEBUG // Debug print of the content of the current scope. void DebugPrint() { OFStream os(stdout); DCHECK(!failed_); switch (Type()) { case ScopeIterator::ScopeTypeGlobal: os << "Global:\n"; CurrentContext()->Print(os); break; case ScopeIterator::ScopeTypeLocal: { os << "Local:\n"; function_->shared()->scope_info()->Print(); if (!CurrentContext().is_null()) { CurrentContext()->Print(os); if (CurrentContext()->has_extension()) { Handle<Object> extension(CurrentContext()->extension(), isolate_); if (extension->IsJSContextExtensionObject()) { extension->Print(os); } } } break; } case ScopeIterator::ScopeTypeWith: os << "With:\n"; CurrentContext()->extension()->Print(os); break; case ScopeIterator::ScopeTypeCatch: os << "Catch:\n"; CurrentContext()->extension()->Print(os); CurrentContext()->get(Context::THROWN_OBJECT_INDEX)->Print(os); break; case ScopeIterator::ScopeTypeClosure: os << "Closure:\n"; CurrentContext()->Print(os); if (CurrentContext()->has_extension()) { Handle<Object> extension(CurrentContext()->extension(), isolate_); if (extension->IsJSContextExtensionObject()) { extension->Print(os); } } break; default: UNREACHABLE(); } PrintF("\n"); } #endif private: Isolate* isolate_; JavaScriptFrame* frame_; int inlined_jsframe_index_; Handle<JSFunction> function_; Handle<Context> context_; List<Handle<ScopeInfo> > nested_scope_chain_; bool failed_; void RetrieveScopeChain(Scope* scope, Handle<SharedFunctionInfo> shared_info) { if (scope != NULL) { int source_position = shared_info->code()->SourcePosition(frame_->pc()); scope->GetNestedScopeChain(&nested_scope_chain_, source_position); } else { // A failed reparse indicates that the preparser has diverged from the // parser or that the preparse data given to the initial parse has been // faulty. We fail in debug mode but in release mode we only provide the // information we get from the context chain but nothing about // completely stack allocated scopes or stack allocated locals. // Or it could be due to stack overflow. DCHECK(isolate_->has_pending_exception()); failed_ = true; } } DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator); }; RUNTIME_FUNCTION(Runtime_GetScopeCount) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator it(isolate, id); JavaScriptFrame* frame = it.frame(); // Count the visible scopes. int n = 0; for (ScopeIterator it(isolate, frame, 0); !it.Done(); it.Next()) { n++; } return Smi::FromInt(n); } // Returns the list of step-in positions (text offset) in a function of the // stack frame in a range from the current debug break position to the end // of the corresponding statement. RUNTIME_FUNCTION(Runtime_GetStepInPositions) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator frame_it(isolate, id); RUNTIME_ASSERT(!frame_it.done()); JavaScriptFrame* frame = frame_it.frame(); Handle<JSFunction> fun = Handle<JSFunction>(frame->function()); Handle<SharedFunctionInfo> shared = Handle<SharedFunctionInfo>(fun->shared()); if (!isolate->debug()->EnsureDebugInfo(shared, fun)) { return isolate->heap()->undefined_value(); } Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared); int len = 0; Handle<JSArray> array(isolate->factory()->NewJSArray(10)); // Find the break point where execution has stopped. BreakLocationIterator break_location_iterator(debug_info, ALL_BREAK_LOCATIONS); break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1); int current_statement_pos = break_location_iterator.statement_position(); while (!break_location_iterator.Done()) { bool accept; if (break_location_iterator.pc() > frame->pc()) { accept = true; } else { StackFrame::Id break_frame_id = isolate->debug()->break_frame_id(); // The break point is near our pc. Could be a step-in possibility, // that is currently taken by active debugger call. if (break_frame_id == StackFrame::NO_ID) { // We are not stepping. accept = false; } else { JavaScriptFrameIterator additional_frame_it(isolate, break_frame_id); // If our frame is a top frame and we are stepping, we can do step-in // at this place. accept = additional_frame_it.frame()->id() == id; } } if (accept) { if (break_location_iterator.IsStepInLocation(isolate)) { Smi* position_value = Smi::FromInt(break_location_iterator.position()); RETURN_FAILURE_ON_EXCEPTION( isolate, JSObject::SetElement( array, len, Handle<Object>(position_value, isolate), NONE, SLOPPY)); len++; } } // Advance iterator. break_location_iterator.Next(); if (current_statement_pos != break_location_iterator.statement_position()) { break; } } return *array; } static const int kScopeDetailsTypeIndex = 0; static const int kScopeDetailsObjectIndex = 1; static const int kScopeDetailsSize = 2; MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeScopeDetails( Isolate* isolate, ScopeIterator* it) { // Calculate the size of the result. int details_size = kScopeDetailsSize; Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size); // Fill in scope details. details->set(kScopeDetailsTypeIndex, Smi::FromInt(it->Type())); Handle<JSObject> scope_object; ASSIGN_RETURN_ON_EXCEPTION(isolate, scope_object, it->ScopeObject(), JSObject); details->set(kScopeDetailsObjectIndex, *scope_object); return isolate->factory()->NewJSArrayWithElements(details); } // Return an array with scope details // args[0]: number: break id // args[1]: number: frame index // args[2]: number: inlined frame index // args[3]: number: scope index // // The array returned contains the following information: // 0: Scope type // 1: Scope object RUNTIME_FUNCTION(Runtime_GetScopeDetails) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]); CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]); // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator frame_it(isolate, id); JavaScriptFrame* frame = frame_it.frame(); // Find the requested scope. int n = 0; ScopeIterator it(isolate, frame, inlined_jsframe_index); for (; !it.Done() && n < index; it.Next()) { n++; } if (it.Done()) { return isolate->heap()->undefined_value(); } Handle<JSObject> details; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details, MaterializeScopeDetails(isolate, &it)); return *details; } // Return an array of scope details // args[0]: number: break id // args[1]: number: frame index // args[2]: number: inlined frame index // args[3]: boolean: ignore nested scopes // // The array returned contains arrays with the following information: // 0: Scope type // 1: Scope object RUNTIME_FUNCTION(Runtime_GetAllScopesDetails) { HandleScope scope(isolate); DCHECK(args.length() == 3 || args.length() == 4); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]); bool ignore_nested_scopes = false; if (args.length() == 4) { CONVERT_BOOLEAN_ARG_CHECKED(flag, 3); ignore_nested_scopes = flag; } // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator frame_it(isolate, id); JavaScriptFrame* frame = frame_it.frame(); List<Handle<JSObject> > result(4); ScopeIterator it(isolate, frame, inlined_jsframe_index, ignore_nested_scopes); for (; !it.Done(); it.Next()) { Handle<JSObject> details; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details, MaterializeScopeDetails(isolate, &it)); result.Add(details); } Handle<FixedArray> array = isolate->factory()->NewFixedArray(result.length()); for (int i = 0; i < result.length(); ++i) { array->set(i, *result[i]); } return *isolate->factory()->NewJSArrayWithElements(array); } RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) { HandleScope scope(isolate); DCHECK(args.length() == 1); // Check arguments. CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); // Count the visible scopes. int n = 0; for (ScopeIterator it(isolate, fun); !it.Done(); it.Next()) { n++; } return Smi::FromInt(n); } RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) { HandleScope scope(isolate); DCHECK(args.length() == 2); // Check arguments. CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]); // Find the requested scope. int n = 0; ScopeIterator it(isolate, fun); for (; !it.Done() && n < index; it.Next()) { n++; } if (it.Done()) { return isolate->heap()->undefined_value(); } Handle<JSObject> details; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details, MaterializeScopeDetails(isolate, &it)); return *details; } static bool SetScopeVariableValue(ScopeIterator* it, int index, Handle<String> variable_name, Handle<Object> new_value) { for (int n = 0; !it->Done() && n < index; it->Next()) { n++; } if (it->Done()) { return false; } return it->SetVariableValue(variable_name, new_value); } // Change variable value in closure or local scope // args[0]: number or JsFunction: break id or function // args[1]: number: frame index (when arg[0] is break id) // args[2]: number: inlined frame index (when arg[0] is break id) // args[3]: number: scope index // args[4]: string: variable name // args[5]: object: new value // // Return true if success and false otherwise RUNTIME_FUNCTION(Runtime_SetScopeVariableValue) { HandleScope scope(isolate); DCHECK(args.length() == 6); // Check arguments. CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]); CONVERT_ARG_HANDLE_CHECKED(String, variable_name, 4); CONVERT_ARG_HANDLE_CHECKED(Object, new_value, 5); bool res; if (args[0]->IsNumber()) { CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]); // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator frame_it(isolate, id); JavaScriptFrame* frame = frame_it.frame(); ScopeIterator it(isolate, frame, inlined_jsframe_index); res = SetScopeVariableValue(&it, index, variable_name, new_value); } else { CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); ScopeIterator it(isolate, fun); res = SetScopeVariableValue(&it, index, variable_name, new_value); } return isolate->heap()->ToBoolean(res); } RUNTIME_FUNCTION(Runtime_DebugPrintScopes) { HandleScope scope(isolate); DCHECK(args.length() == 0); #ifdef DEBUG // Print the scopes for the top frame. StackFrameLocator locator(isolate); JavaScriptFrame* frame = locator.FindJavaScriptFrame(0); for (ScopeIterator it(isolate, frame, 0); !it.Done(); it.Next()) { it.DebugPrint(); } #endif return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_GetThreadCount) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); // Count all archived V8 threads. int n = 0; for (ThreadState* thread = isolate->thread_manager()->FirstThreadStateInUse(); thread != NULL; thread = thread->Next()) { n++; } // Total number of threads is current thread and archived threads. return Smi::FromInt(n + 1); } static const int kThreadDetailsCurrentThreadIndex = 0; static const int kThreadDetailsThreadIdIndex = 1; static const int kThreadDetailsSize = 2; // Return an array with thread details // args[0]: number: break id // args[1]: number: thread index // // The array returned contains the following information: // 0: Is current thread? // 1: Thread id RUNTIME_FUNCTION(Runtime_GetThreadDetails) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]); // Allocate array for result. Handle<FixedArray> details = isolate->factory()->NewFixedArray(kThreadDetailsSize); // Thread index 0 is current thread. if (index == 0) { // Fill the details. details->set(kThreadDetailsCurrentThreadIndex, isolate->heap()->true_value()); details->set(kThreadDetailsThreadIdIndex, Smi::FromInt(ThreadId::Current().ToInteger())); } else { // Find the thread with the requested index. int n = 1; ThreadState* thread = isolate->thread_manager()->FirstThreadStateInUse(); while (index != n && thread != NULL) { thread = thread->Next(); n++; } if (thread == NULL) { return isolate->heap()->undefined_value(); } // Fill the details. details->set(kThreadDetailsCurrentThreadIndex, isolate->heap()->false_value()); details->set(kThreadDetailsThreadIdIndex, Smi::FromInt(thread->id().ToInteger())); } // Convert to JS array and return. return *isolate->factory()->NewJSArrayWithElements(details); } // Sets the disable break state // args[0]: disable break state RUNTIME_FUNCTION(Runtime_SetDisableBreak) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 0); isolate->debug()->set_disable_break(disable_break); return isolate->heap()->undefined_value(); } static bool IsPositionAlignmentCodeCorrect(int alignment) { return alignment == STATEMENT_ALIGNED || alignment == BREAK_POSITION_ALIGNED; } RUNTIME_FUNCTION(Runtime_GetBreakLocations) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0); CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[1]); if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) { return isolate->ThrowIllegalOperation(); } BreakPositionAlignment alignment = static_cast<BreakPositionAlignment>(statement_aligned_code); Handle<SharedFunctionInfo> shared(fun->shared()); // Find the number of break points Handle<Object> break_locations = Debug::GetSourceBreakLocations(shared, alignment); if (break_locations->IsUndefined()) return isolate->heap()->undefined_value(); // Return array as JS array return *isolate->factory()->NewJSArrayWithElements( Handle<FixedArray>::cast(break_locations)); } // Set a break point in a function. // args[0]: function // args[1]: number: break source position (within the function source) // args[2]: number: break point object RUNTIME_FUNCTION(Runtime_SetFunctionBreakPoint) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]); RUNTIME_ASSERT(source_position >= function->shared()->start_position() && source_position <= function->shared()->end_position()); CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 2); // Set break point. RUNTIME_ASSERT(isolate->debug()->SetBreakPoint( function, break_point_object_arg, &source_position)); return Smi::FromInt(source_position); } // Changes the state of a break point in a script and returns source position // where break point was set. NOTE: Regarding performance see the NOTE for // GetScriptFromScriptData. // args[0]: script to set break point in // args[1]: number: break source position (within the script source) // args[2]: number, breakpoint position alignment // args[3]: number: break point object RUNTIME_FUNCTION(Runtime_SetScriptBreakPoint) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSValue, wrapper, 0); CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]); RUNTIME_ASSERT(source_position >= 0); CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[2]); CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 3); if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) { return isolate->ThrowIllegalOperation(); } BreakPositionAlignment alignment = static_cast<BreakPositionAlignment>(statement_aligned_code); // Get the script from the script wrapper. RUNTIME_ASSERT(wrapper->value()->IsScript()); Handle<Script> script(Script::cast(wrapper->value())); // Set break point. if (!isolate->debug()->SetBreakPointForScript(script, break_point_object_arg, &source_position, alignment)) { return isolate->heap()->undefined_value(); } return Smi::FromInt(source_position); } // Clear a break point // args[0]: number: break point object RUNTIME_FUNCTION(Runtime_ClearBreakPoint) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 0); // Clear break point. isolate->debug()->ClearBreakPoint(break_point_object_arg); return isolate->heap()->undefined_value(); } // Change the state of break on exceptions. // args[0]: Enum value indicating whether to affect caught/uncaught exceptions. // args[1]: Boolean indicating on/off. RUNTIME_FUNCTION(Runtime_ChangeBreakOnException) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]); CONVERT_BOOLEAN_ARG_CHECKED(enable, 1); // If the number doesn't match an enum value, the ChangeBreakOnException // function will default to affecting caught exceptions. ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg); // Update break point state. isolate->debug()->ChangeBreakOnException(type, enable); return isolate->heap()->undefined_value(); } // Returns the state of break on exceptions // args[0]: boolean indicating uncaught exceptions RUNTIME_FUNCTION(Runtime_IsBreakOnException) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]); ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg); bool result = isolate->debug()->IsBreakOnException(type); return Smi::FromInt(result); } // Prepare for stepping // args[0]: break id for checking execution state // args[1]: step action from the enumeration StepAction // args[2]: number of times to perform the step, for step out it is the number // of frames to step down. RUNTIME_FUNCTION(Runtime_PrepareStep) { HandleScope scope(isolate); DCHECK(args.length() == 4); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); if (!args[1]->IsNumber() || !args[2]->IsNumber()) { return isolate->Throw(isolate->heap()->illegal_argument_string()); } CONVERT_NUMBER_CHECKED(int, wrapped_frame_id, Int32, args[3]); StackFrame::Id frame_id; if (wrapped_frame_id == 0) { frame_id = StackFrame::NO_ID; } else { frame_id = UnwrapFrameId(wrapped_frame_id); } // Get the step action and check validity. StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1])); if (step_action != StepIn && step_action != StepNext && step_action != StepOut && step_action != StepInMin && step_action != StepMin) { return isolate->Throw(isolate->heap()->illegal_argument_string()); } if (frame_id != StackFrame::NO_ID && step_action != StepNext && step_action != StepMin && step_action != StepOut) { return isolate->ThrowIllegalOperation(); } // Get the number of steps. int step_count = NumberToInt32(args[2]); if (step_count < 1) { return isolate->Throw(isolate->heap()->illegal_argument_string()); } // Clear all current stepping setup. isolate->debug()->ClearStepping(); // Prepare step. isolate->debug()->PrepareStep(static_cast<StepAction>(step_action), step_count, frame_id); return isolate->heap()->undefined_value(); } // Clear all stepping set by PrepareStep. RUNTIME_FUNCTION(Runtime_ClearStepping) { HandleScope scope(isolate); DCHECK(args.length() == 0); isolate->debug()->ClearStepping(); return isolate->heap()->undefined_value(); } // Helper function to find or create the arguments object for // Runtime_DebugEvaluate. MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeArgumentsObject( Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function) { // Do not materialize the arguments object for eval or top-level code. // Skip if "arguments" is already taken. if (!function->shared()->is_function()) return target; Maybe<bool> maybe = JSReceiver::HasOwnProperty( target, isolate->factory()->arguments_string()); if (!maybe.has_value) return MaybeHandle<JSObject>(); if (maybe.value) return target; // FunctionGetArguments can't throw an exception. Handle<JSObject> arguments = Handle<JSObject>::cast(Accessors::FunctionGetArguments(function)); Handle<String> arguments_str = isolate->factory()->arguments_string(); RETURN_ON_EXCEPTION(isolate, Runtime::DefineObjectProperty( target, arguments_str, arguments, NONE), JSObject); return target; } // Compile and evaluate source for the given context. static MaybeHandle<Object> DebugEvaluate(Isolate* isolate, Handle<Context> context, Handle<Object> context_extension, Handle<Object> receiver, Handle<String> source) { if (context_extension->IsJSObject()) { Handle<JSObject> extension = Handle<JSObject>::cast(context_extension); Handle<JSFunction> closure(context->closure(), isolate); context = isolate->factory()->NewWithContext(closure, context, extension); } Handle<JSFunction> eval_fun; ASSIGN_RETURN_ON_EXCEPTION( isolate, eval_fun, Compiler::GetFunctionFromEval(source, context, SLOPPY, NO_PARSE_RESTRICTION, RelocInfo::kNoPosition), Object); Handle<Object> result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, Execution::Call(isolate, eval_fun, receiver, 0, NULL), Object); // Skip the global proxy as it has no properties and always delegates to the // real global object. if (result->IsJSGlobalProxy()) { PrototypeIterator iter(isolate, result); // TODO(verwaest): This will crash when the global proxy is detached. result = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)); } // Clear the oneshot breakpoints so that the debugger does not step further. isolate->debug()->ClearStepping(); return result; } static Handle<JSObject> NewJSObjectWithNullProto(Isolate* isolate) { Handle<JSObject> result = isolate->factory()->NewJSObject(isolate->object_function()); Handle<Map> new_map = Map::Copy(Handle<Map>(result->map())); new_map->set_prototype(*isolate->factory()->null_value()); JSObject::MigrateToMap(result, new_map); return result; } // Evaluate a piece of JavaScript in the context of a stack frame for // debugging. Things that need special attention are: // - Parameters and stack-allocated locals need to be materialized. Altered // values need to be written back to the stack afterwards. // - The arguments object needs to materialized. RUNTIME_FUNCTION(Runtime_DebugEvaluate) { HandleScope scope(isolate); // Check the execution state and decode arguments frame and source to be // evaluated. DCHECK(args.length() == 6); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_SMI_ARG_CHECKED(wrapped_id, 1); CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]); CONVERT_ARG_HANDLE_CHECKED(String, source, 3); CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 4); CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 5); // Handle the processing of break. DisableBreak disable_break_scope(isolate->debug(), disable_break); // Get the frame where the debugging is performed. StackFrame::Id id = UnwrapFrameId(wrapped_id); JavaScriptFrameIterator it(isolate, id); JavaScriptFrame* frame = it.frame(); FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate); Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction())); // Traverse the saved contexts chain to find the active context for the // selected frame. SaveContext* save = FindSavedContextForFrame(isolate, frame); SaveContext savex(isolate); isolate->set_context(*(save->context())); // Materialize stack locals and the arguments object. Handle<JSObject> materialized = NewJSObjectWithNullProto(isolate); ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, materialized, MaterializeStackLocalsWithFrameInspector(isolate, materialized, function, &frame_inspector)); ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, materialized, MaterializeArgumentsObject(isolate, materialized, function)); // At this point, the lookup chain may look like this: // [inner context] -> [function stack]+[function context] -> [outer context] // The function stack is not an actual context, it complements the function // context. In order to have the same lookup chain when debug-evaluating, // we materialize the stack and insert it into the context chain as a // with-context before the function context. // [inner context] -> [with context] -> [function context] -> [outer context] // Ordering the with-context before the function context forces a dynamic // lookup instead of a static lookup that could fail as the scope info is // outdated and may expect variables to still be stack-allocated. // Afterwards, we write changes to the with-context back to the stack // and remove it from the context chain. // This could cause lookup failures if debug-evaluate creates a closure that // uses this temporary context chain. Handle<Context> eval_context(Context::cast(frame_inspector.GetContext())); DCHECK(!eval_context.is_null()); Handle<Context> function_context = eval_context; Handle<Context> outer_context(function->context(), isolate); Handle<Context> inner_context; // We iterate to find the function's context. If the function has no // context-allocated variables, we iterate until we hit the outer context. while (!function_context->IsFunctionContext() && !function_context.is_identical_to(outer_context)) { inner_context = function_context; function_context = Handle<Context>(function_context->previous(), isolate); } Handle<Context> materialized_context = isolate->factory()->NewWithContext( function, function_context, materialized); if (inner_context.is_null()) { // No inner context. The with-context is now inner-most. eval_context = materialized_context; } else { inner_context->set_previous(*materialized_context); } Handle<Object> receiver(frame->receiver(), isolate); MaybeHandle<Object> maybe_result = DebugEvaluate(isolate, eval_context, context_extension, receiver, source); // Remove with-context if it was inserted in between. if (!inner_context.is_null()) inner_context->set_previous(*function_context); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result); // Write back potential changes to materialized stack locals to the stack. UpdateStackLocalsFromMaterializedObject(isolate, materialized, function, frame, inlined_jsframe_index); return *result; } RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) { HandleScope scope(isolate); // Check the execution state and decode arguments frame and source to be // evaluated. DCHECK(args.length() == 4); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_ARG_HANDLE_CHECKED(String, source, 1); CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 2); CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 3); // Handle the processing of break. DisableBreak disable_break_scope(isolate->debug(), disable_break); // Enter the top context from before the debugger was invoked. SaveContext save(isolate); SaveContext* top = &save; while (top != NULL && *top->context() == *isolate->debug()->debug_context()) { top = top->prev(); } if (top != NULL) { isolate->set_context(*top->context()); } // Get the native context now set to the top context from before the // debugger was invoked. Handle<Context> context = isolate->native_context(); Handle<JSObject> receiver(context->global_proxy()); Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, DebugEvaluate(isolate, context, context_extension, receiver, source)); return *result; } RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) { HandleScope scope(isolate); DCHECK(args.length() == 0); // Fill the script objects. Handle<FixedArray> instances = isolate->debug()->GetLoadedScripts(); // Convert the script objects to proper JS objects. for (int i = 0; i < instances->length(); i++) { Handle<Script> script = Handle<Script>(Script::cast(instances->get(i))); // Get the script wrapper in a local handle before calling GetScriptWrapper, // because using // instances->set(i, *GetScriptWrapper(script)) // is unsafe as GetScriptWrapper might call GC and the C++ compiler might // already have dereferenced the instances handle. Handle<JSObject> wrapper = Script::GetWrapper(script); instances->set(i, *wrapper); } // Return result as a JS array. Handle<JSObject> result = isolate->factory()->NewJSObject(isolate->array_function()); JSArray::SetContent(Handle<JSArray>::cast(result), instances); return *result; } // Helper function used by Runtime_DebugReferencedBy below. static int DebugReferencedBy(HeapIterator* iterator, JSObject* target, Object* instance_filter, int max_references, FixedArray* instances, int instances_size, JSFunction* arguments_function) { Isolate* isolate = target->GetIsolate(); SealHandleScope shs(isolate); DisallowHeapAllocation no_allocation; // Iterate the heap. int count = 0; JSObject* last = NULL; HeapObject* heap_obj = NULL; while (((heap_obj = iterator->next()) != NULL) && (max_references == 0 || count < max_references)) { // Only look at all JSObjects. if (heap_obj->IsJSObject()) { // Skip context extension objects and argument arrays as these are // checked in the context of functions using them. JSObject* obj = JSObject::cast(heap_obj); if (obj->IsJSContextExtensionObject() || obj->map()->constructor() == arguments_function) { continue; } // Check if the JS object has a reference to the object looked for. if (obj->ReferencesObject(target)) { // Check instance filter if supplied. This is normally used to avoid // references from mirror objects (see Runtime_IsInPrototypeChain). if (!instance_filter->IsUndefined()) { for (PrototypeIterator iter(isolate, obj); !iter.IsAtEnd(); iter.Advance()) { if (iter.GetCurrent() == instance_filter) { obj = NULL; // Don't add this object. break; } } } if (obj != NULL) { // Valid reference found add to instance array if supplied an update // count. if (instances != NULL && count < instances_size) { instances->set(count, obj); } last = obj; count++; } } } } // Check for circular reference only. This can happen when the object is only // referenced from mirrors and has a circular reference in which case the // object is not really alive and would have been garbage collected if not // referenced from the mirror. if (count == 1 && last == target) { count = 0; } // Return the number of referencing objects found. return count; } // Scan the heap for objects with direct references to an object // args[0]: the object to find references to // args[1]: constructor function for instances to exclude (Mirror) // args[2]: the the maximum number of objects to return RUNTIME_FUNCTION(Runtime_DebugReferencedBy) { HandleScope scope(isolate); DCHECK(args.length() == 3); // Check parameters. CONVERT_ARG_HANDLE_CHECKED(JSObject, target, 0); CONVERT_ARG_HANDLE_CHECKED(Object, instance_filter, 1); RUNTIME_ASSERT(instance_filter->IsUndefined() || instance_filter->IsJSObject()); CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]); RUNTIME_ASSERT(max_references >= 0); // Get the constructor function for context extension and arguments array. Handle<JSFunction> arguments_function( JSFunction::cast(isolate->sloppy_arguments_map()->constructor())); // Get the number of referencing objects. int count; // First perform a full GC in order to avoid dead objects and to make the heap // iterable. Heap* heap = isolate->heap(); heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy"); { HeapIterator heap_iterator(heap); count = DebugReferencedBy(&heap_iterator, *target, *instance_filter, max_references, NULL, 0, *arguments_function); } // Allocate an array to hold the result. Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count); // Fill the referencing objects. { HeapIterator heap_iterator(heap); count = DebugReferencedBy(&heap_iterator, *target, *instance_filter, max_references, *instances, count, *arguments_function); } // Return result as JS array. Handle<JSFunction> constructor = isolate->array_function(); Handle<JSObject> result = isolate->factory()->NewJSObject(constructor); JSArray::SetContent(Handle<JSArray>::cast(result), instances); return *result; } // Helper function used by Runtime_DebugConstructedBy below. static int DebugConstructedBy(HeapIterator* iterator, JSFunction* constructor, int max_references, FixedArray* instances, int instances_size) { DisallowHeapAllocation no_allocation; // Iterate the heap. int count = 0; HeapObject* heap_obj = NULL; while (((heap_obj = iterator->next()) != NULL) && (max_references == 0 || count < max_references)) { // Only look at all JSObjects. if (heap_obj->IsJSObject()) { JSObject* obj = JSObject::cast(heap_obj); if (obj->map()->constructor() == constructor) { // Valid reference found add to instance array if supplied an update // count. if (instances != NULL && count < instances_size) { instances->set(count, obj); } count++; } } } // Return the number of referencing objects found. return count; } // Scan the heap for objects constructed by a specific function. // args[0]: the constructor to find instances of // args[1]: the the maximum number of objects to return RUNTIME_FUNCTION(Runtime_DebugConstructedBy) { HandleScope scope(isolate); DCHECK(args.length() == 2); // Check parameters. CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0); CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]); RUNTIME_ASSERT(max_references >= 0); // Get the number of referencing objects. int count; // First perform a full GC in order to avoid dead objects and to make the heap // iterable. Heap* heap = isolate->heap(); heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy"); { HeapIterator heap_iterator(heap); count = DebugConstructedBy(&heap_iterator, *constructor, max_references, NULL, 0); } // Allocate an array to hold the result. Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count); // Fill the referencing objects. { HeapIterator heap_iterator2(heap); count = DebugConstructedBy(&heap_iterator2, *constructor, max_references, *instances, count); } // Return result as JS array. Handle<JSFunction> array_function = isolate->array_function(); Handle<JSObject> result = isolate->factory()->NewJSObject(array_function); JSArray::SetContent(Handle<JSArray>::cast(result), instances); return *result; } // Find the effective prototype object as returned by __proto__. // args[0]: the object to find the prototype for. RUNTIME_FUNCTION(Runtime_DebugGetPrototype) { HandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); return *GetPrototypeSkipHiddenPrototypes(isolate, obj); } // Patches script source (should be called upon BeforeCompile event). RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSValue, script_wrapper, 0); CONVERT_ARG_HANDLE_CHECKED(String, source, 1); RUNTIME_ASSERT(script_wrapper->value()->IsScript()); Handle<Script> script(Script::cast(script_wrapper->value())); int compilation_state = script->compilation_state(); RUNTIME_ASSERT(compilation_state == Script::COMPILATION_STATE_INITIAL); script->set_source(*source); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugDisassembleFunction) { HandleScope scope(isolate); #ifdef DEBUG DCHECK(args.length() == 1); // Get the function and make sure it is compiled. CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0); if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) { return isolate->heap()->exception(); } OFStream os(stdout); func->code()->Print(os); os << endl; #endif // DEBUG return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_DebugDisassembleConstructor) { HandleScope scope(isolate); #ifdef DEBUG DCHECK(args.length() == 1); // Get the function and make sure it is compiled. CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0); if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) { return isolate->heap()->exception(); } OFStream os(stdout); func->shared()->construct_stub()->Print(os); os << endl; #endif // DEBUG return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return f->shared()->inferred_name(); } static int FindSharedFunctionInfosForScript(HeapIterator* iterator, Script* script, FixedArray* buffer) { DisallowHeapAllocation no_allocation; int counter = 0; int buffer_size = buffer->length(); for (HeapObject* obj = iterator->next(); obj != NULL; obj = iterator->next()) { DCHECK(obj != NULL); if (!obj->IsSharedFunctionInfo()) { continue; } SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj); if (shared->script() != script) { continue; } if (counter < buffer_size) { buffer->set(counter, shared); } counter++; } return counter; } // For a script finds all SharedFunctionInfo's in the heap that points // to this script. Returns JSArray of SharedFunctionInfo wrapped // in OpaqueReferences. RUNTIME_FUNCTION(Runtime_LiveEditFindSharedFunctionInfosForScript) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSValue, script_value, 0); RUNTIME_ASSERT(script_value->value()->IsScript()); Handle<Script> script = Handle<Script>(Script::cast(script_value->value())); const int kBufferSize = 32; Handle<FixedArray> array; array = isolate->factory()->NewFixedArray(kBufferSize); int number; Heap* heap = isolate->heap(); { HeapIterator heap_iterator(heap); Script* scr = *script; FixedArray* arr = *array; number = FindSharedFunctionInfosForScript(&heap_iterator, scr, arr); } if (number > kBufferSize) { array = isolate->factory()->NewFixedArray(number); HeapIterator heap_iterator(heap); Script* scr = *script; FixedArray* arr = *array; FindSharedFunctionInfosForScript(&heap_iterator, scr, arr); } Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(array); result->set_length(Smi::FromInt(number)); LiveEdit::WrapSharedFunctionInfos(result); return *result; } // For a script calculates compilation information about all its functions. // The script source is explicitly specified by the second argument. // The source of the actual script is not used, however it is important that // all generated code keeps references to this particular instance of script. // Returns a JSArray of compilation infos. The array is ordered so that // each function with all its descendant is always stored in a continues range // with the function itself going first. The root function is a script function. RUNTIME_FUNCTION(Runtime_LiveEditGatherCompileInfo) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(JSValue, script, 0); CONVERT_ARG_HANDLE_CHECKED(String, source, 1); RUNTIME_ASSERT(script->value()->IsScript()); Handle<Script> script_handle = Handle<Script>(Script::cast(script->value())); Handle<JSArray> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, result, LiveEdit::GatherCompileInfo(script_handle, source)); return *result; } // Changes the source of the script to a new_source. // If old_script_name is provided (i.e. is a String), also creates a copy of // the script with its original source and sends notification to debugger. RUNTIME_FUNCTION(Runtime_LiveEditReplaceScript) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 3); CONVERT_ARG_CHECKED(JSValue, original_script_value, 0); CONVERT_ARG_HANDLE_CHECKED(String, new_source, 1); CONVERT_ARG_HANDLE_CHECKED(Object, old_script_name, 2); RUNTIME_ASSERT(original_script_value->value()->IsScript()); Handle<Script> original_script(Script::cast(original_script_value->value())); Handle<Object> old_script = LiveEdit::ChangeScriptSource( original_script, new_source, old_script_name); if (old_script->IsScript()) { Handle<Script> script_handle = Handle<Script>::cast(old_script); return *Script::GetWrapper(script_handle); } else { return isolate->heap()->null_value(); } } RUNTIME_FUNCTION(Runtime_LiveEditFunctionSourceUpdated) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 0); RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info)); LiveEdit::FunctionSourceUpdated(shared_info); return isolate->heap()->undefined_value(); } // Replaces code of SharedFunctionInfo with a new one. RUNTIME_FUNCTION(Runtime_LiveEditReplaceFunctionCode) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, new_compile_info, 0); CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 1); RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info)); LiveEdit::ReplaceFunctionCode(new_compile_info, shared_info); return isolate->heap()->undefined_value(); } // Connects SharedFunctionInfo to another script. RUNTIME_FUNCTION(Runtime_LiveEditFunctionSetScript) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, script_object, 1); if (function_object->IsJSValue()) { Handle<JSValue> function_wrapper = Handle<JSValue>::cast(function_object); if (script_object->IsJSValue()) { RUNTIME_ASSERT(JSValue::cast(*script_object)->value()->IsScript()); Script* script = Script::cast(JSValue::cast(*script_object)->value()); script_object = Handle<Object>(script, isolate); } RUNTIME_ASSERT(function_wrapper->value()->IsSharedFunctionInfo()); LiveEdit::SetFunctionScript(function_wrapper, script_object); } else { // Just ignore this. We may not have a SharedFunctionInfo for some functions // and we check it in this function. } return isolate->heap()->undefined_value(); } // In a code of a parent function replaces original function as embedded object // with a substitution one. RUNTIME_FUNCTION(Runtime_LiveEditReplaceRefToNestedFunction) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSValue, parent_wrapper, 0); CONVERT_ARG_HANDLE_CHECKED(JSValue, orig_wrapper, 1); CONVERT_ARG_HANDLE_CHECKED(JSValue, subst_wrapper, 2); RUNTIME_ASSERT(parent_wrapper->value()->IsSharedFunctionInfo()); RUNTIME_ASSERT(orig_wrapper->value()->IsSharedFunctionInfo()); RUNTIME_ASSERT(subst_wrapper->value()->IsSharedFunctionInfo()); LiveEdit::ReplaceRefToNestedFunction(parent_wrapper, orig_wrapper, subst_wrapper); return isolate->heap()->undefined_value(); } // Updates positions of a shared function info (first parameter) according // to script source change. Text change is described in second parameter as // array of groups of 3 numbers: // (change_begin, change_end, change_end_new_position). // Each group describes a change in text; groups are sorted by change_begin. RUNTIME_FUNCTION(Runtime_LiveEditPatchFunctionPositions) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0); CONVERT_ARG_HANDLE_CHECKED(JSArray, position_change_array, 1); RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_array)) LiveEdit::PatchFunctionPositions(shared_array, position_change_array); return isolate->heap()->undefined_value(); } // For array of SharedFunctionInfo's (each wrapped in JSValue) // checks that none of them have activations on stacks (of any thread). // Returns array of the same length with corresponding results of // LiveEdit::FunctionPatchabilityStatus type. RUNTIME_FUNCTION(Runtime_LiveEditCheckAndDropActivations) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0); CONVERT_BOOLEAN_ARG_CHECKED(do_drop, 1); RUNTIME_ASSERT(shared_array->length()->IsSmi()); RUNTIME_ASSERT(shared_array->HasFastElements()) int array_length = Smi::cast(shared_array->length())->value(); for (int i = 0; i < array_length; i++) { Handle<Object> element = Object::GetElement(isolate, shared_array, i).ToHandleChecked(); RUNTIME_ASSERT( element->IsJSValue() && Handle<JSValue>::cast(element)->value()->IsSharedFunctionInfo()); } return *LiveEdit::CheckAndDropActivations(shared_array, do_drop); } // Compares 2 strings line-by-line, then token-wise and returns diff in form // of JSArray of triplets (pos1, pos1_end, pos2_end) describing list // of diff chunks. RUNTIME_FUNCTION(Runtime_LiveEditCompareStrings) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, s1, 0); CONVERT_ARG_HANDLE_CHECKED(String, s2, 1); return *LiveEdit::CompareStrings(s1, s2); } // Restarts a call frame and completely drops all frames above. // Returns true if successful. Otherwise returns undefined or an error message. RUNTIME_FUNCTION(Runtime_LiveEditRestartFrame) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]); RUNTIME_ASSERT(CheckExecutionState(isolate, break_id)); CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]); Heap* heap = isolate->heap(); // Find the relevant frame with the requested index. StackFrame::Id id = isolate->debug()->break_frame_id(); if (id == StackFrame::NO_ID) { // If there are no JavaScript stack frames return undefined. return heap->undefined_value(); } JavaScriptFrameIterator it(isolate, id); int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index); if (inlined_jsframe_index == -1) return heap->undefined_value(); // We don't really care what the inlined frame index is, since we are // throwing away the entire frame anyways. const char* error_message = LiveEdit::RestartFrame(it.frame()); if (error_message) { return *(isolate->factory()->InternalizeUtf8String(error_message)); } return heap->true_value(); } // A testing entry. Returns statement position which is the closest to // source_position. RUNTIME_FUNCTION(Runtime_GetFunctionCodePositionFromSource) { HandleScope scope(isolate); CHECK(isolate->debug()->live_edit_enabled()); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]); Handle<Code> code(function->code(), isolate); if (code->kind() != Code::FUNCTION && code->kind() != Code::OPTIMIZED_FUNCTION) { return isolate->heap()->undefined_value(); } RelocIterator it(*code, RelocInfo::ModeMask(RelocInfo::STATEMENT_POSITION)); int closest_pc = 0; int distance = kMaxInt; while (!it.done()) { int statement_position = static_cast<int>(it.rinfo()->data()); // Check if this break point is closer that what was previously found. if (source_position <= statement_position && statement_position - source_position < distance) { closest_pc = static_cast<int>(it.rinfo()->pc() - code->instruction_start()); distance = statement_position - source_position; // Check whether we can't get any closer. if (distance == 0) break; } it.next(); } return Smi::FromInt(closest_pc); } // Calls specified function with or without entering the debugger. // This is used in unit tests to run code as if debugger is entered or simply // to have a stack with C++ frame in the middle. RUNTIME_FUNCTION(Runtime_ExecuteInDebugContext) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_BOOLEAN_ARG_CHECKED(without_debugger, 1); MaybeHandle<Object> maybe_result; if (without_debugger) { maybe_result = Execution::Call(isolate, function, handle(function->global_proxy()), 0, NULL); } else { DebugScope debug_scope(isolate->debug()); maybe_result = Execution::Call(isolate, function, handle(function->global_proxy()), 0, NULL); } Handle<Object> result; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result); return *result; } // Performs a GC. // Presently, it only does a full GC. RUNTIME_FUNCTION(Runtime_CollectGarbage) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags, "%CollectGarbage"); return isolate->heap()->undefined_value(); } // Gets the current heap usage. RUNTIME_FUNCTION(Runtime_GetHeapUsage) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); int usage = static_cast<int>(isolate->heap()->SizeOfObjects()); if (!Smi::IsValid(usage)) { return *isolate->factory()->NewNumberFromInt(usage); } return Smi::FromInt(usage); } // Finds the script object from the script data. NOTE: This operation uses // heap traversal to find the function generated for the source position // for the requested break point. For lazily compiled functions several heap // traversals might be required rendering this operation as a rather slow // operation. However for setting break points which is normally done through // some kind of user interaction the performance is not crucial. static Handle<Object> Runtime_GetScriptFromScriptName( Handle<String> script_name) { // Scan the heap for Script objects to find the script with the requested // script data. Handle<Script> script; Factory* factory = script_name->GetIsolate()->factory(); Heap* heap = script_name->GetHeap(); HeapIterator iterator(heap); HeapObject* obj = NULL; while (script.is_null() && ((obj = iterator.next()) != NULL)) { // If a script is found check if it has the script data requested. if (obj->IsScript()) { if (Script::cast(obj)->name()->IsString()) { if (String::cast(Script::cast(obj)->name())->Equals(*script_name)) { script = Handle<Script>(Script::cast(obj)); } } } } // If no script with the requested script data is found return undefined. if (script.is_null()) return factory->undefined_value(); // Return the script found. return Script::GetWrapper(script); } // Get the script object from script data. NOTE: Regarding performance // see the NOTE for GetScriptFromScriptData. // args[0]: script data for the script to find the source for RUNTIME_FUNCTION(Runtime_GetScript) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(String, script_name, 0); // Find the requested script. Handle<Object> result = Runtime_GetScriptFromScriptName(Handle<String>(script_name)); return *result; } // Collect the raw data for a stack trace. Returns an array of 4 // element segments each containing a receiver, function, code and // native code offset. RUNTIME_FUNCTION(Runtime_CollectStackTrace) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, error_object, 0); CONVERT_ARG_HANDLE_CHECKED(Object, caller, 1); if (!isolate->bootstrapper()->IsActive()) { // Optionally capture a more detailed stack trace for the message. isolate->CaptureAndSetDetailedStackTrace(error_object); // Capture a simple stack trace for the stack property. isolate->CaptureAndSetSimpleStackTrace(error_object, caller); } return isolate->heap()->undefined_value(); } // Returns V8 version as a string. RUNTIME_FUNCTION(Runtime_GetV8Version) { HandleScope scope(isolate); DCHECK(args.length() == 0); const char* version_string = v8::V8::GetVersion(); return *isolate->factory()->NewStringFromAsciiChecked(version_string); } // Returns function of generator activation. RUNTIME_FUNCTION(Runtime_GeneratorGetFunction) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); return generator->function(); } // Returns context of generator activation. RUNTIME_FUNCTION(Runtime_GeneratorGetContext) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); return generator->context(); } // Returns receiver of generator activation. RUNTIME_FUNCTION(Runtime_GeneratorGetReceiver) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); return generator->receiver(); } // Returns generator continuation as a PC offset, or the magic -1 or 0 values. RUNTIME_FUNCTION(Runtime_GeneratorGetContinuation) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); return Smi::FromInt(generator->continuation()); } RUNTIME_FUNCTION(Runtime_GeneratorGetSourcePosition) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0); if (generator->is_suspended()) { Handle<Code> code(generator->function()->code(), isolate); int offset = generator->continuation(); RUNTIME_ASSERT(0 <= offset && offset < code->Size()); Address pc = code->address() + offset; return Smi::FromInt(code->SourcePosition(pc)); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_LoadMutableDouble) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Smi, index, 1); RUNTIME_ASSERT((index->value() & 1) == 1); FieldIndex field_index = FieldIndex::ForLoadByFieldIndex(object->map(), index->value()); if (field_index.is_inobject()) { RUNTIME_ASSERT(field_index.property_index() < object->map()->inobject_properties()); } else { RUNTIME_ASSERT(field_index.outobject_array_index() < object->properties()->length()); } Handle<Object> raw_value(object->RawFastPropertyAt(field_index), isolate); RUNTIME_ASSERT(raw_value->IsMutableHeapNumber()); return *Object::WrapForRead(isolate, raw_value, Representation::Double()); } RUNTIME_FUNCTION(Runtime_TryMigrateInstance) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, object, 0); if (!object->IsJSObject()) return Smi::FromInt(0); Handle<JSObject> js_object = Handle<JSObject>::cast(object); if (!js_object->map()->is_deprecated()) return Smi::FromInt(0); // This call must not cause lazy deopts, because it's called from deferred // code where we can't handle lazy deopts for lack of a suitable bailout // ID. So we just try migration and signal failure if necessary, // which will also trigger a deopt. if (!JSObject::TryMigrateInstance(js_object)) return Smi::FromInt(0); return *object; } RUNTIME_FUNCTION(Runtime_GetFromCache) { SealHandleScope shs(isolate); // This is only called from codegen, so checks might be more lax. CONVERT_ARG_CHECKED(JSFunctionResultCache, cache, 0); CONVERT_ARG_CHECKED(Object, key, 1); { DisallowHeapAllocation no_alloc; int finger_index = cache->finger_index(); Object* o = cache->get(finger_index); if (o == key) { // The fastest case: hit the same place again. return cache->get(finger_index + 1); } for (int i = finger_index - 2; i >= JSFunctionResultCache::kEntriesIndex; i -= 2) { o = cache->get(i); if (o == key) { cache->set_finger_index(i); return cache->get(i + 1); } } int size = cache->size(); DCHECK(size <= cache->length()); for (int i = size - 2; i > finger_index; i -= 2) { o = cache->get(i); if (o == key) { cache->set_finger_index(i); return cache->get(i + 1); } } } // There is no value in the cache. Invoke the function and cache result. HandleScope scope(isolate); Handle<JSFunctionResultCache> cache_handle(cache); Handle<Object> key_handle(key, isolate); Handle<Object> value; { Handle<JSFunction> factory(JSFunction::cast( cache_handle->get(JSFunctionResultCache::kFactoryIndex))); // TODO(antonm): consider passing a receiver when constructing a cache. Handle<JSObject> receiver(isolate->global_proxy()); // This handle is nor shared, nor used later, so it's safe. Handle<Object> argv[] = {key_handle}; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, value, Execution::Call(isolate, factory, receiver, arraysize(argv), argv)); } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { cache_handle->JSFunctionResultCacheVerify(); } #endif // Function invocation may have cleared the cache. Reread all the data. int finger_index = cache_handle->finger_index(); int size = cache_handle->size(); // If we have spare room, put new data into it, otherwise evict post finger // entry which is likely to be the least recently used. int index = -1; if (size < cache_handle->length()) { cache_handle->set_size(size + JSFunctionResultCache::kEntrySize); index = size; } else { index = finger_index + JSFunctionResultCache::kEntrySize; if (index == cache_handle->length()) { index = JSFunctionResultCache::kEntriesIndex; } } DCHECK(index % 2 == 0); DCHECK(index >= JSFunctionResultCache::kEntriesIndex); DCHECK(index < cache_handle->length()); cache_handle->set(index, *key_handle); cache_handle->set(index + 1, *value); cache_handle->set_finger_index(index); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { cache_handle->JSFunctionResultCacheVerify(); } #endif return *value; } RUNTIME_FUNCTION(Runtime_MessageGetStartPosition) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSMessageObject, message, 0); return Smi::FromInt(message->start_position()); } RUNTIME_FUNCTION(Runtime_MessageGetScript) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(JSMessageObject, message, 0); return message->script(); } #ifdef DEBUG // ListNatives is ONLY used by the fuzz-natives.js in debug mode // Exclude the code in release mode. RUNTIME_FUNCTION(Runtime_ListNatives) { HandleScope scope(isolate); DCHECK(args.length() == 0); #define COUNT_ENTRY(Name, argc, ressize) +1 int entry_count = 0 RUNTIME_FUNCTION_LIST(COUNT_ENTRY) INLINE_FUNCTION_LIST(COUNT_ENTRY) INLINE_OPTIMIZED_FUNCTION_LIST(COUNT_ENTRY); #undef COUNT_ENTRY Factory* factory = isolate->factory(); Handle<FixedArray> elements = factory->NewFixedArray(entry_count); int index = 0; bool inline_runtime_functions = false; #define ADD_ENTRY(Name, argc, ressize) \ { \ HandleScope inner(isolate); \ Handle<String> name; \ /* Inline runtime functions have an underscore in front of the name. */ \ if (inline_runtime_functions) { \ name = factory->NewStringFromStaticChars("_" #Name); \ } else { \ name = factory->NewStringFromStaticChars(#Name); \ } \ Handle<FixedArray> pair_elements = factory->NewFixedArray(2); \ pair_elements->set(0, *name); \ pair_elements->set(1, Smi::FromInt(argc)); \ Handle<JSArray> pair = factory->NewJSArrayWithElements(pair_elements); \ elements->set(index++, *pair); \ } inline_runtime_functions = false; RUNTIME_FUNCTION_LIST(ADD_ENTRY) INLINE_OPTIMIZED_FUNCTION_LIST(ADD_ENTRY) inline_runtime_functions = true; INLINE_FUNCTION_LIST(ADD_ENTRY) #undef ADD_ENTRY DCHECK_EQ(index, entry_count); Handle<JSArray> result = factory->NewJSArrayWithElements(elements); return *result; } #endif RUNTIME_FUNCTION(Runtime_IS_VAR) { UNREACHABLE(); // implemented as macro in the parser return NULL; } #define TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, size) \ RUNTIME_FUNCTION(Runtime_HasExternal##Type##Elements) { \ CONVERT_ARG_CHECKED(JSObject, obj, 0); \ return isolate->heap()->ToBoolean(obj->HasExternal##Type##Elements()); \ } TYPED_ARRAYS(TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION) #undef TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION #define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s) \ RUNTIME_FUNCTION(Runtime_HasFixed##Type##Elements) { \ CONVERT_ARG_CHECKED(JSObject, obj, 0); \ return isolate->heap()->ToBoolean(obj->HasFixed##Type##Elements()); \ } TYPED_ARRAYS(FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION) #undef FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION RUNTIME_FUNCTION(Runtime_IsJSGlobalProxy) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSGlobalProxy()); } RUNTIME_FUNCTION(Runtime_IsObserved) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); if (!args[0]->IsJSReceiver()) return isolate->heap()->false_value(); CONVERT_ARG_CHECKED(JSReceiver, obj, 0); DCHECK(!obj->IsJSGlobalProxy() || !obj->map()->is_observed()); return isolate->heap()->ToBoolean(obj->map()->is_observed()); } RUNTIME_FUNCTION(Runtime_SetIsObserved) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, obj, 0); RUNTIME_ASSERT(!obj->IsJSGlobalProxy()); if (obj->IsJSProxy()) return isolate->heap()->undefined_value(); RUNTIME_ASSERT(!obj->map()->is_observed()); DCHECK(obj->IsJSObject()); JSObject::SetObserved(Handle<JSObject>::cast(obj)); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_EnqueueMicrotask) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, microtask, 0); isolate->EnqueueMicrotask(microtask); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_RunMicrotasks) { HandleScope scope(isolate); DCHECK(args.length() == 0); isolate->RunMicrotasks(); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_GetObservationState) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); return isolate->heap()->observation_state(); } static bool ContextsHaveSameOrigin(Handle<Context> context1, Handle<Context> context2) { return context1->security_token() == context2->security_token(); } RUNTIME_FUNCTION(Runtime_ObserverObjectAndRecordHaveSameOrigin) { HandleScope scope(isolate); DCHECK(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSFunction, observer, 0); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, record, 2); Handle<Context> observer_context(observer->context()->native_context()); Handle<Context> object_context(object->GetCreationContext()); Handle<Context> record_context(record->GetCreationContext()); return isolate->heap()->ToBoolean( ContextsHaveSameOrigin(object_context, observer_context) && ContextsHaveSameOrigin(object_context, record_context)); } RUNTIME_FUNCTION(Runtime_ObjectWasCreatedInCurrentOrigin) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); Handle<Context> creation_context(object->GetCreationContext(), isolate); return isolate->heap()->ToBoolean( ContextsHaveSameOrigin(creation_context, isolate->native_context())); } RUNTIME_FUNCTION(Runtime_GetObjectContextObjectObserve) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); Handle<Context> context(object->GetCreationContext(), isolate); return context->native_object_observe(); } RUNTIME_FUNCTION(Runtime_GetObjectContextObjectGetNotifier) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); Handle<Context> context(object->GetCreationContext(), isolate); return context->native_object_get_notifier(); } RUNTIME_FUNCTION(Runtime_GetObjectContextNotifierPerformChange) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, object_info, 0); Handle<Context> context(object_info->GetCreationContext(), isolate); return context->native_object_notifier_perform_change(); } static Object* ArrayConstructorCommon(Isolate* isolate, Handle<JSFunction> constructor, Handle<AllocationSite> site, Arguments* caller_args) { Factory* factory = isolate->factory(); bool holey = false; bool can_use_type_feedback = true; if (caller_args->length() == 1) { Handle<Object> argument_one = caller_args->at<Object>(0); if (argument_one->IsSmi()) { int value = Handle<Smi>::cast(argument_one)->value(); if (value < 0 || value >= JSObject::kInitialMaxFastElementArray) { // the array is a dictionary in this case. can_use_type_feedback = false; } else if (value != 0) { holey = true; } } else { // Non-smi length argument produces a dictionary can_use_type_feedback = false; } } Handle<JSArray> array; if (!site.is_null() && can_use_type_feedback) { ElementsKind to_kind = site->GetElementsKind(); if (holey && !IsFastHoleyElementsKind(to_kind)) { to_kind = GetHoleyElementsKind(to_kind); // Update the allocation site info to reflect the advice alteration. site->SetElementsKind(to_kind); } // We should allocate with an initial map that reflects the allocation site // advice. Therefore we use AllocateJSObjectFromMap instead of passing // the constructor. Handle<Map> initial_map(constructor->initial_map(), isolate); if (to_kind != initial_map->elements_kind()) { initial_map = Map::AsElementsKind(initial_map, to_kind); } // If we don't care to track arrays of to_kind ElementsKind, then // don't emit a memento for them. Handle<AllocationSite> allocation_site; if (AllocationSite::GetMode(to_kind) == TRACK_ALLOCATION_SITE) { allocation_site = site; } array = Handle<JSArray>::cast(factory->NewJSObjectFromMap( initial_map, NOT_TENURED, true, allocation_site)); } else { array = Handle<JSArray>::cast(factory->NewJSObject(constructor)); // We might need to transition to holey ElementsKind kind = constructor->initial_map()->elements_kind(); if (holey && !IsFastHoleyElementsKind(kind)) { kind = GetHoleyElementsKind(kind); JSObject::TransitionElementsKind(array, kind); } } factory->NewJSArrayStorage(array, 0, 0, DONT_INITIALIZE_ARRAY_ELEMENTS); ElementsKind old_kind = array->GetElementsKind(); RETURN_FAILURE_ON_EXCEPTION( isolate, ArrayConstructInitializeElements(array, caller_args)); if (!site.is_null() && (old_kind != array->GetElementsKind() || !can_use_type_feedback)) { // The arguments passed in caused a transition. This kind of complexity // can't be dealt with in the inlined hydrogen array constructor case. // We must mark the allocationsite as un-inlinable. site->SetDoNotInlineCall(); } return *array; } RUNTIME_FUNCTION(Runtime_ArrayConstructor) { HandleScope scope(isolate); // If we get 2 arguments then they are the stub parameters (constructor, type // info). If we get 4, then the first one is a pointer to the arguments // passed by the caller, and the last one is the length of the arguments // passed to the caller (redundant, but useful to check on the deoptimizer // with an assert). Arguments empty_args(0, NULL); bool no_caller_args = args.length() == 2; DCHECK(no_caller_args || args.length() == 4); int parameters_start = no_caller_args ? 0 : 1; Arguments* caller_args = no_caller_args ? &empty_args : reinterpret_cast<Arguments*>(args[0]); CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start); CONVERT_ARG_HANDLE_CHECKED(Object, type_info, parameters_start + 1); #ifdef DEBUG if (!no_caller_args) { CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 2); DCHECK(arg_count == caller_args->length()); } #endif Handle<AllocationSite> site; if (!type_info.is_null() && *type_info != isolate->heap()->undefined_value()) { site = Handle<AllocationSite>::cast(type_info); DCHECK(!site->SitePointsToLiteral()); } return ArrayConstructorCommon(isolate, constructor, site, caller_args); } RUNTIME_FUNCTION(Runtime_InternalArrayConstructor) { HandleScope scope(isolate); Arguments empty_args(0, NULL); bool no_caller_args = args.length() == 1; DCHECK(no_caller_args || args.length() == 3); int parameters_start = no_caller_args ? 0 : 1; Arguments* caller_args = no_caller_args ? &empty_args : reinterpret_cast<Arguments*>(args[0]); CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start); #ifdef DEBUG if (!no_caller_args) { CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 1); DCHECK(arg_count == caller_args->length()); } #endif return ArrayConstructorCommon(isolate, constructor, Handle<AllocationSite>::null(), caller_args); } RUNTIME_FUNCTION(Runtime_NormalizeElements) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0); RUNTIME_ASSERT(!array->HasExternalArrayElements() && !array->HasFixedTypedArrayElements()); JSObject::NormalizeElements(array); return *array; } RUNTIME_FUNCTION(Runtime_MaxSmi) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); return Smi::FromInt(Smi::kMaxValue); } // TODO(dcarney): remove this function when TurboFan supports it. // Takes the object to be iterated over and the result of GetPropertyNamesFast // Returns pair (cache_array, cache_type). RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInInit) { SealHandleScope scope(isolate); DCHECK(args.length() == 2); // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs. // Not worth creating a macro atm as this function should be removed. if (!args[0]->IsJSReceiver() || !args[1]->IsObject()) { Object* error = isolate->ThrowIllegalOperation(); return MakePair(error, isolate->heap()->undefined_value()); } Handle<JSReceiver> object = args.at<JSReceiver>(0); Handle<Object> cache_type = args.at<Object>(1); if (cache_type->IsMap()) { // Enum cache case. if (Map::EnumLengthBits::decode(Map::cast(*cache_type)->bit_field3()) == 0) { // 0 length enum. // Can't handle this case in the graph builder, // so transform it into the empty fixed array case. return MakePair(isolate->heap()->empty_fixed_array(), Smi::FromInt(1)); } return MakePair(object->map()->instance_descriptors()->GetEnumCache(), *cache_type); } else { // FixedArray case. Smi* new_cache_type = Smi::FromInt(object->IsJSProxy() ? 0 : 1); return MakePair(*Handle<FixedArray>::cast(cache_type), new_cache_type); } } // TODO(dcarney): remove this function when TurboFan supports it. RUNTIME_FUNCTION(Runtime_ForInCacheArrayLength) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(Object, cache_type, 0); CONVERT_ARG_HANDLE_CHECKED(FixedArray, array, 1); int length = 0; if (cache_type->IsMap()) { length = Map::cast(*cache_type)->EnumLength(); } else { DCHECK(cache_type->IsSmi()); length = array->length(); } return Smi::FromInt(length); } // TODO(dcarney): remove this function when TurboFan supports it. // Takes (the object to be iterated over, // cache_array from ForInInit, // cache_type from ForInInit, // the current index) // Returns pair (array[index], needs_filtering). RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInNext) { SealHandleScope scope(isolate); DCHECK(args.length() == 4); int32_t index; // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs. // Not worth creating a macro atm as this function should be removed. if (!args[0]->IsJSReceiver() || !args[1]->IsFixedArray() || !args[2]->IsObject() || !args[3]->ToInt32(&index)) { Object* error = isolate->ThrowIllegalOperation(); return MakePair(error, isolate->heap()->undefined_value()); } Handle<JSReceiver> object = args.at<JSReceiver>(0); Handle<FixedArray> array = args.at<FixedArray>(1); Handle<Object> cache_type = args.at<Object>(2); // Figure out first if a slow check is needed for this object. bool slow_check_needed = false; if (cache_type->IsMap()) { if (object->map() != Map::cast(*cache_type)) { // Object transitioned. Need slow check. slow_check_needed = true; } } else { // No slow check needed for proxies. slow_check_needed = Smi::cast(*cache_type)->value() == 1; } return MakePair(array->get(index), isolate->heap()->ToBoolean(slow_check_needed)); } // ---------------------------------------------------------------------------- // Reference implementation for inlined runtime functions. Only used when the // compiler does not support a certain intrinsic. Don't optimize these, but // implement the intrinsic in the respective compiler instead. // TODO(mstarzinger): These are place-holder stubs for TurboFan and will // eventually all have a C++ implementation and this macro will be gone. #define U(name) \ RUNTIME_FUNCTION(RuntimeReference_##name) { \ UNIMPLEMENTED(); \ return NULL; \ } U(IsStringWrapperSafeForDefaultValueOf) U(DebugBreakInOptimizedCode) #undef U RUNTIME_FUNCTION(RuntimeReference_IsSmi) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsSmi()); } RUNTIME_FUNCTION(RuntimeReference_IsNonNegativeSmi) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsSmi() && Smi::cast(obj)->value() >= 0); } RUNTIME_FUNCTION(RuntimeReference_IsArray) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSArray()); } RUNTIME_FUNCTION(RuntimeReference_IsRegExp) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSRegExp()); } RUNTIME_FUNCTION(RuntimeReference_IsConstructCall) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); return isolate->heap()->ToBoolean(frame->IsConstructor()); } RUNTIME_FUNCTION(RuntimeReference_CallFunction) { SealHandleScope shs(isolate); return __RT_impl_Runtime_Call(args, isolate); } RUNTIME_FUNCTION(RuntimeReference_ArgumentsLength) { SealHandleScope shs(isolate); DCHECK(args.length() == 0); JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); return Smi::FromInt(frame->GetArgumentsLength()); } RUNTIME_FUNCTION(RuntimeReference_Arguments) { SealHandleScope shs(isolate); return __RT_impl_Runtime_GetArgumentsProperty(args, isolate); } RUNTIME_FUNCTION(RuntimeReference_ValueOf) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); if (!obj->IsJSValue()) return obj; return JSValue::cast(obj)->value(); } RUNTIME_FUNCTION(RuntimeReference_SetValueOf) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(Object, obj, 0); CONVERT_ARG_CHECKED(Object, value, 1); if (!obj->IsJSValue()) return value; JSValue::cast(obj)->set_value(value); return value; } RUNTIME_FUNCTION(RuntimeReference_DateField) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(Object, obj, 0); CONVERT_SMI_ARG_CHECKED(index, 1); if (!obj->IsJSDate()) { HandleScope scope(isolate); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError("not_date_object", HandleVector<Object>(NULL, 0))); } JSDate* date = JSDate::cast(obj); if (index == 0) return date->value(); return JSDate::GetField(date, Smi::FromInt(index)); } RUNTIME_FUNCTION(RuntimeReference_ObjectEquals) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); CONVERT_ARG_CHECKED(Object, obj1, 0); CONVERT_ARG_CHECKED(Object, obj2, 1); return isolate->heap()->ToBoolean(obj1 == obj2); } RUNTIME_FUNCTION(RuntimeReference_IsObject) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); if (!obj->IsHeapObject()) return isolate->heap()->false_value(); if (obj->IsNull()) return isolate->heap()->true_value(); if (obj->IsUndetectableObject()) return isolate->heap()->false_value(); Map* map = HeapObject::cast(obj)->map(); bool is_non_callable_spec_object = map->instance_type() >= FIRST_NONCALLABLE_SPEC_OBJECT_TYPE && map->instance_type() <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE; return isolate->heap()->ToBoolean(is_non_callable_spec_object); } RUNTIME_FUNCTION(RuntimeReference_IsFunction) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsJSFunction()); } RUNTIME_FUNCTION(RuntimeReference_IsUndetectableObject) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsUndetectableObject()); } RUNTIME_FUNCTION(RuntimeReference_IsSpecObject) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); return isolate->heap()->ToBoolean(obj->IsSpecObject()); } RUNTIME_FUNCTION(RuntimeReference_HasCachedArrayIndex) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); return isolate->heap()->false_value(); } RUNTIME_FUNCTION(RuntimeReference_GetCachedArrayIndex) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(RuntimeReference_FastOneByteArrayJoin) { SealHandleScope shs(isolate); DCHECK(args.length() == 2); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(RuntimeReference_GeneratorNext) { UNREACHABLE(); // Optimization disabled in SetUpGenerators(). return NULL; } RUNTIME_FUNCTION(RuntimeReference_GeneratorThrow) { UNREACHABLE(); // Optimization disabled in SetUpGenerators(). return NULL; } RUNTIME_FUNCTION(RuntimeReference_ClassOf) { SealHandleScope shs(isolate); DCHECK(args.length() == 1); CONVERT_ARG_CHECKED(Object, obj, 0); if (!obj->IsJSReceiver()) return isolate->heap()->null_value(); return JSReceiver::cast(obj)->class_name(); } RUNTIME_FUNCTION(RuntimeReference_GetFromCache) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_SMI_ARG_CHECKED(id, 0); args[0] = isolate->native_context()->jsfunction_result_caches()->get(id); return __RT_impl_Runtime_GetFromCache(args, isolate); } RUNTIME_FUNCTION(RuntimeReference_DebugIsActive) { SealHandleScope shs(isolate); return Smi::FromInt(isolate->debug()->is_active()); } // ---------------------------------------------------------------------------- // Implementation of Runtime #define F(name, number_of_args, result_size) \ { \ Runtime::k##name, Runtime::RUNTIME, #name, FUNCTION_ADDR(Runtime_##name), \ number_of_args, result_size \ } \ , #define I(name, number_of_args, result_size) \ { \ Runtime::kInline##name, Runtime::INLINE, "_" #name, \ FUNCTION_ADDR(RuntimeReference_##name), number_of_args, result_size \ } \ , #define IO(name, number_of_args, result_size) \ { \ Runtime::kInlineOptimized##name, Runtime::INLINE_OPTIMIZED, "_" #name, \ FUNCTION_ADDR(Runtime_##name), number_of_args, result_size \ } \ , static const Runtime::Function kIntrinsicFunctions[] = { RUNTIME_FUNCTION_LIST(F) INLINE_OPTIMIZED_FUNCTION_LIST(F) INLINE_FUNCTION_LIST(I) INLINE_OPTIMIZED_FUNCTION_LIST(IO)}; #undef IO #undef I #undef F void Runtime::InitializeIntrinsicFunctionNames(Isolate* isolate, Handle<NameDictionary> dict) { DCHECK(dict->NumberOfElements() == 0); HandleScope scope(isolate); for (int i = 0; i < kNumFunctions; ++i) { const char* name = kIntrinsicFunctions[i].name; if (name == NULL) continue; Handle<NameDictionary> new_dict = NameDictionary::Add( dict, isolate->factory()->InternalizeUtf8String(name), Handle<Smi>(Smi::FromInt(i), isolate), PropertyDetails(NONE, NORMAL, Representation::None())); // The dictionary does not need to grow. CHECK(new_dict.is_identical_to(dict)); } } const Runtime::Function* Runtime::FunctionForName(Handle<String> name) { Heap* heap = name->GetHeap(); int entry = heap->intrinsic_function_names()->FindEntry(name); if (entry != kNotFound) { Object* smi_index = heap->intrinsic_function_names()->ValueAt(entry); int function_index = Smi::cast(smi_index)->value(); return &(kIntrinsicFunctions[function_index]); } return NULL; } const Runtime::Function* Runtime::FunctionForEntry(Address entry) { for (size_t i = 0; i < arraysize(kIntrinsicFunctions); ++i) { if (entry == kIntrinsicFunctions[i].entry) { return &(kIntrinsicFunctions[i]); } } return NULL; } const Runtime::Function* Runtime::FunctionForId(Runtime::FunctionId id) { return &(kIntrinsicFunctions[static_cast<int>(id)]); } } } // namespace v8::internal
35.460771
80
0.682579
[ "object", "vector", "transform" ]
427fe7f27096b975b09b6f01182851d7d80e24c2
8,547
ipp
C++
Biosphere/Include/bio/biocoenosis/fauna/hipc/Object.ipp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
1
2021-09-10T17:18:51.000Z
2021-09-10T17:18:51.000Z
Biosphere/Include/bio/biocoenosis/fauna/hipc/Object.ipp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
null
null
null
Biosphere/Include/bio/biocoenosis/fauna/hipc/Object.ipp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
null
null
null
namespace bio::hipc { template<u32 CommandId, typename ...Arguments> Result Object::ProcessRequest(Arguments &&...Args) { bool domainmode = (this->IsDomain() || this->IsSubService()); u64 orawsz = 0; RequestData rq; u32 *tls = (u32*)arm::GetThreadLocalStorage(); rq.InRawSize += (alignof(u64) - 1); rq.InRawSize -= (rq.InRawSize % alignof(u64)); u64 magicoff = rq.InRawSize; rq.InRawSize += sizeof(u64); rq.InRawSize += (alignof(u64) - 1); rq.InRawSize -= (rq.InRawSize % alignof(u64)); u64 cmdidoff = rq.InRawSize; rq.InRawSize += sizeof(u64); this->ProcessArgument(rq, 0, Args...); if(domainmode) { orawsz = rq.InRawSize; rq.InRawSize += sizeof(DomainHeader) + (rq.InObjectIds.size() * sizeof(u32)); } *tls++ = (4 | (rq.InStaticBuffers.size() << 16) | (rq.InBuffers.size() << 20) | (rq.OutBuffers.size() << 24) | (rq.ExchangeBuffers.size() << 28)); u32 *fillsz = tls; if(rq.OutStaticBuffers.size() > 0) *tls = ((rq.OutStaticBuffers.size() + 2) << 10); else *tls = 0; if(rq.InProcessId || (!rq.InCopyHandles.empty()) || (!rq.InMoveHandles.empty())) { *tls++ |= 0x80000000; *tls++ = ((!!rq.InProcessId) | (rq.InCopyHandles.size() << 1) | (rq.InMoveHandles.size() << 5)); if(rq.InProcessId) tls += 2; if(!rq.InCopyHandles.empty()) for(u32 i = 0; i < rq.InCopyHandles.size(); i++) *tls++ = rq.InCopyHandles[i]; if(!rq.InMoveHandles.empty()) for(u32 i = 0; i < rq.InMoveHandles.size(); i++) *tls++ = rq.InMoveHandles[i]; } else tls++; if(!rq.InStaticBuffers.empty()) for(u32 i = 0; i < rq.InStaticBuffers.size(); i++, tls += 2) { Buffer ins = rq.InStaticBuffers[i]; BufferSendData *bsd = (BufferSendData*)tls; uintptr_t uptr = (uintptr_t)ins.Data; bsd->Address = uptr; bsd->Packed = (ins.Info.Index | (ins.Size << 16) | (((uptr >> 32) & 15) << 12) | (((uptr >> 36) & 15) << 6)); } if(!rq.InBuffers.empty()) for(u32 i = 0; i < rq.InBuffers.size(); i++, tls += 3) { Buffer in = rq.InBuffers[i]; BufferCommandData *bcd = (BufferCommandData*)tls; bcd->Size = in.Size; uintptr_t uptr = (uintptr_t)in.Data; bcd->Address = uptr; bcd->Packed = (in.Info.Type | (((uptr >> 32) & 15) << 28) | ((uptr >> 36) << 2)); } if(!rq.OutBuffers.empty()) for(u32 i = 0; i < rq.OutBuffers.size(); i++, tls += 3) { Buffer out = rq.OutBuffers[i]; BufferCommandData *bcd = (BufferCommandData*)tls; bcd->Size = out.Size; uintptr_t uptr = (uintptr_t)out.Data; bcd->Address = uptr; bcd->Packed = (out.Info.Type | (((uptr >> 32) & 15) << 28) | ((uptr >> 36) << 2)); } if(!rq.ExchangeBuffers.empty()) for(u32 i = 0; i < rq.ExchangeBuffers.size(); i++, tls += 3) { Buffer ex = rq.ExchangeBuffers[i]; BufferCommandData *bcd = (BufferCommandData*)tls; bcd->Size = ex.Size; uintptr_t uptr = (uintptr_t)ex.Data; bcd->Address = uptr; bcd->Packed = (ex.Info.Type | (((uptr >> 32) & 15) << 28) | ((uptr >> 36) << 2)); } u32 pad = (((16 - (((uintptr_t)tls) & 15)) & 15) / 4); u32 *raw = (u32*)(tls + pad); size_t rawsz = ((rq.InRawSize / 4) + 4); tls += rawsz; u16 *tls16 = (u16*)tls; if(!rq.OutStaticBuffers.empty()) for(u32 i = 0; i < rq.OutStaticBuffers.size(); i++) { Buffer outs = rq.OutStaticBuffers[i]; size_t outssz = (uintptr_t)outs.Size; tls16[i] = ((outssz > 0xffff) ? 0 : outssz); } size_t u16s = (((2 * rq.OutStaticBuffers.size()) + 3) / 4); tls += u16s; rawsz += u16s; *fillsz |= rawsz; if(!rq.OutStaticBuffers.empty()) for(u32 i = 0; i < rq.OutStaticBuffers.size(); i++, tls += 2) { Buffer outs = rq.OutStaticBuffers[i]; BufferReceiveData *brd = (BufferReceiveData*)tls; uintptr_t uptr = (uintptr_t)outs.Data; brd->Address = uptr; brd->Packed = ((uptr >> 32) | (outs.Size << 16)); } void *vraw = (void*)raw; if(domainmode) { DomainHeader *dh = (DomainHeader*)vraw; u32 *ooids = (u32*)(((uintptr_t)vraw) + sizeof(DomainHeader) + orawsz); dh->Type = 1; dh->ObjectIdCount = (u8)rq.InObjectIds.size(); dh->Size = orawsz; dh->ObjectId = this->GetObjectId(); dh->Pad[0] = dh->Pad[1] = 0; if(!rq.InObjectIds.empty()) for(u32 i = 0; i < rq.InObjectIds.size(); i++) ooids[i] = rq.InObjectIds[i]; vraw = (void*)(((uintptr_t)vraw) + sizeof(DomainHeader)); } rq.InRawData = (u8*)vraw; *((u64*)(((u8*)rq.InRawData) + magicoff)) = hipc::SFCI; *((u64*)(((u8*)rq.InRawData) + cmdidoff)) = CommandId; this->ProcessArgument(rq, 2, Args...); Result rc = svc::SendSyncRequest(this->GetHandle()); if(rc.IsFailure()) return rc; u32 *otls = (u32*)arm::GetThreadLocalStorage(); rq.OutRawSize += (alignof(u64) - 1); rq.OutRawSize -= (rq.OutRawSize % alignof(u64)); rq.OutRawSize += sizeof(u64); rq.OutRawSize += (alignof(u64) - 1); rq.OutRawSize -= (rq.OutRawSize % alignof(u64)); u64 resoff = rq.OutRawSize; rq.OutRawSize += sizeof(u64); this->ProcessArgument(rq, 3, Args...); u32 ctrl0 = *otls++; u32 ctrl1 = *otls++; if(ctrl1 & 0x80000000) { u32 ctrl2 = *otls++; if(ctrl2 & 1) { u64 pid = *otls++; pid |= (((u64)(*otls++)) << 32); rq.OutProcessId = pid; } size_t ohcopy = ((ctrl2 >> 1) & 15); size_t ohmove = ((ctrl2 >> 5) & 15); size_t oh = (ohcopy + ohmove); u32 *aftoh = (otls + oh); if(oh > 8) oh = 8; if(oh > 0) { rq.OutHandles.reserve(oh); for(u32 i = 0; i < oh; i++) { u32 hdl = *(otls + i); rq.OutHandles.push_back(hdl); } } otls = aftoh; } this->ProcessArgument(rq, 4, Args...); size_t nst = ((ctrl0 >> 16) & 15); u32 *aftst = otls + (nst * 2); if(nst > 8) nst = 8; if(nst > 0) for(u32 i = 0; i < nst; i++, otls += 2) { BufferSendData *bsd = (BufferSendData*)otls; BIO_IGNORE(bsd); } otls = aftst; size_t bsend = ((ctrl0 >> 20) & 15); size_t brecv = ((ctrl0 >> 24) & 15); size_t bexch = ((ctrl0 >> 28) & 15); size_t bnum = bsend + brecv + bexch; void *ovraw = (void*)(((uintptr_t)(otls + (bnum * 3)) + 15) &~ 15); if(bnum > 8) bnum = 8; if(bnum > 0) for(u32 i = 0; i < bnum; i++, otls += 3) { BufferCommandData *bcd = (BufferCommandData*)otls; BIO_IGNORE(bcd); } if(domainmode) { DomainResponse *dr = (DomainResponse*)ovraw; u32 *ooids = (u32*)(((uintptr_t)ovraw) + sizeof(DomainResponse) + rq.OutRawSize); u32 ooidcount = dr->ObjectIdCount; if(ooidcount > 8) ooidcount = 8; if(ooidcount > 0) { rq.OutObjectIds.reserve(ooidcount); for(u32 i = 0; i < ooidcount; i++) rq.OutObjectIds.push_back(ooids[i]); } ovraw = (void*)(((uintptr_t)ovraw) + sizeof(DomainResponse)); } rq.OutRawData = (u8*)ovraw; this->ProcessArgument(rq, 5, Args...); rc = (u32)(*((u64*)(((u8*)rq.OutRawData) + resoff))); return rc; } template<typename Argument> void Object::ProcessArgument(RequestData &Data, u8 Part, Argument &&Arg) { Arg.Process(Data, Part); } template<typename Argument, typename ...Arguments> void Object::ProcessArgument(RequestData &Data, u8 Part, Argument &&Arg, Arguments &&...Args) { this->ProcessArgument(Data, Part, Arg); this->ProcessArgument(Data, Part, Args...); } }
42.311881
154
0.49491
[ "object" ]
4284cab2c38d9ff044480cffe6f1eab435906608
2,044
cpp
C++
main.cpp
kmmax/HostInfo
d7bfdbac3ba297e678c3e24b483533e8820bf41e
[ "MIT" ]
null
null
null
main.cpp
kmmax/HostInfo
d7bfdbac3ba297e678c3e24b483533e8820bf41e
[ "MIT" ]
null
null
null
main.cpp
kmmax/HostInfo
d7bfdbac3ba297e678c3e24b483533e8820bf41e
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "transparant.h" #include <QApplication> #include <QScreen> #include <QDebug> #include <QLabel> #include <QSysInfo> #include <QHostInfo> #include <QNetworkInterface> #include <QTextEdit> #include <QFontMetrics> #include <algorithm> int main(int argc, char *argv[]) { QApplication a(argc, argv); // MainWindow w; // w.show(); QScreen *screen = QApplication::primaryScreen(); QRect rect = screen->geometry(); int width = rect.width(); int height = rect.height(); QLabel label("???"); label.setStyleSheet("QLabel {color: yellow; font-size:100px;}"); label.setWindowFlags(Qt::Tool | Qt::FramelessWindowHint); label.setAttribute(Qt::WA_TranslucentBackground); label.setWindowFlag(Qt::WindowStaysOnBottomHint); // int posX = rect.x(); // int posY = rect.y(); label.move(width/2 - label.width()/2, height/5); label.setText(QSysInfo::machineHostName()); label.setScreen(screen); label.show(); QFontMetrics fm(label.font()); int pixelsWide = fm.horizontalAdvance(label.text()); int pixelsHigh = fm.height(); qDebug() << pixelsWide; qDebug() << pixelsHigh; label.resize(pixelsWide, pixelsHigh); label.move(width/2 - label.width()/2, height/5); qDebug() << "----------"; qDebug() << QHostInfo::localHostName(); qDebug() << QHostInfo::localDomainName(); QString msg; QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces(); for (auto &interface: interfaces) { qDebug() << interface.name(); msg += interface.name() + "\n"; QList<QHostAddress> addresses = interface.allAddresses(); for (auto &address: addresses) { if (QAbstractSocket::IPv4Protocol == address.protocol()) { qDebug() << "\t" << address.toString() << ": " << address.protocol(); } } } // QTextEdit *edit = new QTextEdit(); // edit->setReadOnly(true); // edit->setText(msg); // edit->show(); return a.exec(); }
27.621622
86
0.624755
[ "geometry" ]
428c727b286b872fbbc5fee508d5ed319c6b25b0
1,216
cpp
C++
ElectruxShorthandInterpretedLanguage/src/LineTypeHandler/ModuleLoader.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
6
2019-08-29T23:31:17.000Z
2021-11-14T20:35:47.000Z
ElectruxShorthandInterpretedLanguage/src/LineTypeHandler/ModuleLoader.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
null
null
null
ElectruxShorthandInterpretedLanguage/src/LineTypeHandler/ModuleLoader.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
1
2019-09-01T12:22:58.000Z
2019-09-01T12:22:58.000Z
#include <iostream> #include <string> #include <vector> #include <fstream> #include "../../include/Errors.hpp" #include "../../include/DataTypes.hpp" #include "../../include/Executor.hpp" #include "../../include/Lexer.hpp" #include "../../include/LineTypeHandler/ModuleLoader.hpp" ErrorTypes LoadModule( const std::vector< DataType::Data > & dataline ) { if( dataline.size() < 3 ) { std::cerr << "Error on line: " << dataline[ 0 ].fileline << ": Module loading requires a name!" << std::endl; return SYNTAX_ERROR; } std::fstream file; file.open( dataline[ 2 ].word + ".emod", std::ios::in ); if( !file ) { std::cerr << "Error on line: " << dataline[ 0 ].fileline << ": No module named: " << dataline[ 2 ].word << std::endl; return ENTITY_NOT_FOUND; } std::string line; std::vector< std::vector< DataType::Data > > alldata; int fileline = 1; while( std::getline( file, line ) ) { if( line.empty() || line == "\n" ) { ++fileline; continue; } auto dataline = Lexer::ParseLexicoSymbols( line, fileline ); if( !dataline.empty() ) alldata.push_back( dataline ); ++fileline; } file.close(); std::cout << "\n\nExecuting...\n\n"; ExecuteAll( alldata ); return SUCCESS; }
23.384615
119
0.627467
[ "vector" ]
428e36f614eb9aa41bfffc18858a9fc12976ce1d
2,426
cpp
C++
Source/Dynamics/RigidBody/RigidDebugInfoModule.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/RigidDebugInfoModule.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/RigidDebugInfoModule.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
#include "RigidDebugInfoModule.h" #include "RigidBodyRoot.h" #include <iostream> namespace PhysIKA { IMPLEMENT_CLASS(RigidDebugInfoModule) bool RigidDebugInfoModule::execute() { RigidBodyRoot<DataType3f>* root = static_cast<RigidBodyRoot<DataType3f>*>(this->getParent()); const std::vector<std::pair<int, RigidBody2_ptr>>& all_nodes = root->getAllParentidNodePair(); SystemMotionState& state = *(root->getSystemState()->m_motionState); float eng = 0.0; SpatialVector<float> mom; std::vector<SpatialVector<float>> all_v(all_nodes.size()); for (int i = 0; i < all_nodes.size(); ++i) { int parent_id = all_nodes[i].first; RigidBody2_ptr cur_node = all_nodes[i].second; Joint* cur_joint = cur_node->getParentJoint(); /// Transformation from world to node. Transform3d<float> Xo(state.globalPosition[i] - Vector3f(0, 12, 0), state.globalRotation[i].getConjugate()); /// Transformation from predecessor to successor. Transform3d<float>& Xup = state.m_X[i]; /// global velocity in node frame. if (parent_id >= 0) { all_v[i] = state.m_v[i] + Xup.transformM(all_v[parent_id]); } else { all_v[i] = state.m_v[i]; } /// Momemtum of current node, expressed in world frame. SpatialVector<float> cur_mom; cur_mom = Xo.inverseTransform().transformF(cur_node->getI() * all_v[i]); /// Kinetic energy of current node. float cur_kin; cur_kin = Xo.inverseTransform().transformM(all_v[i]) * cur_mom * 0.5; /// Potential energy of current node. float cur_pot; cur_pot = root->getGravity().dot(state.globalPosition[i]) * (cur_node->getI().getMass() * (-1)); /// Total momemtum mom = mom + cur_mom; /// Total energy eng = eng + cur_kin + cur_pot; } //std::cout << "[**] dq"; //for (int i = 0; i < state.m_dq.size(); ++i) //{ // std::cout << " " << state.m_dq[i]; //} //std::cout << std::endl; std::cout << "MOMEMTUM: " << mom[0] << " " << mom[1] << " " << mom[2] << " " << mom[3] << " " << mom[4] << " " << mom[5] << std::endl; std::cout << "ENERGY: " << eng << std::endl; return true; } } // namespace PhysIKA
33.694444
144
0.556472
[ "vector" ]
428f6aa8fd16f5203d258acd8ac03296ed4f0152
4,293
hpp
C++
header/p6_move_bar.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
header/p6_move_bar.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
header/p6_move_bar.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
/* This software is distributed under MIT License, which means: - Do whatever you want - Please keep this notice and include the license file to your project - I provide no warranty Created by Kyrylo Sovailo (github.com/Meta-chan, k.sovailo@gmail.com) Reinventing bicycles since 2020 */ #ifndef P6_MOVE_BAR #define P6_MOVE_BAR #include "p6_common.hpp" #include <wx/wx.h> #include <vector> namespace p6 { class Frame; ///Force bar is used to move many nodes and forces at one time, one of possible contents of side bar class MoveBar { private: Frame *_frame; ///<Application's window wxStaticText *_anchor_x_static; ///<Text explaining anchor's X coordinate edit box wxTextCtrl *_anchor_x_text; ///<Anchor's X coordinate edit box wxStaticText *_anchor_y_static; ///<Text explaining anchor's Y coordinate edit box wxTextCtrl *_anchor_y_text; ///<Anchor's Y coordinate edit box wxStaticText *_scale_static; ///<Text explaining scale rate edit box wxTextCtrl *_scale_text; ///<Scale rate edit box wxStaticText *_angle_static; ///<Text explaining rotation angle edit box wxTextCtrl *_angle_text; ///<Rotation angle (in grad) edit box wxStaticText *_shift_x_static; ///<Text explaining horizontal shift edit box wxTextCtrl *_shift_x_text; ///<Horizontal shift edit box wxStaticText *_shift_y_static; ///<Text explaining vertical shift edit box wxTextCtrl *_shift_y_text; ///<Vertical shift edit box wxCheckBox *_allowed_shift; ///<Check box that decides if mouse is allowed to shift selection wxCheckBox *_allowed_scale; ///<Check box that decides if mouse is allowed to scale selection wxCheckBox *_allowed_rotate; ///<Check box that decides if mouse is allowed to rotate selection Coord _shift; ///<Shift real _scale; ///<Scale rate real _angle; ///<Rotation angle (in rad) Coord _old_shift; ///<Old shift when being shifted real _old_scale; ///<Old scale rate when being scaled real _old_angle; ///<Old angle when being rotated Coord _initial_anchor; ///<Anchor's initial (without shift) position Coord _drag_begin; ///<Begin point of dragging (in reals, unlike MainPanel) std::vector<Coord> _initial_node_coords; ///<Selected node's initial coordinates std::vector<Coord> _initial_force_directions; ///<Selected force's initial directions void _on_anchor_x(wxCommandEvent &e); ///<Handles text input in anchor's X coordinate edit box, changes anchor's X coordinate, resets scale rate and angle void _on_anchor_y(wxCommandEvent &e); ///<Handles text input in anchor's Y coordinate edit box, changes anchor's Y coordinate, resets scale rate and angle void _on_scale(wxCommandEvent &e); ///<Handles text input in scale rate edit box, changes scale rate void _on_angle(wxCommandEvent &e); ///<Handles text input in rotation angle edit box, changes rotation angle void _on_shift_x(wxCommandEvent &e); ///<Handles text input in horizontal shift edit box, changes horizontal shift void _on_shift_y(wxCommandEvent &e); ///<Handles text input in vertical shift edit box, changes vertical shift void _on_allowed_shift(wxCommandEvent &e); ///<Handles checking "shifting allowed" box void _on_allowed_scale(wxCommandEvent &e); ///<Handles checking "scaling allowed" box void _on_allowed_rotate(wxCommandEvent &e); ///<Handles checking "rotation allowed" box void _refresh_scale_angle() noexcept; ///<Sets scale rate to one and angle to zero void _refresh_construction() noexcept; ///<Calculates coordinates of selected nodes and directions of selected forces public: MoveBar(Frame *frame) noexcept; ///<Creates move bar Coord anchor() const noexcept; ///<Returns coordinates of anchor void set_anchor(wxPoint point) noexcept; ///<Sets coordinates of anchor void drag_begin(wxPoint point) noexcept; ///<Begins dragging by mouse void drag_continue(wxPoint point) noexcept; ///<Processes dragging by mouse void show() noexcept; ///<Adds bar's components to side bar void refresh() noexcept; ///<Refreshes initial coordinates and directions void hide() noexcept; ///<Removes bar's components from side bar }; } #endif
55.753247
157
0.728162
[ "vector" ]
429f2f0efbf378a6ef94364cfcf3d03dfcaa6f99
1,325
cpp
C++
URI/1266/code.cpp
fspaniol/Competitive-Programming
5ebd53c9d966750800e16f74273b194c04bb7f70
[ "MIT" ]
null
null
null
URI/1266/code.cpp
fspaniol/Competitive-Programming
5ebd53c9d966750800e16f74273b194c04bb7f70
[ "MIT" ]
null
null
null
URI/1266/code.cpp
fspaniol/Competitive-Programming
5ebd53c9d966750800e16f74273b194c04bb7f70
[ "MIT" ]
null
null
null
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int val, postes, cont; while (cin >> postes && postes != 0) { cont = 0; vector<int> cerca; while (postes--) { cin >> val; cerca.push_back(val); } // preenche lugar onde tem 3 vazios seguidos for (int i = 1; i < cerca.size(); i++) { if (cerca[i] == 0 && cerca[(i+1) % cerca.size()] == 0 && cerca[i-1] == 0) { //cout << i << endl; cerca[i] = 1; cont++; i++; } } // preenche o restante for (int i = 0; i < cerca.size(); i++) { if (cerca[i] == 0 && cerca[(i+1) % cerca.size()] == 0) { //cout << i << endl; cerca[i] = 1; cont++; } } cout << cont << endl; } return 0; }
21.721311
87
0.464151
[ "vector" ]
42ac4849437f7955796a9e8f695d16ee7a67ca94
4,803
hpp
C++
thirdparty/antlr/cpp/antlr3memory.hpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
1
2020-05-05T14:11:05.000Z
2020-05-05T14:11:05.000Z
thirdparty/antlr/cpp/antlr3memory.hpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
3
2020-03-23T09:16:47.000Z
2020-10-13T20:41:59.000Z
thirdparty/antlr/cpp/antlr3memory.hpp
RuslanKorshunov/sc-machine
8cb79a818d4e4144843b26722ac67bd71515ddaf
[ "MIT" ]
23
2015-04-18T15:11:56.000Z
2021-12-21T14:43:22.000Z
#ifndef _ANTLR3MEMORY_HPP #define _ANTLR3MEMORY_HPP // [The "BSD licence"] // Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <string.h> #include <deque> #include <map> #include <new> #include <set> #include <vector> #include "antlr3defs.hpp" ANTLR_BEGIN_NAMESPACE() class DefaultAllocPolicy { public: //limitation of c++. unable to write a typedef template <class TYPE> class AllocatorType : public std::allocator<TYPE> { public: typedef TYPE value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; template<class U> struct rebind { typedef AllocatorType<U> other; }; AllocatorType() throw() {} AllocatorType( const AllocatorType& alloc ) throw() {} template<typename U> AllocatorType(const AllocatorType<U>& alloc) throw(){} }; template<class TYPE> class VectorType : public std::vector< TYPE, AllocatorType<TYPE> > { }; template<class TYPE> class ListType : public std::deque< TYPE, AllocatorType<TYPE> > { }; template<class TYPE> class StackType : public std::deque< TYPE, AllocatorType<TYPE> > { public: void push( const TYPE& elem ) { this->push_back(elem); } void pop() { this->pop_back(); } TYPE& peek() { return this->back(); } TYPE& top() { return this->back(); } const TYPE& peek() const { return this->back(); } const TYPE& top() const { return this->back(); } }; template<class TYPE> class OrderedSetType : public std::set< TYPE, std::less<TYPE>, AllocatorType<TYPE> > { }; template<class TYPE> class UnOrderedSetType : public std::set< TYPE, std::less<TYPE>, AllocatorType<TYPE> > { }; template<class KeyType, class ValueType> class UnOrderedMapType : public std::map< KeyType, ValueType, std::less<KeyType>, AllocatorType<std::pair<const KeyType, ValueType> > > { }; template<class KeyType, class ValueType> class OrderedMapType : public std::map< KeyType, ValueType, std::less<KeyType>, AllocatorType<std::pair<KeyType, ValueType> > > { }; ANTLR_INLINE static void* operator new (std::size_t bytes) { void* p = alloc(bytes); return p; } ANTLR_INLINE static void* operator new (std::size_t , void* p) { return p; } ANTLR_INLINE static void* operator new[]( std::size_t bytes) { void* p = alloc(bytes); return p; } ANTLR_INLINE static void operator delete(void* p) { DefaultAllocPolicy::free(p); } ANTLR_INLINE static void operator delete(void* , void* ) {} //placement delete ANTLR_INLINE static void operator delete[](void* p) { DefaultAllocPolicy::free(p); } ANTLR_INLINE static void* alloc( std::size_t bytes ) { void* p = malloc(bytes); if( p== NULL ) throw std::bad_alloc(); return p; } ANTLR_INLINE static void* alloc0( std::size_t bytes ) { void* p = calloc(1, bytes); if( p== NULL ) throw std::bad_alloc(); return p; } ANTLR_INLINE static void free( void* p ) { return ::free(p); } ANTLR_INLINE static void* realloc(void *ptr, size_t size) { return ::realloc( ptr, size ); } }; ANTLR_END_NAMESPACE() #endif /* _ANTLR3MEMORY_H */
29.109091
88
0.689985
[ "vector" ]
42b194e6a247160d4453ecf7a7f6558e3de79ef9
958
hpp
C++
include/mango/image/quantize.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
3
2021-02-27T10:29:37.000Z
2022-02-16T16:31:26.000Z
include/mango/image/quantize.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
null
null
null
include/mango/image/quantize.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
5
2021-03-22T11:06:00.000Z
2022-02-22T02:53:19.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include <mango/image/format.hpp> #include <mango/image/surface.hpp> namespace mango::image { class ColorQuantizer { protected: enum { NETSIZE = 256 }; Palette m_palette; int m_network[NETSIZE][4]; int m_netindex[NETSIZE]; public: ColorQuantizer(const Surface& source, float quality = 0.90f); ColorQuantizer(const Palette& palette); ~ColorQuantizer(); // get generated palette Palette getPalette() const; // quantize ANY image with the quantization network (the original color image is recommended) void quantize(const Surface& dest, const Surface& source, bool dithering = true); protected: void buildIndex(); int getIndex(int r, int g, int b) const; }; } // namespace mango::image
24.564103
101
0.649269
[ "3d" ]
42b5f1243b2c01517020550c36d788522299cc19
2,977
hpp
C++
include/HMUI/ITableCellOwner.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HMUI/ITableCellOwner.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HMUI/ITableCellOwner.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: HMUI namespace HMUI { // Forward declaring type: TableViewSelectionType struct TableViewSelectionType; } // Completed forward declares // Type namespace: HMUI namespace HMUI { // Forward declaring type: ITableCellOwner class ITableCellOwner; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::HMUI::ITableCellOwner); DEFINE_IL2CPP_ARG_TYPE(::HMUI::ITableCellOwner*, "HMUI", "ITableCellOwner"); // Type namespace: HMUI namespace HMUI { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: HMUI.ITableCellOwner // [TokenAttribute] Offset: FFFFFFFF class ITableCellOwner { public: // public HMUI.TableViewSelectionType get_selectionType() // Offset: 0xFFFFFFFFFFFFFFFF ::HMUI::TableViewSelectionType get_selectionType(); // public System.Boolean get_canSelectSelectedCell() // Offset: 0xFFFFFFFFFFFFFFFF bool get_canSelectSelectedCell(); // public System.Int32 get_numberOfCells() // Offset: 0xFFFFFFFFFFFFFFFF int get_numberOfCells(); }; // HMUI.ITableCellOwner #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: HMUI::ITableCellOwner::get_selectionType // Il2CppName: get_selectionType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::HMUI::TableViewSelectionType (HMUI::ITableCellOwner::*)()>(&HMUI::ITableCellOwner::get_selectionType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HMUI::ITableCellOwner*), "get_selectionType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HMUI::ITableCellOwner::get_canSelectSelectedCell // Il2CppName: get_canSelectSelectedCell template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HMUI::ITableCellOwner::*)()>(&HMUI::ITableCellOwner::get_canSelectSelectedCell)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HMUI::ITableCellOwner*), "get_canSelectSelectedCell", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HMUI::ITableCellOwner::get_numberOfCells // Il2CppName: get_numberOfCells template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (HMUI::ITableCellOwner::*)()>(&HMUI::ITableCellOwner::get_numberOfCells)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HMUI::ITableCellOwner*), "get_numberOfCells", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
43.779412
176
0.723547
[ "vector" ]
42bd94b3542bd10c55a0705304cf2ab2e490490d
28,147
cpp
C++
src/Mesh.cpp
RedFox20/NanoMesh
89e4e74ea793b3c950c8d82ab238ab3c85adf77a
[ "MIT" ]
1
2020-08-13T01:37:32.000Z
2020-08-13T01:37:32.000Z
src/Mesh.cpp
RedFox20/NanoMesh
89e4e74ea793b3c950c8d82ab238ab3c85adf77a
[ "MIT" ]
null
null
null
src/Mesh.cpp
RedFox20/NanoMesh
89e4e74ea793b3c950c8d82ab238ab3c85adf77a
[ "MIT" ]
1
2018-10-18T11:48:35.000Z
2018-10-18T11:48:35.000Z
#include <Nano/Mesh.h> #include <rpp/file_io.h> #include <rpp/sprint.h> #include <rpp/timer.h> #include "InternalConfig.h" namespace Nano { using namespace rpp::literals; /////////////////////////////////////////////////////////////////////////////////////////////// bool VertexDescr::operator==(const VertexDescr& vd) const { return v == vd.v && t == vd.t && n == vd.n && c == vd.c; } bool VertexDescr::operator!=(const VertexDescr& vd) const { return v != vd.v || t != vd.t || n != vd.n || c != vd.c; } bool Triangle::ContainsVertexId(int vertexId) const { return a.v == vertexId || b.v == vertexId || c.v == vertexId; } bool Triangle::operator==(const Triangle& t) const { return a == t.a && b == t.b && c == t.c; } bool Triangle::operator!=(const Triangle& t) const { return a != t.a || b != t.b || c != t.c; } std::string to_string(const Triangle& triangle) { rpp::string_buffer sb; sb.writef("{%d,%d,%d}", triangle.a.v, triangle.b.v, triangle.c.v); return sb.str(); } rpp::Vector3 PickedTriangle::center() const { Assert(good(), "Invalid PickedTriangle"); rpp::Vector3 c = group->Vertex(face->a); c += group->Vertex(face->b); c += group->Vertex(face->c); c /= 3; return c; } rpp::Vector3 PickedTriangle::vertex(const VertexDescr& vd) const { Assert(good(), "Invalid PickedTriangle"); Assert(vd.v != -1 && vd.v < group->NumVerts(), "Invalid VertexDescr: %d / %d", vd.v, group->NumVerts()); return group->VertexData()[vd.v]; } int PickedTriangle::id() const { if (!group || !face) return -1; const Triangle* faces = group->Tris.data(); size_t count = group->Tris.size(); for (size_t i = 0; i < count; ++i) if (faces + i == face) return int(i); return -1; } std::string to_string(const PickedTriangle& triangle) { rpp::string_buffer sb; sb.write('{'); sb.write(triangle.group?triangle.group->GroupId:-1); sb.write(','); if (triangle.face) sb.write(*triangle.face); else sb.write(-1); sb.write('}'); return sb.str(); } /////////////////////////////////////////////////////////////////////////////////////////////// void MeshGroup::Clear() { Verts.clear(); Coords.clear(); Normals.clear(); Colors.clear(); Weights.clear(); BlendIndices.clear(); BlendWeights.clear(); Tris.clear(); CoordsMapping = MapMode::None; NormalsMapping = MapMode::None; ColorMapping = MapMode::None; BlendMapping = MapMode::None; } Material& MeshGroup::CreateMaterial(std::string name) { Mat = std::make_shared<Material>(); Mat->Name = move(name); return *Mat; } void MeshGroup::SetFaceWinding(FaceWinding winding) noexcept { if (Winding == winding) return; for (Triangle& tri : Tris) { // 0 1 2 --> 0 2 1 std::swap(tri.b, tri.c); } Winding = winding; } void MeshGroup::SetCoordSys(CoordSys targetSystem) noexcept { if (System == targetSystem) return; auto isBilateralMatch = [=](CoordSys a, CoordSys b) { return (System == a && targetSystem == b) || (System == b && targetSystem == a); }; if (isBilateralMatch(CoordSys::GL, CoordSys::Unity)) { for (rpp::Vector3& v : Verts) v.x = -v.x; for (rpp::Vector3& n : Normals) n.x = -n.x; } System = targetSystem; } void MeshGroup::UpdateNormal(const VertexDescr& vd0, const VertexDescr& vd1, const VertexDescr& vd2, const bool checkDuplicateVerts) noexcept { auto* verts = Verts.data(); auto* normals = Normals.data(); const rpp::Vector3& v0 = verts[vd0.v]; const rpp::Vector3& v1 = verts[vd1.v]; const rpp::Vector3& v2 = verts[vd2.v]; // calculate triangle normal: rpp::Vector3 ba = v1 - v0; rpp::Vector3 ca = v2 - v0; rpp::Vector3 normal = ba.cross(ca); if (!checkDuplicateVerts) { // apply normal directly to indexed normals, no exhaustive matching Assert(vd0.n != -1 && vd1.n != -1 && vd2.n != -1, "Invalid vertex normals: %d, %d, %d", vd0.n, vd1.n, vd2.n); normals[vd0.n] += normal; normals[vd1.n] += normal; normals[vd2.n] += normal; } else { // add normals to any vertex that shares v0/v1/v2 coordinates // an unoptimized Mesh may have multiple vertices occupying the same XYZ position for (const Triangle& f : Tris) { for (const VertexDescr& vd : f) { const rpp::Vector3& v = verts[vd.v]; if (v == v0 || v == v1 || v == v2) { Assert(vd.n != -1, "Invalid vertex normalId -1"); normals[vd.n] += normal; } } } } } void MeshGroup::RecalculateNormals(const bool checkDuplicateVerts) noexcept { for (rpp::Vector3& normal : Normals) normal = rpp::Vector3::Zero(); FaceWinding winding = Winding; // normals are calculated for each tri: for (const Triangle& tri : Tris) { if (winding == FaceWinding::CCW) { UpdateNormal(tri.a, tri.b, tri.c, checkDuplicateVerts); } else { UpdateNormal(tri.c, tri.b, tri.a, checkDuplicateVerts); } } for (rpp::Vector3& normal : Normals) normal.normalize(); } rpp::Vector3 MeshGroup::GetNormalForSelection(const std::vector<WeightId>& selection) const noexcept { rpp::Vector3 normal = rpp::Vector3::Zero(); if (selection.empty() || NormalsMapping != MapMode::PerVertex) return normal; const rpp::Vector3* normals = NormalData(); for (WeightId wid : selection) { normal += normals[wid.ID]; } normal.normalize(); return normal; } void MeshGroup::InvertNormals() noexcept { for (rpp::Vector3& normal : Normals) normal = -normal; } void MeshGroup::FlattenFaceData() noexcept { // Flatten the mesh, so each Triangle Vertex is unique auto* meshVerts = Verts.data(); auto* meshCoords = Coords.data(); auto* meshNormals = Normals.data(); auto* meshColors = Colors.data(); size_t count = Tris.size() * 3u; std::vector<rpp::Vector3> verts; verts.reserve(count); std::vector<rpp::Vector2> coords; if (!Coords.empty()) coords.reserve(count); std::vector<rpp::Vector3> normals; if (!Normals.empty()) normals.reserve(count); std::vector<rpp::Color3> colors; if (!Colors.empty()) colors.reserve(count); int vertexId = 0, coordId = 0, normalId = 0, colorId = 0; for (Triangle& f : Tris) { for (VertexDescr& vd : f) { if (vd.v != -1) { verts.push_back(meshVerts[vd.v]); vd.v = vertexId++; // set new vertex Id's on the fly } if (vd.t != -1) { coords.push_back(meshCoords[vd.t]); vd.t = coordId++; } if (vd.n != -1) { normals.push_back(meshNormals[vd.n]); vd.n = normalId++; } if (vd.c != -1) { colors.push_back(meshColors[vd.c]); vd.c = colorId++; } } } Verts = move(verts); Coords = move(coords); Normals = move(normals); Colors = move(colors); CoordsMapping = Coords.empty() ? MapMode::None : MapMode::PerFaceVertex; NormalsMapping = Normals.empty() ? MapMode::None : MapMode::PerFaceVertex; ColorMapping = Colors.empty() ? MapMode::None : MapMode::PerFaceVertex; } void MeshGroup::SetVertexColor(int vertexId, const rpp::Color3& vertexColor) noexcept { Assert(vertexId < NumVerts(), "Invalid vertexId %d >= numVerts(%d)", vertexId, NumVerts()); if (Colors.empty()) { Colors.resize(Verts.size()); ColorMapping = MapMode::PerVertex; } Colors[vertexId] = vertexColor; } void MeshGroup::AddMeshData(const MeshGroup& group, rpp::Vector3 offset) noexcept { const int numVertsOld = (int)Verts.size(); const int numCoordsOld = (int)Coords.size(); const int numNormalsOld = (int)Normals.size(); const int numTrisOld = (int)Tris.size(); append(Verts, group.Verts); if (offset != rpp::Vector3::Zero()) { for (int i = numVertsOld, count = (int)Verts.size(); i < count; ++i) Verts[i] += offset; } append(Coords, group.Coords); append(Normals, group.Normals); // Colors are optional, but since it's a flatmap, we need to resize as appropriate if (!Colors.empty() || !group.Colors.empty()) { if (group.Colors.empty()) { Colors.resize(Verts.size()); } else { Colors.resize(size_t(numVertsOld)); append(Colors, group.Colors); } ColorMapping = MapMode::PerVertex; } rpp::append(Tris, group.Tris); for (int i = numTrisOld, numTris = (int)Tris.size(); i < numTris; ++i) { Triangle& face = Tris[i]; for (VertexDescr& vd : face) { vd.v += numVertsOld; if (vd.t != -1) vd.t += numCoordsOld; if (vd.n != -1) vd.n += numNormalsOld; if (vd.c != -1) vd.c += numVertsOld; } } } void MeshGroup::CreateGameVertexData(std::vector<BasicVertex>& vertices, std::vector<int>& indices) const noexcept { auto* meshVerts = Verts.data(); auto* meshCoords = Coords.data(); auto* meshNormals = Normals.data(); vertices.reserve(Tris.size() * 3u); indices.reserve(Tris.size() * 3u); int vertexId = 0; const auto addVertex = [&](const VertexDescr& vd) { indices.push_back(vertexId++); vertices.emplace_back<BasicVertex>({ vd.v != -1 ? meshVerts[vd.v] : rpp::Vector3::Zero(), vd.t != -1 ? meshCoords[vd.t] : rpp::Vector2::Zero(), vd.n != -1 ? meshNormals[vd.n] : rpp::Vector3::Zero() }); }; for (const Triangle& face : Tris) for (const VertexDescr& vd : face) addVertex(vd); } void MeshGroup::SplitSeamVertices() noexcept { auto canShareVertex = [](const VertexDescr& a, const VertexDescr& b) { return a.t == b.t && a.n == b.n && a.c == b.c; }; std::unordered_multimap<int, VertexDescr> addedVerts; addedVerts.reserve(NumVerts()); auto getExistingVertex = [&](const VertexDescr& old, VertexDescr& out) -> bool { for (auto r = addedVerts.equal_range(old.v); r.first != r.second; ++r.first) { VertexDescr existing = r.first->second; if (canShareVertex(old, existing)) { out = existing; return true; } } return false; }; size_t numTris = Tris.size(); auto* oldFaces = Tris.data(); auto* oldVerts = Verts.data(); std::vector<Triangle> faces; faces.resize(numTris); std::vector<rpp::Vector3> verts; verts.reserve(Verts.size()); for (size_t faceId = 0; faceId < numTris; ++faceId) { const Triangle& oldFace = oldFaces[faceId]; Triangle& newFace = faces[faceId]; for (int i = 0; i < 3; ++i) { const VertexDescr& old = oldFace[i]; VertexDescr& result = newFace[i]; if (getExistingVertex(old, result)) continue; // insert new verts.push_back(oldVerts[old.v]); result = { (int)verts.size() - 1, old.t, old.n, old.c }; addedVerts.emplace(old.v, result); } } Verts = move(verts); Tris = move(faces); } void MeshGroup::PerVertexFlatten() noexcept { auto* oldCoords = Coords.empty() ? nullptr : Coords.data(); auto* oldNormals = Normals.empty() ? nullptr : Normals.data(); auto* oldColors = Colors.empty() ? nullptr : Colors.data(); if (!oldCoords && !oldNormals && !oldColors) return; // nothing to do here std::vector<rpp::Vector2> coords; coords.reserve(Verts.size()); std::vector<rpp::Vector3> normals; normals.reserve(Verts.size()); std::vector<rpp::Color3> colors; colors.reserve(Verts.size()); std::vector<bool> added; added.resize(Verts.size()); for (Triangle& face : Tris) { for (VertexDescr& vd : face) { int vertexId = vd.v; if (!added[vertexId]) { added[vertexId] = true; if (oldCoords) coords.push_back(vd.t != -1 ? oldCoords[vd.t] : rpp::Vector2::Zero()); if (oldNormals) normals.push_back(vd.n != -1 ? oldNormals[vd.n] : rpp::Vector3::Zero()); if (oldColors) colors.push_back(vd.c != -1 ? oldColors[vd.c] : rpp::Color3::Zero()); } if (oldCoords) vd.t = vertexId; if (oldNormals) vd.n = vertexId; if (oldColors) vd.c = vertexId; } } if (CoordsMapping != MapMode::None) { CoordsMapping = MapMode::PerVertex; Coords = move(coords); Assert(Coords.size() == Verts.size(), "Coords must match vertices"); } if (NormalsMapping != MapMode::None) { NormalsMapping = MapMode::PerVertex; Normals = move(normals); Assert(Normals.size() == Verts.size(), "Normals must match vertices"); } if (ColorMapping != MapMode::None) { ColorMapping = MapMode::PerVertex; Colors = move(colors); Assert(Colors.size() == Verts.size(), "Colors must match vertices"); } } void MeshGroup::OptimizedFlatten() noexcept { SplitSeamVertices(); PerVertexFlatten(); } void MeshGroup::CreateIndexArray(std::vector<int>& indices) const noexcept { CreateIndexArray(indices, Winding); } void MeshGroup::CreateIndexArray(std::vector<short>& indices) const noexcept { CreateIndexArray(indices, Winding); } void MeshGroup::CreateIndexArray(std::vector<unsigned>& indices) const noexcept { CreateIndexArray(reinterpret_cast<std::vector<int>&>(indices), Winding); } void MeshGroup::CreateIndexArray(std::vector<unsigned short>& indices) const noexcept { CreateIndexArray(reinterpret_cast<std::vector<short>&>(indices), Winding); } void MeshGroup::CreateIndexArray(std::vector<int>& indices, FaceWinding winding) const noexcept { indices.clear(); indices.reserve(Tris.size() * 3u); if (Winding == winding) { for (const Triangle& face : Tris) { indices.push_back(face.a.v); indices.push_back(face.b.v); indices.push_back(face.c.v); } } else // flip the winding, 0 1 2 --> 0 2 1 { for (const Triangle& face : Tris) { indices.push_back(face.a.v); indices.push_back(face.c.v); indices.push_back(face.b.v); } } } void MeshGroup::CreateIndexArray(std::vector<short>& indices, FaceWinding winding) const noexcept { indices.clear(); indices.reserve(Tris.size() * 3u); if (Winding == winding) { for (const Triangle& face : Tris) { indices.push_back((short)face.a.v); indices.push_back((short)face.b.v); indices.push_back((short)face.c.v); } } else // flip the winding, 0 1 2 --> 0 2 1 { for (const Triangle& face : Tris) { indices.push_back((short)face.a.v); indices.push_back((short)face.c.v); indices.push_back((short)face.b.v); } } } PickedTriangle MeshGroup::PickTriangle(const rpp::Ray& ray) const noexcept { const rpp::Vector3* verts = Verts.data(); const Triangle* picked = nullptr; float closestDist = 9999999999999.0f; for (const Triangle& tri : Tris) { const rpp::Vector3& v0 = verts[tri.a.v]; const rpp::Vector3& v1 = verts[tri.b.v]; const rpp::Vector3& v2 = verts[tri.c.v]; float dist = ray.intersectTriangle(v0, v1, v2); if (dist > 0.0f && dist < closestDist) { closestDist = dist; picked = &tri; } } return picked ? PickedTriangle{ this, picked, closestDist } : PickedTriangle{}; } void MeshGroup::Print() const { rpp::string_buffer sb; sb.writef(" group %-28s", Name.c_str()); if (NumVerts()) sb.writef(" %5d verts", NumVerts()); if (NumTris()) sb.writef(" %5d tris", NumTris()); if (NumCoords()) sb.writef(" %5d uvs", NumCoords()); if (NumNormals())sb.writef(" %5d normals", NumNormals()); if (NumColors()) sb.writef(" %5d colors", NumColors()); if (Offset != rpp::Vector3::Zero()) { char buf[48]; sb.writef(" offset:%s", Offset.toString(buf)); } LogInfo("%.*s", sb.size(), sb.data()); } void MeshGroup::PrintVerts(const char* what) const { if (!what) what = Name.c_str(); const int numVerts = NumVerts(); const rpp::Vector3* verts = VertexData(); rpp::string_buffer sb; sb.writef("%s vertices[%d]:", what, numVerts); for (int i = 0; i < numVerts; ++i) { const rpp::Vector3& v = verts[i]; sb.writef("\n [%d] { %.3f, %.3f, %.3f }", i, v.x, v.y, v.z); } LogInfo("%.*s", sb.size(), sb.data()); } /////////////////////////////////////////////////////////////////////////////////////////////// std::string to_string(Options o) { rpp::string_buffer sb; bool prepend = false; auto write_flag = [&](bool flag, rpp::strview what) { if (!flag) return; if (prepend) sb.write('|'); else prepend = true; sb.write(what); }; write_flag(o & Options::SingleGroup, "SingleGroup"); write_flag(o & Options::EmptyGroups, "EmptyGroups"); write_flag(o & Options::NoThrow, "NoThrow"); write_flag(o & Options::Log, "Log"); write_flag(o & Options::SplitSeams, "SplitSeams"); write_flag(o & Options::Flatten, "Flatten"); write_flag(o & Options::ClockWise, "ClockWise"); write_flag(o & Options::Unity, "Unity"); return sb.str(); } /////////////////////////////////////////////////////////////////////////////////////////////// Mesh::Mesh() = default; Mesh::~Mesh() = default; Mesh::Mesh(rpp::strview meshPath, Options options) { Load(meshPath, options); } int Mesh::TotalTris() const { return rpp::sum_all(Groups, &MeshGroup::NumTris); } int Mesh::TotalVerts() const { return rpp::sum_all(Groups, &MeshGroup::NumVerts); } int Mesh::TotalCoords() const { return rpp::sum_all(Groups, &MeshGroup::NumCoords); } int Mesh::TotalNormals() const { return rpp::sum_all(Groups, &MeshGroup::NumNormals); } int Mesh::TotalColors() const { return rpp::sum_all(Groups, &MeshGroup::NumColors); } int Mesh::TotalAnimClips() const { return (int)AnimationClips.size(); } MeshGroup* Mesh::FindGroup(rpp::strview name) { for (auto& group : Groups) if (group.Name == name) return &group; return nullptr; } const MeshGroup* Mesh::FindGroup(rpp::strview name) const { for (auto& group : Groups) if (group.Name == name) return &group; return nullptr; } MeshGroup& Mesh::CreateGroup(std::string name) { return rpp::emplace_back(Groups, (int)Groups.size(), name); } MeshGroup& Mesh::FindOrCreateGroup(rpp::strview name) { if (MeshGroup* group = FindGroup(name)) return *group; return emplace_back(Groups, (int)Groups.size(), name); } std::shared_ptr<Material> Mesh::FindMaterial(rpp::strview name) const { for (const MeshGroup& group : Groups) if (name.equalsi(group.Name)) return group.Mat; return {}; } bool Mesh::HasAnyMaterials() const { for (const MeshGroup& group : Groups) if (group.Mat) return true; return false; } void Mesh::Clear() noexcept { Name.clear(); Groups.clear(); } Mesh Mesh::Clone(bool cloneMaterials) const noexcept { Mesh obj; obj.Name = Name; obj.Groups = Groups; obj.Bones = Bones; obj.SkinnedBones = SkinnedBones; obj.AnimationClips = AnimationClips; if (cloneMaterials) { for (auto& group : obj.Groups) if (group.Mat) group.Mat = std::make_shared<Material>(*group.Mat); } return obj; } bool Mesh::Load(rpp::strview meshPath, Options opt) { //rpp::ScopedPerfTimer perf{ "Nano::Mesh::Load" }; if (opt & Options::Unity) { opt |= Options::SingleGroup | Options::SplitSeams | Options::Flatten | Options::ClockWise; } rpp::strview ext = rpp::file_ext(meshPath); if (ext.equalsi("fbx"_sv)) return LoadFBX(meshPath, opt); if (ext.equalsi("obj"_sv)) return LoadOBJ(meshPath, opt); if (ext.equalsi("txt"_sv)) return LoadTXT(meshPath, opt); NanoErr(opt, "Error: unrecognized mesh format for file '%s'", meshPath); } void Mesh::ApplyLoadOptions(Options opt) { if (opt & Options::SplitSeams) { SplitSeamVertices(); for (MeshGroup& g : Groups) g.SplitSeamVertices(); } if (opt & Options::Flatten) { OptimizedFlatten(); } FaceWinding winding = (opt & Options::ClockWise) ? FaceWinding::CW : FaceWinding::CCW; SetFaceWinding(winding); if (opt & Options::Unity) { SetCoordSys(CoordSys::Unity); } if (opt & Options::Log) { for (MeshGroup& g : Groups) { g.Print(); } if (!(opt & Options::SingleGroup)) { LogInfo("Loaded %-31s %5d verts %5d tris", Name, TotalVerts(), TotalTris()); } } } bool Mesh::SaveAs(rpp::strview meshPath, Options opt) const { //rpp::ScopedPerfTimer perf{ "Nano::Mesh::SaveAs" }; rpp::strview ext = file_ext(meshPath); if (ext.equalsi("fbx"_sv)) return SaveAsFBX(meshPath, opt); if (ext.equalsi("obj"_sv)) return SaveAsOBJ(meshPath, opt); NanoErr(opt, "Error: unrecognized mesh format for file '%s'", meshPath); } /////////////////////////////////////////////////////////////////////////////////////////////// void Mesh::RecalculateNormals(bool checkDuplicateVerts) noexcept { for (MeshGroup& group : Groups) group.RecalculateNormals(checkDuplicateVerts); } void Mesh::InvertNormals() noexcept { for (MeshGroup& group : Groups) group.InvertNormals(); } /////////////////////////////////////////////////////////////////////////////////////////////// void Mesh::AddMeshData(const Mesh& mesh, rpp::Vector3 offset) noexcept { size_t numGroupsOld = Groups.size(); rpp::append(Groups, mesh.Groups); auto oldGroupHasIdenticalName = [=](rpp::strview name) { for (size_t i = 0; i < numGroupsOld; ++i) if (Groups[i].Name == name) return true; return false; }; for (size_t i = numGroupsOld; i < Groups.size(); ++i) { MeshGroup& group = Groups[i]; while (oldGroupHasIdenticalName(group.Name)) group.Name += "_" + std::to_string(numGroupsOld); if (offset != rpp::Vector3::Zero()) { for (rpp::Vector3& vertex : group.Verts) vertex += offset; } } } rpp::BoundingBox Mesh::CalculateBBox() const noexcept { if (Groups.empty()) return {}; rpp::BoundingBox bounds = rpp::BoundingBox::create(Groups.front().Verts); for (size_t i = 1; i < Groups.size(); ++i) bounds.join(rpp::BoundingBox::create(Groups[i].Verts)); return bounds; } void Mesh::SplitSeamVertices() noexcept { for (MeshGroup& g : Groups) g.SplitSeamVertices(); } void Mesh::FlattenMeshData() noexcept { for (MeshGroup& group : Groups) if (!group.IsFlattened()) group.FlattenFaceData(); } bool Mesh::IsFlattened() const noexcept { for (const MeshGroup& group : Groups) if (!group.IsFlattened()) return false; return true; } void Mesh::OptimizedFlatten() noexcept { for (MeshGroup& group : Groups) group.OptimizedFlatten(); } void Mesh::SetFaceWinding(FaceWinding winding) noexcept { for (MeshGroup& g : Groups) { g.SetFaceWinding(winding); } } void Mesh::SetCoordSys(CoordSys targetSystem) noexcept { for (MeshGroup& g : Groups) { g.SetCoordSys(targetSystem); } } void Mesh::MergeGroups() noexcept { if (Groups.size() <= 1u) return; auto& merged = Groups.front(); while (Groups.size() > 1) { merged.AddMeshData(Groups.back()); Groups.pop_back(); } } PickedTriangle Mesh::PickTriangle(const rpp::Ray& ray) const noexcept { PickedTriangle closest = {}; for (const MeshGroup& group : Groups) { if (PickedTriangle result = group.PickTriangle(ray)) { if (!closest || result.distance < closest.distance) closest = result; } } return closest; } int Mesh::AddAnimClip(std::string name, float duration) { int id = TotalAnimClips(); AnimationClips.emplace_back(Nano::AnimationClip{ std::move(name), duration }); return id; } /////////////////////////////////////////////////////////////////////////////////////////////// }
32.058087
121
0.508615
[ "mesh", "vector" ]
42c093e6392be89afb0ee95a2c013fa1bef33511
2,403
cpp
C++
LaneDetector/demo.cpp
hitrich/Autonomous_Car_Lane_Det
c4546663e2ac4a922f79aa17ade0994b57d13b58
[ "MIT" ]
null
null
null
LaneDetector/demo.cpp
hitrich/Autonomous_Car_Lane_Det
c4546663e2ac4a922f79aa17ade0994b57d13b58
[ "MIT" ]
null
null
null
LaneDetector/demo.cpp
hitrich/Autonomous_Car_Lane_Det
c4546663e2ac4a922f79aa17ade0994b57d13b58
[ "MIT" ]
null
null
null
#include <opencv2/highgui/highgui.hpp> #include <iostream> #include <string> #include <vector> #include "opencv2/opencv.hpp" #include "../include/LaneDetector.hpp" #include "../LaneDetector/LaneDetector.cpp" /** *@brief Function main that runs the main algorithm of the lane detection. *@brief It will read a video of a car in the highway and it will output the *@brief same video but with the plotted detected lane *@param argv[] is a string to the full path of the demo video *@return flag_plot tells if the demo has sucessfully finished */ int main(int argc, char *argv[]) { if (argc != 2) { std::cout << "Not enough parameters" << std::endl; return -1; } // The input argument is the location of the video std::string source = argv[1]; cv::VideoCapture cap(source); if (!cap.isOpened()) return -1; LaneDetector lanedetector; // Create the class object cv::Mat frame; cv::Mat img_denoise; cv::Mat img_edges; cv::Mat img_mask; cv::Mat img_lines; std::vector<cv::Vec4i> lines; std::vector<std::vector<cv::Vec4i> > left_right_lines; std::vector<cv::Point> lane; std::string turn; int flag_plot = -1; int i = 0; // Main algorithm starts. Iterate through every frame of the video while (i < 540) { // Capture frame if (!cap.read(frame)) break; // Denoise the image using a Gaussian filter img_denoise = lanedetector.deNoise(frame); // Detect edges in the image img_edges = lanedetector.edgeDetector(img_denoise); // Mask the image so that we only get the ROI img_mask = lanedetector.mask(img_edges); // Obtain Hough lines in the cropped image lines = lanedetector.houghLines(img_mask); if (!lines.empty()) { // Separate lines into left and right lines left_right_lines = lanedetector.lineSeparation(lines, img_edges); // Apply regression to obtain only one line for each side of the lane lane = lanedetector.regression(left_right_lines, frame); // Predict the turn by determining the vanishing point of the the lines turn = lanedetector.predictTurn(); // Plot lane detection flag_plot = lanedetector.plotLane(frame, lane, turn); i += 1; cv::waitKey(25); } else { flag_plot = -1; } } return flag_plot; }
30.0375
79
0.648356
[ "object", "vector" ]
42c20878d7b7cbeb46a708038a0439c926510138
17,164
cpp
C++
depositpage/DepositAutomatic.cpp
whitexwc15184/WhitecoinLightWallet
cfc458faa1695d90d2210903425377612113c064
[ "MIT" ]
null
null
null
depositpage/DepositAutomatic.cpp
whitexwc15184/WhitecoinLightWallet
cfc458faa1695d90d2210903425377612113c064
[ "MIT" ]
3
2020-03-16T05:23:24.000Z
2020-03-31T03:29:39.000Z
depositpage/DepositAutomatic.cpp
whitexwc15184/WhitecoinLightWallet
cfc458faa1695d90d2210903425377612113c064
[ "MIT" ]
1
2020-02-16T00:28:39.000Z
2020-02-16T00:28:39.000Z
#include "DepositAutomatic.h" #include "wallet.h" #include <mutex> #include <memory> #include <list> #include <QTimer> #include <QDebug> #include <QJsonArray> #include <QJsonObject> #include <QJsonValue> #include "extra/HttpManager.h" class DepositAutomatic::DataPrivate { public: struct accountInfo { accountInfo() :captialFee(0) ,transactionFinished(false) { } QString accountAddress; QString accountName; QString tunnelAddress; QString assetSymbol; QString assetMultiAddress; QString assetNumber; double captialFee; QJsonObject transactionDetail; bool transactionFinished; }; public: DataPrivate() :autoDeposit(XWCWallet::getInstance()->autoDeposit) ,isInUpdate(false) { } public: bool isInUpdate;//是否处于更新阶段,防止重复更新 bool autoDeposit;//是否自动充值 std::mutex mutexLock;//数据修改锁 std::mutex updateMutexLock;//更新标志锁 std::list<std::shared_ptr<accountInfo>> accounts;//所有账户信息 std::list<QString> assetSymbols;//资产类型 QTimer *timer; HttpManager httpManager;////用于查询通道账户余额 public: //清理空tunnel账户 void clearEmptyTunnel() { accounts.erase(std::remove_if(accounts.begin(),accounts.end(),[](std::shared_ptr<accountInfo> info){ return info->tunnelAddress.isEmpty();}) ,accounts.end()); } //是否已有通道地址 bool findTunel(const QString &tunnel){ for(auto it = accounts.begin();it != accounts.end();++it) { if(!(*it)->tunnelAddress.isEmpty() && tunnel == (*it)->tunnelAddress){ return true; } } return false; } //更新通道账户 void updateTunnel(const QString &accountAddress,const QString &symbol,const QString &tunnelAddress){ std::lock_guard<std::mutex> lockguard(mutexLock); for(auto it = accounts.begin();it != accounts.end();++it){ if(accountAddress == (*it)->accountAddress && symbol==(*it)->assetSymbol){ (*it)->tunnelAddress = tunnelAddress; break; } } } //更新多签地址 void updateMulti(const QString &symbol,const QString &multi){ std::lock_guard<std::mutex> lockguard(mutexLock); for(auto it = accounts.begin();it != accounts.end();++it){ if(symbol == (*it)->assetSymbol){ (*it)->assetMultiAddress = multi; } } } //更新账户余额 void updateMoney(const QString &tunnelAddress,const QString &assetSymbol,const QString &number){ std::lock_guard<std::mutex> lockguard(mutexLock); for(auto it = accounts.begin();it != accounts.end();++it){ if(tunnelAddress == (*it)->tunnelAddress && assetSymbol == (*it)->assetSymbol){ int pre = XWCWallet::getInstance()->assetInfoMap.value(XWCWallet::getInstance()->getAssetId( getRealAssetSymbol( assetSymbol))).precision; (*it)->assetNumber = QString::number(std::max<double>(0,number.toDouble()-(*it)->captialFee) ,'f',pre); //qDebug()<<"update-money---"<<tunnelAddress<<(*it)->assetMultiAddress<<(*it)->assetNumber; if((*it)->assetNumber.toDouble() < 1e-11) { accounts.erase(it); } break; } } } //更新交易详情 void updateDetail(const QString &tunnelAddress,const QJsonObject &obj){ std::lock_guard<std::mutex> lockguard(mutexLock); for(auto it = accounts.begin();it != accounts.end();++it){ if(tunnelAddress == (*it)->tunnelAddress){ (*it)->transactionDetail = obj; qDebug()<<"signsign"<<tunnelAddress<<(*it)->transactionDetail; break; } } } //设置正在更新 void SetInUpdateTrue() { std::lock_guard<std::mutex> lockguard(updateMutexLock); isInUpdate = true; } void SetInUpdateFalse() { std::lock_guard<std::mutex> lockguard(updateMutexLock); isInUpdate = false; } }; DepositAutomatic::DepositAutomatic(QObject *parent) : QObject(parent) ,_p(new DataPrivate()) { _p->timer = new QTimer(this); connect(_p->timer,&QTimer::timeout,this,&DepositAutomatic::autoDeposit); _p->timer->start(30000); connect( XWCWallet::getInstance(), &XWCWallet::jsonDataUpdated, this, &DepositAutomatic::jsonDataUpdated); connect(&_p->httpManager,SIGNAL(httpReplied(QByteArray,int)),this,SLOT(httpReplied(QByteArray,int))); //test //autoDeposit(); } DepositAutomatic::~DepositAutomatic() { delete _p; _p = nullptr; } void DepositAutomatic::autoDeposit() { _p->autoDeposit = XWCWallet::getInstance()->autoDeposit; if(_p->autoDeposit && !_p->isInUpdate && XWCWallet::getInstance()->GetBlockSyncFinish()) { //_p->timer->stop(); updateData(); } } void DepositAutomatic::PostQueryTunnelAddress(const QString &accountName, const QString &symbol) { if(accountName.isEmpty() || symbol.isEmpty()) return; XWCWallet::getInstance()->postRPC( "automatic-get_binding_account-"+accountName, toJsonFormat( "get_binding_account", QJsonArray() << accountName<<symbol )); } void DepositAutomatic::PostQueryMultiAddress(const QString &symbol) { if(symbol.isEmpty()) return; XWCWallet::getInstance()->postRPC( "automatic-get_current_multi_address_"+symbol, toJsonFormat( "get_current_multi_address", QJsonArray() << symbol)); } void DepositAutomatic::PostQueryTunnelMoney(const QString &symbol,const QString &tunnelAddress) { if(symbol.isEmpty() || tunnelAddress.isEmpty()) return; QJsonObject object; object.insert("jsonrpc","2.0"); object.insert("id",45); object.insert("method","Zchain.Address.GetBalance"); QJsonObject paramObject; paramObject.insert("chainId",symbol); paramObject.insert("addr",tunnelAddress); object.insert("params",paramObject); _p->httpManager.post(XWCWallet::getInstance()->middlewarePath,QJsonDocument(object).toJson()); } void DepositAutomatic::PostCreateTransaction(const QString &fromAddress, const QString &toAddress, const QString &number, const QString &symbol) { // for(auto it = _p->accounts.begin();it != _p->accounts.end();++it) // { // qDebug()<<"justbeforetransaction"<<(*it)->tunnelAddress<<(*it)->assetSymbol<<(*it)->assetMultiAddress<<(*it)->assetNumber; // } if(fromAddress.isEmpty() || toAddress.isEmpty() || number.isEmpty() || symbol.isEmpty() || number.toDouble()<1e-10) return; XWCWallet::getInstance()->postRPC( "automatic-createrawtransaction_"+fromAddress, toJsonFormat( "createrawtransaction", QJsonArray() << fromAddress<<toAddress<<number<<symbol )); // qDebug()<<"auto-post-trasaction----"<<toJsonFormat( "createrawtransaction", QJsonArray() // << fromAddress<<toAddress<<number<<symbol ); } void DepositAutomatic::PostSignTrasaction(const QString &fromAddress, const QString &symbol, const QJsonObject &detail) { if(fromAddress.isEmpty() || symbol.isEmpty() || detail.isEmpty()) return; XWCWallet::getInstance()->postRPC( "automatic-signrawtransaction", toJsonFormat( "signrawtransaction", QJsonArray() <<fromAddress<<symbol<<detail<<true )); } void DepositAutomatic::FinishQueryTunnel() { XWCWallet::getInstance()->postRPC( "automatic-finish-tunnel", toJsonFormat( "automatic-finish-tunnel", QJsonArray())); } void DepositAutomatic::FinishQueryMoney() { XWCWallet::getInstance()->postRPC( "automatic-finish-money", toJsonFormat( "automatic-finish-money", QJsonArray())); } void DepositAutomatic::FinishQueryMulti() { XWCWallet::getInstance()->postRPC( "automatic-finish-multi", toJsonFormat( "automatic-finish-multi", QJsonArray())); } void DepositAutomatic::FinishCreateTransaction() { XWCWallet::getInstance()->postRPC( "automatic-finish-transaction", toJsonFormat( "automatic-finish-transaction", QJsonArray())); } void DepositAutomatic::FinishSign() { XWCWallet::getInstance()->postRPC( "automatic-finish-sign", toJsonFormat( "automatic-finish-sign", QJsonArray())); } void DepositAutomatic::jsonDataUpdated(const QString &id) { if(id.startsWith("automatic-get_binding_account-")) { QString result = XWCWallet::getInstance()->jsonDataValue( id); result.prepend("{"); result.append("}"); //提取通道账户地址 ParseTunnel(result); } else if("automatic-finish-tunnel" == id) { //先排除没有tunnel的账户 _p->clearEmptyTunnel(); //qDebug()<<_p->accounts.size(); //开始查找多签地址 std::for_each(_p->assetSymbols.begin(),_p->assetSymbols.end(),[this](const QString &symbol){ this->PostQueryMultiAddress(symbol); }); //结束查找 FinishQueryMulti(); } else if(id.startsWith("automatic-get_current_multi_address_")) { QString result = XWCWallet::getInstance()->jsonDataValue( id); result.prepend("{"); result.append("}"); ParseMutli(result); } else if("automatic-finish-multi" == id) {//开始查找余额 for(auto it = _p->accounts.begin();it != _p->accounts.end();++it) { PostQueryTunnelMoney((*it)->assetSymbol,(*it)->tunnelAddress); } // std::for_each(_p->accounts.begin(),_p->accounts.end(),[this](const std::shared_ptr<DepositAutomatic::DataPrivate::accountInfo>& info){ // this->PostQueryTunnelMoney(info->assetSymbol,info->tunnelAddress); // }); QTimer::singleShot(500,[this](){this->PostQueryTunnelMoney("autofinish","autofinish");}); } else if("automatic-finish-money" == id) {//开始创建交易 std::for_each(_p->accounts.begin(),_p->accounts.end(),[this](const std::shared_ptr<DepositAutomatic::DataPrivate::accountInfo>& info){ this->PostCreateTransaction(info->tunnelAddress,info->assetMultiAddress,info->assetNumber,info->assetSymbol); //qDebug()<<"postdata"<<info->tunnelAddress<<info->assetMultiAddress<<info->assetNumber<<info->assetSymbol; }); //结束交易创建 FinishCreateTransaction(); } else if(id.startsWith("automatic-createrawtransaction_")) { QString address = id.mid(QString("automatic-createrawtransaction_").size()); QString result = XWCWallet::getInstance()->jsonDataValue( id); result.prepend("{"); result.append("}"); ParseTransaction(address,result); // qDebug()<<id<<"-----"<<XWCWallet::getInstance()->jsonDataValue( id); } else if("automatic-finish-transaction" == id) {//进行签名 std::for_each(_p->accounts.begin(),_p->accounts.end(),[this](const std::shared_ptr<DepositAutomatic::DataPrivate::accountInfo>& info){ this->PostSignTrasaction(info->tunnelAddress,info->assetSymbol,info->transactionDetail); }); FinishSign(); } else if("automatic-signrawtransaction" == id) { qDebug()<<id<<"-----"<<XWCWallet::getInstance()->jsonDataValue( id); } else if("automatic-finish-sign" == id) {//结束签名,可以进行刷新 _p->SetInUpdateFalse(); } } void DepositAutomatic::httpReplied(QByteArray _data, int _status) {//解析查询余额的返回,补全账户信息 // qDebug() << "auto--http-- " << _data << _status; if(QString(_data).contains("autofinish")) { //结束查找余额--必须等余额查完了再创建交易--余额的查询很慢 FinishQueryMoney(); for(auto it = _p->accounts.begin();it != _p->accounts.end();++it) { qDebug()<<"justafter--tunnel-money"<<(*it)->tunnelAddress<<(*it)->assetSymbol<<(*it)->assetMultiAddress<<(*it)->assetNumber; } return; } QJsonObject object = QJsonDocument::fromJson(_data).object().value("result").toObject(); QString tunnel = object.value("address").toString(); QString asset = object.value("chainId").toString().toUpper(); QString number = QString::number( jsonValueToDouble(object.value("balance"))); _p->updateMoney(tunnel,asset,number); } void DepositAutomatic::updateData() { std::lock_guard<std::mutex> guard(_p->mutexLock); _p->SetInUpdateTrue(); _p->accounts.clear(); _p->assetSymbols.clear(); _p->autoDeposit = XWCWallet::getInstance()->autoDeposit; QMap<QString,AccountInfo> accountInfoMap = XWCWallet::getInstance()->accountInfoMap; QMap<QString,AssetInfo> assetInfoMap = XWCWallet::getInstance()->assetInfoMap; foreach (AccountInfo info, accountInfoMap) { foreach(AssetInfo assetInfo,assetInfoMap){ if(assetInfo.id != "1.3.0" && assetInfo.symbol != "ETH" && !assetInfo.symbol.startsWith("ERC")) { std::shared_ptr<DataPrivate::accountInfo> da = std::make_shared<DataPrivate::accountInfo>(); da->accountAddress = info.address; da->accountName = info.name; da->assetSymbol = assetInfo.symbol; da->captialFee = static_cast<double>(assetInfo.fee)/std::max<int>(1,static_cast<int>(pow(10,assetInfo.precision))); _p->accounts.push_back(da); } } } foreach(AssetInfo assetInfo,assetInfoMap){ if(assetInfo.id != "1.3.0" && assetInfo.symbol != "ETH" && !assetInfo.symbol.startsWith("ERC")) { _p->assetSymbols.push_back(assetInfo.symbol); } } if(_p->accounts.empty()) { _p->SetInUpdateFalse(); return; } //发送寻找多签地址、以及对应通道地址 for(const auto &in : _p->accounts) { PostQueryTunnelAddress(in->accountName,in->assetSymbol); } FinishQueryTunnel(); } void DepositAutomatic::ParseTunnel(const QString &jsonString) { // qDebug()<< "auto--"<<jsonString; QJsonParseError json_error; QJsonDocument parse_doucment = QJsonDocument::fromJson(jsonString.toLatin1(),&json_error); if(json_error.error != QJsonParseError::NoError || !parse_doucment.isObject()) return ; QJsonObject jsonObject = parse_doucment.object(); if(!jsonObject.value("result").isArray()) { return ; } QJsonArray object = jsonObject.value("result").toArray(); if(object.isEmpty()) return ; QString accountAddress = object[0].toObject().value("owner").toString(); QString symbol = object[0].toObject().value("chain_type").toString(); QString tunnelAddress = object[0].toObject().value("bind_account").toString(); if(!accountAddress.isEmpty() && !accountAddress.isEmpty() && !symbol.isEmpty()) { _p->updateTunnel(accountAddress,symbol,tunnelAddress); } } void DepositAutomatic::ParseMutli(const QString &jsonString) { // qDebug()<< "auto--"<<jsonString; QJsonParseError json_error; QJsonDocument parse_doucment = QJsonDocument::fromJson(jsonString.toLatin1(),&json_error); if(json_error.error != QJsonParseError::NoError || !parse_doucment.isObject()) return ; QJsonObject jsonObject = parse_doucment.object(); if(!jsonObject.value("result").isObject()) { return; } QString symbol = jsonObject.value("result").toObject().value("chain_type").toString(); QString multi = jsonObject.value("result").toObject().value("bind_account_hot").toString(); if(!symbol.isEmpty() && !multi.isEmpty()) { _p->updateMulti(symbol,multi); } } void DepositAutomatic::ParseTransaction(const QString &address,const QString &jsonString) { qDebug()<< "parse--transaction--"<<jsonString; QJsonParseError json_error; QJsonDocument parse_doucment = QJsonDocument::fromJson(jsonString.toLatin1(),&json_error); if(json_error.error != QJsonParseError::NoError || !parse_doucment.isObject()) return ; QJsonObject jsonObject = parse_doucment.object(); QJsonObject obj = jsonObject.value("result").toObject(); //获取对应通道地址 //QString tunnelAddress; //QJsonArray arr = obj.value("trx").toObject().value("vout").toArray(); //foreach (QJsonValue val, arr) { // if(!val.isObject()) continue; // QJsonObject valObj = val.toObject(); // if(valObj.value("n").toInt() == 0) // { // qDebug()<<"dededetail--"<<valObj.value("scriptPubKey").toObject().value("addresses"); // tunnelAddress = valObj.value("scriptPubKey").toObject().value("addresses").toArray()[0].toString(); // break; // } //} if(!address.isEmpty()) { qDebug()<<"dededetail--"<<address<<obj; _p->updateDetail(address,obj); } }
34.815416
154
0.615183
[ "object" ]
42c7806b658ff324bda81c8c61cf48b9754c30c5
3,146
cpp
C++
src/OPECiphertext.cpp
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
src/OPECiphertext.cpp
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
src/OPECiphertext.cpp
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 University of Leeds * * 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. * * This is being developed for the TANGO Project: http://tango-project.eu */ #include "OPECiphertext.h" /** * Default constructor */ OPECiphertext::OPECiphertext() { // TODO Auto-generated constructor stub } /** * Default destructor */ OPECiphertext::~OPECiphertext() { // TODO Auto-generated destructor stub } /** * Initialise \c ciphertext to the value supplied * @param a An NTL multiprecision integer */ OPECiphertext::OPECiphertext(NTL::ZZ& a){ ciphertext = a; } /** * Initialise \c ciphertext to the value supplied * @param str A decimal string */ OPECiphertext::OPECiphertext(std::string& str){ std::stringstream ss(str); ss >> ciphertext; } /** * Write \c ciphertext as decimal string to the output stream * @param o Output stream * @param c \c OPECiphertext object * @return a reference to the output stream */ std::ostream& operator<<(std::ostream& o, const OPECiphertext& c){ o << c.ciphertext; return o; } /** * Read \c ciphertext as decimal string from the input stream and convert to \c NTL::ZZ * @param i Input stream * @param c \c OPECiphertext object * @return a reference to the output stream */ std::istream& operator>>(std::istream& i, OPECiphertext& c){ i >> c.ciphertext; return i; } /** * Returns \c a.ciphertext \< \c b.ciphertext * @param a \c OPECiphertext object * @param b \c OPECiphertext object * @return \c true or \c false */ bool operator<(const OPECiphertext& a, const OPECiphertext& b){ return a.ciphertext<b.ciphertext; } /** * Returns \c a.ciphertext &le; \c b.ciphertext * @param a \c OPECiphertext object * @param b \c OPECiphertext object * @return \c true or \c false */ bool operator<=(const OPECiphertext& a, const OPECiphertext& b){ return a.ciphertext<=b.ciphertext; } /** * Returns \c a.ciphertext = \c b.ciphertext * @param a \c OPECiphertext object * @param b \c OPECiphertext object * @return \c true or \c false */ bool operator==(const OPECiphertext& a, const OPECiphertext& b){ return a.ciphertext==b.ciphertext; } /** * Returns \c a.ciphertext \> \c b.ciphertext * @param a \c OPECiphertext object * @param b \c OPECiphertext object * @return \c true or \c false */ bool operator>(const OPECiphertext& a, const OPECiphertext& b){ return a.ciphertext>b.ciphertext; } /** * Returns \c a.ciphertext &ge; \c b.ciphertext * @param a \c OPECiphertext object * @param b \c OPECiphertext object * @return \c true or \c false */ bool operator>=(const OPECiphertext& a, const OPECiphertext& b){ return a.ciphertext>=b.ciphertext; }
25.370968
87
0.705022
[ "object" ]