blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
451fd13463e66fe57268b69fc1e5627fa5fe0b03 | 7fdf48345a3178fd6ec582d99b34897965b09e82 | /support/xerces/samples/DOMPrint/DOMTreeErrorReporter.cpp | 8fe7603a30a05d2763d0d4d78c2cc078ab874401 | [
"Apache-1.1",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | hhy5277/livingstone2 | e748c3cec0b5b5e94e7acb6c812c879dce399f22 | 38fa2f1d81ff6124e37aff21b5c73751ad25fec0 | refs/heads/master | 2020-04-18T01:13:42.154101 | 2018-01-12T03:09:27 | 2018-01-12T03:09:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,679 | cpp | /*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log: DOMTreeErrorReporter.cpp,v $
* Revision 1.1.1.1 2000/04/08 04:37:32 kurien
* XML parser for C++
*
*
* Revision 1.3 2000/02/06 07:47:18 rahulj
* Year 2K copyright swat.
*
* Revision 1.2 1999/12/03 00:14:53 andyh
* Removed transcoding stuff, replaced with DOMString::transcode.
*
* Tweaked xml encoding= declaration to say ISO-8859-1. Still wrong,
* but not as wrong as utf-8
*
* Revision 1.1.1.1 1999/11/09 01:09:51 twl
* Initial checkin
*
* Revision 1.6 1999/11/08 20:43:35 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <sax/SAXParseException.hpp>
#include "DOMTreeErrorReporter.hpp"
#include <iostream.h>
#include <stdlib.h>
#include <memory.h>
#include <dom/DOMString.hpp>
// Global streaming operator for DOMString is defined in DOMPrint.cpp
extern ostream& operator<<(ostream& target, const DOMString& s);
void DOMTreeErrorReporter::warning(const SAXParseException&)
{
//
// Ignore all warnings.
//
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch)
{
cerr << "Error at file \"" << DOMString(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << DOMString(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch)
{
cerr << "Fatal Error at file \"" << DOMString(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << DOMString(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::resetErrors()
{
// No-op in this case
}
| [
"gpgreen@gmail.com"
] | gpgreen@gmail.com |
d357858c30bd14953db1d0428a55db1ab184e4f9 | 1594cfdd6a1d448cc81a096eefb349516fcad465 | /p1_world/world/stdafx.cpp | d196a8d18f3901cafad3316c2f0d97ed988b9cf5 | [] | no_license | fpuertasrodriguez/IS | e2e2e474544e62936cfdeaab883e8b883a0b5f80 | 306f7b0d7be5417a78c6f4dd536ecdc4030d99b4 | refs/heads/master | 2020-07-21T17:33:51.380308 | 2016-11-22T19:33:39 | 2016-11-22T19:33:39 | 73,844,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | // stdafx.cpp : source file that includes just the standard includes
// mundo.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"francisco.puertas@live.u-tad.com"
] | francisco.puertas@live.u-tad.com |
9fd5a428a0704c9218a0d714d3f22e656ad175d2 | a06a9ae73af6690fabb1f7ec99298018dd549bb7 | /_Library/_Include/boost/geometry/strategies/transform.hpp | fbe9ab769c3fe50737ec3ba6724f09069e12dd70 | [] | no_license | longstl/mus12 | f76de65cca55e675392eac162dcc961531980f9f | 9e1be111f505ac23695f7675fb9cefbd6fa876e9 | refs/heads/master | 2021-05-18T08:20:40.821655 | 2020-03-29T17:38:13 | 2020-03-29T17:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,140 | hpp | ////////////////////////////////////////////////////////////////////////////////
// transform.hpp
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_HPP
#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_HPP
#include <cstddef>
#include <boost/mpl/assert.hpp>
#include <boost/geometry/strategies/tags.hpp>
namespace boost { namespace geometry
{
namespace strategy { namespace transform { namespace services
{
/*!
\brief Traits class binding a transformation strategy to a coordinate system
\ingroup transform
\details Can be specialized
- per coordinate system family (tag)
- per coordinate system (or groups of them)
- per dimension
- per point type
\tparam CoordinateSystemTag 1,2 coordinate system tags
\tparam CoordinateSystem 1,2 coordinate system
\tparam D 1, 2 dimension
\tparam Point 1, 2 point type
*/
template
<
typename CoordinateSystemTag1, typename CoordinateSystemTag2,
typename CoordinateSystem1, typename CoordinateSystem2,
std::size_t Dimension1, std::size_t Dimension2,
typename Point1, typename Point2
>
struct default_strategy
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_POINT_TYPES
, (types<Point1, Point2>)
);
};
}}} // namespace strategy::transform::services
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_HPP
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"adm.fael.hs@gmail.com"
] | adm.fael.hs@gmail.com |
b2a53f401ff2cd85f04b59298ed2480942fdc139 | af87b330e08a6bef230824bc384a20762a302ee5 | /design/waiter_flow_control/reserve_waiter.cpp | e127ae3788408393ee1aa808b362d4263e3e8982 | [] | no_license | nalreddy/code | d9684845d555733444c7e6b6b4ce45ae861cfc42 | 8fffb2534fec265174c11aebd8ce1d63cb2e3532 | refs/heads/master | 2023-08-31T16:16:10.770116 | 2023-08-23T09:39:04 | 2023-08-23T09:39:04 | 95,104,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,329 | cpp | #include<boost/intrusive/list>
class SourceList
{
SourceList(const size_t capacity) : mFree(capacity)
{
}
~SourceList() { }
void reserve( Request& _res )
{
if( 0 == _res.mRequested )
return;
if( _res.mRequested > free() )
exception
{
lock( mMutex );
size_t prev = mReserve.load( boost::memory_order_relaxed );
mReserve.store( prev + 1, boost::memory_order_relaxed );
const size_t available = std::min( _res.mRequested, mFree );
_res.mReserved += available;
mFree -= available;
if( available == _res.mRequested )
return;
_res.mQueued = true;
mRequestQueue.push_back( _res );
}
{
mRequestWait.fetch_add( 1, boost::memory_order_relaxed );
_res.wait();
}
}
void release( Request& _res )
{
if( 0 != _res.reserved())
{
if (_res.mReserved > 0)
{
RequestQueue toNotify;
{
lock( mMutex );
freeEntries( _res.mReserved, toNotify );
}
notifyRequests( toNotify );
}
}
}
void notifyRequests( RequestQueue& _requests )
{
while( !_requests.empty() )
{
Request& res = _requests.front();
_requests.pop_front();
res.notify();
}
}
void freeEntries( const size_t _count,RequestQueue& _toNotify )
{
size_t remaining = _count;
while( remaining && !mRequeQueue.empty() )
remaining = dispatch( remaining, _toNotify );
if( remaining > 0 )
mFree += remaining;
}
size_t dispatch( const size_t _available, RequestQueue& _toNotify )
{
size_t remaining = _available;
if( !mRequestQueue.empty() )
{
Request& res = mRequestQueue.front();
size_t consumed;
const bool pop = res.transfer( remaining, consumed );
remaining -= consumed;
if( pop )
{
mRequestQueue.pop_front();
_toNotify.push_back( res );
}
}
return remaining;
}
};
typedef boost::intrusive::listbase_hook<
boost::intrusive::linkmode<boost::intrusive::normal_link>
> RequestHook;
class Request : public RequestHook, private boost::noncopyable
{
friend class SourceList;
Request(SourceList& sList, const sizet _req = 0 );
Request(SourceList& sList, const sizet _req, const bool Try& );
Request( Request& other) :
mRequested( other.mRequested ),
mReserved( other.mReserved ),
mQueued( false )
{
other.mRequested = 0;
other.mReserved = 0;
other.mReservedHB = 0;
}
~Request();
sizet requested() const { return mRequested; }
sizet reserved() const { return mReserved; }
private:
void wait();
bool decrement();
void notify();
SourceList& mSList;
sizet mRequested;
sizet mReserved;
bool mQueued;
boost::mutex mMutex;
boost::conditionvariable mCondition;
};
Request::Request( SourceList& sList, const sizet _req ) :
mSList(sList), mRequested( req ), mReserved( 0 ), mReservedHB( 0 ), mQueued( false )
{
sList.reserve( *this );
}
Request::Request( SourceList& sList, const size_t _req,
const TryReservet& ) :
mSList( sList ), mRequested( _req ), mReserved( 0 ), mReservedHB( 0 ), mQueued( false )
{
mSList.tryReserve( *this );
}
Request::~Request()
{
mSList.release( *this );
}
void Request::reset()
{
mSList.release( *this );
mReserved = 0;
mReservedHB = 0;
}
void Request::wait()
{
boost::mutex::scopedlock lock( mMutex );
while( mQueued )
mCondition.wait( lock );
}
bool Request::decrement()
{
--mReserved;
return false;
}
Request::notify()
{
boost::mutex::scopedlock lock( mMutex );
mQueued = false;
mCondition.notifyone();
}
typedef boost::intrusive::list<Request> RequestQueue;
class RequestMgr
{
RequestQueue mRequestQueue;
};
| [
"vvs@hpe.com"
] | vvs@hpe.com |
293dea830f9db4942b02632d728116c572521a47 | 2bbc6cfe4649fcf7fb09d2d7ce47d57c69fe9160 | /xls/dslx/evaluate.h | b0131447ea7c20824aebd30cf5095e3005125ae0 | [
"Apache-2.0"
] | permissive | Global19/xls | 6cd698156020d2fc6ee57b38e16ff7df72de7c9b | 2463419e22997c644e5e6d982e7649991d562966 | refs/heads/main | 2023-03-03T03:02:13.197690 | 2021-02-12T23:12:05 | 2021-02-12T23:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,743 | h | // Copyright 2020 The XLS Authors
//
// 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 XLS_DSLX_CPP_EVALUATE_H_
#define XLS_DSLX_CPP_EVALUATE_H_
#include "absl/status/statusor.h"
#include "xls/dslx/ast.h"
#include "xls/dslx/import_routines.h"
#include "xls/dslx/interp_bindings.h"
#include "xls/dslx/interp_callback_data.h"
#include "xls/dslx/interp_value.h"
#include "xls/ir/bits.h"
namespace xls::dslx {
// Returns whether 'value' conforms to the given concrete type.
absl::StatusOr<bool> ConcreteTypeAcceptsValue(const ConcreteType& type,
const InterpValue& value);
// Returns whether the value is compatible with type (recursively).
//
// This compatibility test is used for e.g. casting validity purposes.
absl::StatusOr<bool> ValueCompatibleWithType(const ConcreteType& type,
const InterpValue& value);
// Converts "value" into a value of "type".
//
// Args:
// type: Type to convert value into.
// value: Value to convert into "type".
// span: The span of the expression performing the conversion (used for error
// reporting).
// enum_values: If type is an enum, provides the evaluated values for it.
// enum_signed: If type is an enum, provides whether it is signed.
absl::StatusOr<InterpValue> ConcreteTypeConvertValue(
const ConcreteType& type, const InterpValue& value, const Span& span,
absl::optional<std::vector<InterpValue>> enum_values,
absl::optional<bool> enum_signed);
// Evaluates the user defined function fn as an invocation against args.
//
// Args:
// fn: The user-defined function to evaluate.
// args: The argument with which the user-defined function is being invoked.
// span: The source span of the invocation.
// symbolic_bindings: Tuple containing the symbolic bindings to use in
// the evaluation of this function body (computed by the typechecker)
//
// Returns:
// The value that results from evaluating the function on the arguments.
//
// Raises:
// EvaluateError: If the types annotated on either parameters or the return
// type do not match with the values presented as arguments / the value
// resulting from the function evaluation.
absl::StatusOr<InterpValue> EvaluateFunction(
Function* f, absl::Span<const InterpValue> args, const Span& span,
const SymbolicBindings& symbolic_bindings, InterpCallbackData* callbacks);
// Note: all interpreter "node evaluators" have the same signature.
absl::StatusOr<InterpValue> EvaluateConstRef(ConstRef* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
absl::StatusOr<InterpValue> EvaluateNameRef(NameRef* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
absl::StatusOr<InterpValue> EvaluateColonRef(ColonRef* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
absl::StatusOr<InterpValue> EvaluateWhile(While* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
absl::StatusOr<InterpValue> EvaluateCarry(Carry* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a Number AST node to a value.
//
// Args:
// expr: Number AST node.
// bindings: Name bindings for this evaluation.
// type_context: Type context for evaluating this number; since numbers
// literals are agnostic of their bit width this allows us to create the
// proper-width value.
//
// Returns:
// The resulting interpreter value.
//
// Raises:
// EvaluateError: If the type context is missing or inappropriate (e.g. a
// tuple cannot be the type for a number).
absl::StatusOr<InterpValue> EvaluateNumber(Number* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a struct instance expression; e.g. `Foo { field: stuff }`.
absl::StatusOr<InterpValue> EvaluateStructInstance(
StructInstance* expr, InterpBindings* bindings, ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a struct instance expression;
// e.g. `Foo { field: stuff, ..other_foo }`.
absl::StatusOr<InterpValue> EvaluateSplatStructInstance(
SplatStructInstance* expr, InterpBindings* bindings,
ConcreteType* type_context, InterpCallbackData* callbacks);
// Evaluates a tuple expression; e.g. `(x, y)`.
absl::StatusOr<InterpValue> EvaluateXlsTuple(XlsTuple* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a let expression; e.g. `let x = y in z`
absl::StatusOr<InterpValue> EvaluateLet(Let* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a for expression.
absl::StatusOr<InterpValue> EvaluateFor(For* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a cast expression; e.g. `x as u32`.
absl::StatusOr<InterpValue> EvaluateCast(Cast* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a unary operation expression; e.g. `-x`.
absl::StatusOr<InterpValue> EvaluateUnop(Unop* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates an array expression; e.g. `[a, b, c]`.
absl::StatusOr<InterpValue> EvaluateArray(Array* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a binary operation expression; e.g. `x + y`.
absl::StatusOr<InterpValue> EvaluateBinop(Binop* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a ternary expression; e.g. `foo if bar else baz`.
absl::StatusOr<InterpValue> EvaluateTernary(Ternary* expr,
InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates an attribute expression; e.g. `x.y`.
absl::StatusOr<InterpValue> EvaluateAttr(Attr* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates a match expression; e.g. `match x { ... }`.
absl::StatusOr<InterpValue> EvaluateMatch(Match* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Evaluates an index expression; e.g. `a[i]`.
absl::StatusOr<InterpValue> EvaluateIndex(Index* expr, InterpBindings* bindings,
ConcreteType* type_context,
InterpCallbackData* callbacks);
// Creates the top level bindings for a given module. We may not be able to
// create a *complete* set of bindings if we've re-entered this routine; e.g. in
// evaluating a top-level constant we recur to ask what enums (or similar) are
// available in the module scope -- in those cases we populate as many top level
// bindings as we can before we reach the work-in-progress point.
//
// Args:
// module: The top-level module to make bindings for.
// callbacks: Provide ability to call back into the interpreter facilities
// e.g. on import or for evaluating constant value expressions.
absl::StatusOr<std::shared_ptr<InterpBindings>> MakeTopLevelBindings(
Module* module, InterpCallbackData* callbacks);
using ConcretizeVariant = absl::variant<TypeAnnotation*, EnumDef*, StructDef*>;
// Resolve "type" into a concrete type via expression evaluation.
absl::StatusOr<std::unique_ptr<ConcreteType>> ConcretizeType(
ConcretizeVariant type, InterpBindings* bindings,
InterpCallbackData* callbacks);
// As above, but specifically for concretizing TypeAnnotation nodes.
absl::StatusOr<std::unique_ptr<ConcreteType>> ConcretizeTypeAnnotation(
TypeAnnotation* type, InterpBindings* bindings,
InterpCallbackData* callbacks);
// Resolves (parametric) dimensions from deduction vs the current bindings.
absl::StatusOr<int64> ResolveDim(
absl::variant<Expr*, int64, ConcreteTypeDim> dim, InterpBindings* bindings);
using DerefVariant = absl::variant<TypeAnnotation*, EnumDef*, StructDef*>;
// Returns the type_definition dereferenced into a Struct or Enum or
// TypeAnnotation.
//
// Will produce TypeAnnotation in the case we bottom out in a tuple, for
// example.
//
// Args:
// node: Node to resolve to a struct/enum/annotation.
// bindings: Current bindings for evaluating the node.
absl::StatusOr<DerefVariant> EvaluateToStructOrEnumOrAnnotation(
TypeDefinition type_definition, InterpBindings* bindings,
InterpCallbackData* callbacks);
} // namespace xls::dslx
#endif // XLS_DSLX_CPP_EVALUATE_H_
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
7cc5d959dc42913ab58c83ba25a85aa1ac05adb8 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5706278382862336_0/C++/Nishad94/A.cpp | 41dfbde38e7c5c7f153bf920fd51f8aab96e4522 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#define ll long long
using namespace std;
ll gcd(ll a, ll b)
{
if(a == 0)
return b;
if(a > b){
ll tmp = a;
a = b;
b = tmp;
}
return gcd(b%a, a);
}
int main()
{
int T;
cin >> T;
for(int t = 1; t <= T; ++t){
string s;
cin >> s;
ll P, Q;
P = Q = 0;
int i = 0;
while(s[i] != '/'){
P = P*10 + s[i] - '0';
++i;
}
++i;
while(i < s.size()){
Q = Q*10 + s[i] - '0';
++i;
}
ll common = gcd(P,Q);
P = P/common; Q = Q/common;
// check if q is power of 2
ll temp = Q;
while(temp){
if(temp & 1 == 1)
break;
temp /= 2;
}
if(temp == 1){
ll ans = 0;
while(P < Q){
if(Q & 1 == 1)
break;
Q = Q/2;
++ans;
}
if(P < Q)
cout << "Case #" << t << ": " << "impossible" << endl;
else
cout << "Case #" << t << ": " << ans << endl;
}
else
cout << "Case #" << t << ": " << "impossible" << endl;
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
177d52b34c3163a0fcd4ed450156aa04f363eb69 | f2cdb477c2f76699c38835eb8d6c5b401343d3b4 | /headers/editor/Misc.h | b77a350d73936b1530e56702100f36e28b09f8a2 | [] | no_license | czeidler/ALEditor | 68960ab9a4be789e015c9a8f7d8278081677cd6e | 90c1db5b38eedbb101dfc4648c13e65d552fc033 | refs/heads/master | 2020-06-02T12:50:36.770133 | 2018-03-12T18:47:24 | 2018-03-12T18:47:24 | 16,716,221 | 11 | 7 | null | 2018-03-13T08:03:59 | 2014-02-11T02:05:25 | C++ | UTF-8 | C++ | false | false | 2,036 | h | /*
* Copyright 2012, Clemens Zeidler <haiku@clemens-zeidler.de>
* Distributed under the terms of the MIT License.
*/
#ifndef MISC_H
#define MISC_H
#include <Bitmap.h>
#include <Rect.h>
#include <CustomizableView.h>
namespace BALM {
class EditorHelper {
public:
static BRect GetDragFrame(const BSize prefSize, const BSize minSize)
{
const float kDefaultWidth = 100;
const float kDefaultHeight = 100;
const float kToLarge = 250;
BRect frame;
frame.left = 0;
frame.top = 0;
// validate frame
if (prefSize.width > kToLarge) {
if (minSize.width > kDefaultWidth)
frame.right = minSize.width;
else
frame.right = kDefaultWidth;
} else
frame.right = prefSize.width;
if (prefSize.height > kToLarge) {
if (minSize.height > kDefaultHeight)
frame.bottom = minSize.height;
else
frame.bottom = kDefaultHeight;
} else
frame.bottom = prefSize.height;
// app server bug:
if (frame.right > 150)
frame.right = 150;
if (frame.bottom > 40)
frame.bottom = 40;
return frame;
}
static BBitmap* CreateBitmap(BALM::CustomizableAddOn* addOn, BRect& frame,
BMessage* message = NULL)
{
BReference<Customizable> customizable = addOn->InstantiateCustomizable(
message);
CustomizableView* customizableView = dynamic_cast<CustomizableView*>(
customizable.Get());
if (customizableView == NULL) {
frame = BRect(-1, -1, -1, -1);
return NULL;
}
BSize prefSize = customizableView->PreferredSize();
BSize minSize = customizableView->MinSize();
frame = GetDragFrame(prefSize, minSize);
return NULL;
BView* view = customizableView->View();
if (view == NULL)
return NULL;
BBitmap* bitmap = new BBitmap(frame, B_RGBA32, true);
if (!bitmap->Lock())
return NULL;
bitmap->AddChild(view);
view->ResizeTo(frame.Width(), frame.Height());
view->Draw(frame);
view->Sync();
view->RemoveSelf();
bitmap->Unlock();
BBitmap* dragBitmap = new BBitmap(frame, B_RGBA32);
memcpy(dragBitmap->Bits(), bitmap->Bits(), bitmap->BitsLength());
delete bitmap;
return dragBitmap;
}
};
}
#endif // MISC_H
| [
"haiku@clemens-zeidler.de"
] | haiku@clemens-zeidler.de |
1230cdb617e4f91509135480b1b59426e7bc1a76 | af2f5806cdb788749a9987a4294a8e270aab3ec8 | /Project/06_OpenTyrian/Class/menus.cpp | 231b986f5a941e09f2f3dd159f9f5efb3e7f8418 | [] | no_license | pdpdds/SDLProgramming | 65f53bf7a7d28952780a06b4a1b80b4a80aeea95 | f69683aa41908f8f1b3b80b7076ca0e7908f59da | refs/heads/master | 2021-01-18T22:35:12.116696 | 2020-12-31T06:22:53 | 2020-12-31T06:22:53 | 37,397,842 | 12 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 6,970 | cpp | /*
* OpenTyrian Classic: A modern cross-platform port of Tyrian
* Copyright (C) 2007-2009 The OpenTyrian Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "episodes.h"
#include "fonthand.h"
#include "keyboard.h"
#include "menus.h"
#include "nortsong.h"
#include "opentyr.h"
#include "palette.h"
#include "picload.h"
#include "setup.h"
#include "sprite.h"
#include "video.h"
char episode_name[6][31], difficulty_name[7][21], gameplay_name[5][26];
bool
select_menuitem_by_touch(JE_byte menu_top, JE_byte menu_spacing, JE_shortint menu_item_count, JE_shortint *current_item)
{
if (!mousedown)
return false;
char new_item = (mouse_y - menu_top) / menu_spacing;
if (mouse_y >= menu_top && mouse_y < menu_top + (menu_item_count+1) * menu_spacing)
{
if (new_item == *current_item)
return false;
JE_playSampleNum(S_CURSOR);
*current_item = new_item;
}
return true;
}
bool select_gameplay( void )
{
JE_loadPic(VGAScreen, 2, false);
JE_dString(VGAScreen, JE_fontCenter(gameplay_name[0], FONT_SHAPES), 20, gameplay_name[0], FONT_SHAPES);
const JE_byte menu_top = 30, menu_spacing = 24;
JE_shortint gameplay = 1,
gameplay_max = 4;
bool fade_in = true;
for (; ; )
{
for (int i = 1; i <= gameplay_max; i++)
{
JE_outTextAdjust(VGAScreen, JE_fontCenter(gameplay_name[i], SMALL_FONT_SHAPES), i * menu_spacing + menu_top, gameplay_name[i], 15, - 4 + (i == gameplay ? 2 : 0) - (i == 4 ? 4 : 0), SMALL_FONT_SHAPES, true);
}
JE_showVGA();
if (fade_in)
{
fade_palette(colors, 10, 0, 255);
fade_in = false;
}
JE_word temp = 0;
JE_textMenuWait(&temp, false);
if (select_menuitem_by_touch(menu_top, menu_spacing, gameplay_max, &gameplay))
continue;
if (newkey)
{
switch (lastkey_sym)
{
case SDLK_UP:
case SDLK_LCTRL:
gameplay--;
if (gameplay < 1)
{
gameplay = gameplay_max;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_DOWN:
case SDLK_LALT:
gameplay++;
if (gameplay > gameplay_max)
{
gameplay = 1;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_RETURN:
case SDLK_SPACE:
if (gameplay == 4)
{
JE_playSampleNum(S_SPRING);
/* TODO: NETWORK */
fprintf(stderr, "error: networking via menu not implemented\n");
break;
}
JE_playSampleNum(S_SELECT);
fade_black(10);
onePlayerAction = (gameplay == 2);
twoPlayerMode = (gameplay == 3);
return true;
case SDLK_ESCAPE:
JE_playSampleNum(S_SPRING);
/* fading handled elsewhere
fade_black(10); */
return false;
default:
break;
}
}
}
}
bool select_episode( void )
{
JE_loadPic(VGAScreen, 2, false);
JE_dString(VGAScreen, JE_fontCenter(episode_name[0], FONT_SHAPES), 20, episode_name[0], FONT_SHAPES);
const JE_byte menu_top = 20, menu_spacing = 30;
JE_shortint episode = 1,
episode_max = EPISODE_MAX - 1;
bool fade_in = true;
for (; ; )
{
for (int i = 1; i <= episode_max; i++)
{
JE_outTextAdjust(VGAScreen, 20, i * menu_spacing + menu_top, episode_name[i], 15, -4 + (i == episode ? 2 : 0) - (!episodeAvail[i - 1] ? 4 : 0), SMALL_FONT_SHAPES, true);
}
JE_showVGA();
if (fade_in)
{
fade_palette(colors, 10, 0, 255);
fade_in = false;
}
JE_word temp = 0;
JE_textMenuWait(&temp, false);
if (select_menuitem_by_touch(menu_top, menu_spacing, episode_max, &episode))
continue;
if (newkey)
{
switch (lastkey_sym)
{
case SDLK_UP:
case SDLK_LCTRL:
episode--;
if (episode < 1)
{
episode = episode_max;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_DOWN:
case SDLK_LALT:
episode++;
if (episode > episode_max)
{
episode = 1;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_RETURN:
case SDLK_SPACE:
if (!episodeAvail[episode - 1])
{
JE_playSampleNum(S_SPRING);
break;
}
JE_playSampleNum(S_SELECT);
fade_black(10);
JE_initEpisode(episode);
initial_episode_num = episodeNum;
return true;
case SDLK_ESCAPE:
JE_playSampleNum(S_SPRING);
/* fading handled elsewhere
fade_black(10); */
return false;
default:
break;
}
}
}
}
bool select_difficulty( void )
{
JE_loadPic(VGAScreen, 2, false);
JE_dString(VGAScreen, JE_fontCenter(difficulty_name[0], FONT_SHAPES), 20, difficulty_name[0], FONT_SHAPES);
const JE_byte menu_top = 30, menu_spacing = 24;
difficultyLevel = 2;
JE_shortint difficulty_max = 3;
bool fade_in = true;
for (; ; )
{
for (int i = 1; i <= difficulty_max; i++)
{
JE_outTextAdjust(VGAScreen, JE_fontCenter(difficulty_name[i], SMALL_FONT_SHAPES), i * menu_spacing + menu_top, difficulty_name[i], 15, -4 + (i == difficultyLevel ? 2 : 0), SMALL_FONT_SHAPES, true);
}
JE_showVGA();
if (fade_in)
{
fade_palette(colors, 10, 0, 255);
fade_in = false;
}
JE_word temp = 0;
JE_textMenuWait(&temp, false);
if (select_menuitem_by_touch(menu_top, menu_spacing, difficulty_max, &difficultyLevel))
continue;
if (SDL_GetModState() & KMOD_SHIFT)
{
if ((difficulty_max < 4 && keysactive[SDLK_g]) ||
(difficulty_max == 4 && keysactive[SDLK_RIGHTBRACKET]))
{
difficulty_max++;
}
} else if (difficulty_max == 5 && keysactive[SDLK_l] && keysactive[SDLK_o] && keysactive[SDLK_r] && keysactive[SDLK_d]) {
difficulty_max++;
}
if (newkey)
{
switch (lastkey_sym)
{
case SDLK_UP:
case SDLK_LCTRL:
difficultyLevel--;
if (difficultyLevel < 1)
{
difficultyLevel = difficulty_max;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_DOWN:
case SDLK_LALT:
difficultyLevel++;
if (difficultyLevel > difficulty_max)
{
difficultyLevel = 1;
}
JE_playSampleNum(S_CURSOR);
break;
case SDLK_RETURN:
case SDLK_SPACE:
JE_playSampleNum(S_SELECT);
/* fading handled elsewhere
fade_black(10); */
if (difficultyLevel == 6)
{
difficultyLevel = 8;
} else if (difficultyLevel == 5) {
difficultyLevel = 6;
}
return true;
case SDLK_ESCAPE:
JE_playSampleNum(S_SPRING);
/* fading handled elsewhere
fade_black(10); */
return false;
default:
break;
}
}
}
}
// kate: tab-width 4; vim: set noet:
| [
"juhang3@daum.net"
] | juhang3@daum.net |
897d8e653c156bd1ee1712bff52dd452dd83ffd8 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/content/public/common/client_hints.mojom-shared.h | f263d76ee77515407a5cad31e20525bfcbc07ca8 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,339 | h | // content/public/common/client_hints.mojom-shared.h is auto generated by mojom_bindings_generator.py, do not edit
// 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.
#ifndef CONTENT_PUBLIC_COMMON_CLIENT_HINTS_MOJOM_SHARED_H_
#define CONTENT_PUBLIC_COMMON_CLIENT_HINTS_MOJOM_SHARED_H_
#include <stdint.h>
#include <functional>
#include <ostream>
#include <type_traits>
#include <utility>
#include "base/compiler_specific.h"
#include "base/containers/flat_map.h"
#include "mojo/public/cpp/bindings/array_data_view.h"
#include "mojo/public/cpp/bindings/enum_traits.h"
#include "mojo/public/cpp/bindings/interface_data_view.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/map_data_view.h"
#include "mojo/public/cpp/bindings/string_data_view.h"
#include "content/public/common/client_hints.mojom-shared-internal.h"
#include "mojo/public/mojom/base/time.mojom-shared.h"
#include "third_party/blink/public/mojom/web_client_hints/web_client_hints_types.mojom-shared.h"
#include "url/mojom/origin.mojom-shared.h"
#include "mojo/public/cpp/bindings/lib/interface_serialization.h"
namespace client_hints {
namespace mojom {
} // namespace mojom
} // namespace client_hints
namespace mojo {
namespace internal {
} // namespace internal
} // namespace mojo
namespace client_hints {
namespace mojom {
// Interface base classes. They are used for type safety check.
class ClientHintsInterfaceBase {};
using ClientHintsPtrDataView =
mojo::InterfacePtrDataView<ClientHintsInterfaceBase>;
using ClientHintsRequestDataView =
mojo::InterfaceRequestDataView<ClientHintsInterfaceBase>;
using ClientHintsAssociatedPtrInfoDataView =
mojo::AssociatedInterfacePtrInfoDataView<ClientHintsInterfaceBase>;
using ClientHintsAssociatedRequestDataView =
mojo::AssociatedInterfaceRequestDataView<ClientHintsInterfaceBase>;
} // namespace mojom
} // namespace client_hints
namespace std {
} // namespace std
namespace mojo {
} // namespace mojo
namespace client_hints {
namespace mojom {
} // namespace mojom
} // namespace client_hints
#endif // CONTENT_PUBLIC_COMMON_CLIENT_HINTS_MOJOM_SHARED_H_ | [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
e519794cd899ad84d744faea208bb333c3be014a | 5a6be7b482229f34ba09c690b876308fbf5caa93 | /src/ESTG.h | bec4db4d62b9024a11f7f5736209e575ea91da4a | [] | no_license | fancydz/test-ex | c207698f38097b40396ab240dc25165ae68ab3e2 | 8b41aff1f42cedc48e13111e5da0d586779cd061 | refs/heads/master | 2020-05-19T10:42:19.382391 | 2018-03-13T07:01:02 | 2018-03-13T07:01:02 | 37,370,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | h | #ifndef ESTG_H
#define ESTG_H
#include <list>
#include <hge.h>
#include <hgefont.h>
#include <common\common_res.h>
#include <bullet.h>
#include <common\self_char\self_char.h>
#include <common\self_char\green_dam\green_dam.h>
using namespace std;
class ESTG
{
public:
ESTG(char* rep_file=0);
list<bullet*> blist[MAX_ATTR][MAX_LAYER];
self_char* self;
bullet* stage_master;
bool pause;
struct control_t
{
bool up,down,left,right,fire,slow,bomb;
} control;
struct data_t
{
int object;
int object_alive;
int point;
int p2p[8];
int player;
int spell;
int graze;
int score;
int score_show;
} data;
int ticker;
list<bullet*>::iterator add(bullet* pbullet);
void add_self(int _self);
void loop();
void run_scripts();
float xorg,yorg,xstr,ystr,xos,yos;
int shake_status;
void shake(int duration=120);
back_ground* bg1;//pre
back_ground* bg2;//post
void set_bg(back_ground* pbg,int trans_time=60);
int bg_trans_time;
int bg_trans_status;//0 means post bg is fully drawn
resource sres;
float se_volume;
float bgm_volume;
void play_se(char* effect,float volume)
{
res->snd[effect]->vol+=exp(volume*SND_FACTOR);
}
struct bgm_info_t
{
HEFFECT next_bgm;
HCHANNEL bgm_chn;
int fade_status;
float loop_end;
float loop_lenth;
float pos;
} bgm;
void play_bgm(HEFFECT se_bgm,float lp_end,float lp_lenth);
void destroy_all_enemy();
void kill_all_bullet();
float hp_bar;
float count_down_timer;
bool is_replay;
bool no_rep;
char rep_data[1024*1024];
struct rep_info_t
{
int ran_seed;
int lenth;
//and other informations
} rep_info;
void save_rep(char* rep_file_path);
void load_rep(char* rep_file_path);
bool quit_flag;
void quit();
~ESTG();
};
inline bool is_collide(bullet* attacker,bullet* sufferer,float sufferer_r=-1.0);
extern HGE* hge;
extern ESTG* estg;
extern cres* res;
inline float x2scr(float x){return (estg->xos+estg->xorg+estg->xstr*x);}
inline float y2scr(float y){return (estg->yos+estg->yorg+estg->ystr*y);}
inline float uix2scr(float x){return (estg->xorg+estg->xstr*x);}
inline float uiy2scr(float y){return (estg->yorg+estg->ystr*y);}
//score calc
#define BULLET_BONUS 15
#define ATTACK_BONUS 15
#define POINT_BONUS 3000
#define GRAZE_BONUS 150
#define TIME_BONUS 2000
#define GRAZE_FACTOR 7500
#define CARD_FACTOR 3
//
#endif
| [
"w.humanoid@88e6bfd8-b675-11de-a433-7fce7b4d64d6"
] | w.humanoid@88e6bfd8-b675-11de-a433-7fce7b4d64d6 |
79754bdd0a7c92bd5f3e23931ab5ea5d6eddeb34 | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /_REPO/MICROSOFT/cocos2d-x/cocos/ui/UIEditBox/UIEditBoxImpl-common.h | 5a74067eab6eb80b414e569d84906465efe64e31 | [
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | C++ | false | false | 6,640 | h | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2012 James Chen
Copyright (c) 2013-2015 zilongshanren
http://www.cocos2d-x.org
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.
****************************************************************************/
#ifndef __UIEditBoxIMPLICOMMON_H__
#define __UIEditBoxIMPLICOMMON_H__
#include "platform/CCPlatformConfig.h"
#include "ui/UIEditBox/UIEditBoxImpl-common.h"
#include "ui/UIEditBox/UIEditBoxImpl.h"
NS_CC_BEGIN
namespace ui {
class EditBox;
class CC_GUI_DLL EditBoxImplCommon : public EditBoxImpl
{
public:
/**
* @js NA
*/
EditBoxImplCommon(EditBox* pEditText);
/**
* @js NA
* @lua NA
*/
virtual ~EditBoxImplCommon();
virtual bool initWithSize(const Size& size) override;
virtual void setFont(const char* pFontName, int fontSize) override;
virtual void setFontColor(const Color4B& color) override;
virtual void setPlaceholderFont(const char* pFontName, int fontSize) override;
virtual void setPlaceholderFontColor(const Color4B& color) override;
virtual void setInputMode(EditBox::InputMode inputMode) override;
virtual void setInputFlag(EditBox::InputFlag inputFlag) override;
virtual void setReturnType(EditBox::KeyboardReturnType returnType) override;
virtual void setText(const char* pText) override;
virtual void setPlaceHolder(const char* pText) override;
virtual void setVisible(bool visible) override;
virtual void setMaxLength(int maxLength) override;
virtual void setTextHorizontalAlignment(TextHAlignment alignment) override;
virtual int getMaxLength() override { return _maxLength; }
virtual const char* getText(void) override { return _text.c_str(); }
virtual const char* getPlaceHolder(void) override { return _placeHolder.c_str(); }
virtual const char* getFontName() override { return _fontName.c_str(); }
virtual int getFontSize() override { return _fontSize; }
virtual const Color4B& getFontColor() override { return _colText; }
virtual const char* getPlaceholderFontName() override { return _placeholderFontName.c_str(); }
virtual int getPlaceholderFontSize() override { return _placeholderFontSize; }
virtual const Color4B& getPlaceholderFontColor() override { return _colPlaceHolder; }
virtual EditBox::InputMode getInputMode() override { return _editBoxInputMode; }
virtual EditBox::InputFlag getInputFlag() override { return _editBoxInputFlag; }
virtual EditBox::KeyboardReturnType getReturnType() override { return _keyboardReturnType; }
virtual TextHAlignment getTextHorizontalAlignment() override { return _alignment; }
virtual void refreshInactiveText();
virtual void setContentSize(const Size& size) override;
virtual void setAnchorPoint(const Vec2& anchorPoint) override {}
virtual void setPosition(const Vec2& pos) override {}
/**
* @js NA
* @lua NA
*/
virtual void draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
/**
* @js NA
* @lua NA
*/
virtual void onEnter(void) override;
virtual void openKeyboard() override;
virtual void closeKeyboard() override;
virtual void onEndEditing(const std::string& text);
void editBoxEditingDidBegin();
void editBoxEditingChanged(const std::string& text);
void editBoxEditingDidEnd(const std::string& text, EditBoxDelegate::EditBoxEndAction action = EditBoxDelegate::EditBoxEndAction::UNKNOWN);
virtual bool isEditing() override = 0;
virtual void createNativeControl(const Rect& frame) = 0;
virtual void setNativeFont(const char* pFontName, int fontSize) = 0;
virtual void setNativeFontColor(const Color4B& color) = 0;
virtual void setNativePlaceholderFont(const char* pFontName, int fontSize) = 0;
virtual void setNativePlaceholderFontColor(const Color4B& color) = 0;
virtual void setNativeInputMode(EditBox::InputMode inputMode) = 0;
virtual void setNativeInputFlag(EditBox::InputFlag inputFlag) = 0;
virtual void setNativeReturnType(EditBox::KeyboardReturnType returnType) = 0;
virtual void setNativeTextHorizontalAlignment(cocos2d::TextHAlignment alignment) = 0;
virtual void setNativeText(const char* pText) = 0;
virtual void setNativePlaceHolder(const char* pText) = 0;
virtual void setNativeVisible(bool visible) = 0;
virtual void updateNativeFrame(const Rect& rect) = 0;
virtual const char* getNativeDefaultFontName() = 0;
virtual void nativeOpenKeyboard() = 0;
virtual void nativeCloseKeyboard() = 0;
virtual void setNativeMaxLength(int maxLength) {};
protected:
void initInactiveLabels(const Size& size);
void setInactiveText(const char* pText);
void refreshLabelAlignment();
void placeInactiveLabels(const Size& size);
virtual void doAnimationWhenKeyboardMove(float duration, float distance)override {};
Label* _label;
Label* _labelPlaceHolder;
EditBox::InputMode _editBoxInputMode;
EditBox::InputFlag _editBoxInputFlag;
EditBox::KeyboardReturnType _keyboardReturnType;
cocos2d::TextHAlignment _alignment;
std::string _text;
std::string _placeHolder;
std::string _fontName;
std::string _placeholderFontName;
int _fontSize;
int _placeholderFontSize;
Color4B _colText;
Color4B _colPlaceHolder;
int _maxLength;
Size _contentSize;
bool _editingMode;
};
}
NS_CC_END
#endif /* __UIEditBoxIMPLICOMMON_H__ */
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
b11e670bb986e6de269706aee082d13d1682672a | 9c0987e2a040902a82ed04d5e788a074a2161d2f | /cpp/platform/impl/windows/generated/winrt/impl/Windows.ApplicationModel.ConversationalAgent.0.h | 476a58bba2b123c814b1833b9a675c5198d4f9a8 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | l1kw1d/nearby-connections | ff9119338a6bd3e5c61bc2c93d8d28b96e5ebae5 | ea231c7138d3dea8cd4cd75692137e078cbdd73d | refs/heads/master | 2023-06-15T04:15:54.683855 | 2021-07-12T23:05:16 | 2021-07-12T23:06:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,117 | h | // Copyright 2020 Google 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
//
// https://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.
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.210505.3
#ifndef WINRT_Windows_ApplicationModel_ConversationalAgent_0_H
#define WINRT_Windows_ApplicationModel_ConversationalAgent_0_H
WINRT_EXPORT namespace winrt::Windows::Foundation
{
struct EventRegistrationToken;
struct IAsyncAction;
template <typename TResult> struct __declspec(empty_bases) IAsyncOperation;
template <typename TSender, typename TResult> struct __declspec(empty_bases) TypedEventHandler;
}
WINRT_EXPORT namespace winrt::Windows::Foundation::Collections
{
template <typename T> struct __declspec(empty_bases) IVectorView;
}
WINRT_EXPORT namespace winrt::Windows::Media::Audio
{
struct AudioDeviceInputNode;
struct AudioGraph;
}
WINRT_EXPORT namespace winrt::Windows::Storage::Streams
{
struct IInputStream;
}
WINRT_EXPORT namespace winrt::Windows::ApplicationModel::ConversationalAgent
{
enum class ActivationSignalDetectionTrainingDataFormat : int32_t
{
Voice8kHz8BitMono = 0,
Voice8kHz16BitMono = 1,
Voice16kHz8BitMono = 2,
Voice16kHz16BitMono = 3,
VoiceOEMDefined = 4,
Audio44kHz8BitMono = 5,
Audio44kHz16BitMono = 6,
Audio48kHz8BitMono = 7,
Audio48kHz16BitMono = 8,
AudioOEMDefined = 9,
OtherOEMDefined = 10,
};
enum class ActivationSignalDetectorKind : int32_t
{
AudioPattern = 0,
AudioImpulse = 1,
HardwareEvent = 2,
};
enum class ActivationSignalDetectorPowerState : int32_t
{
HighPower = 0,
ConnectedLowPower = 1,
DisconnectedLowPower = 2,
};
enum class ConversationalAgentSessionUpdateResponse : int32_t
{
Success = 0,
Failed = 1,
};
enum class ConversationalAgentState : int32_t
{
Inactive = 0,
Detecting = 1,
Listening = 2,
Working = 3,
Speaking = 4,
ListeningAndSpeaking = 5,
};
enum class ConversationalAgentSystemStateChangeType : int32_t
{
UserAuthentication = 0,
ScreenAvailability = 1,
IndicatorLightAvailability = 2,
VoiceActivationAvailability = 3,
};
enum class DetectionConfigurationAvailabilityChangeKind : int32_t
{
SystemResourceAccess = 0,
Permission = 1,
LockScreenPermission = 2,
};
enum class DetectionConfigurationTrainingStatus : int32_t
{
Success = 0,
FormatNotSupported = 1,
VoiceTooQuiet = 2,
VoiceTooLoud = 3,
VoiceTooFast = 4,
VoiceTooSlow = 5,
VoiceQualityProblem = 6,
TrainingSystemInternalError = 7,
};
struct IActivationSignalDetectionConfiguration;
struct IActivationSignalDetector;
struct IConversationalAgentDetectorManager;
struct IConversationalAgentDetectorManagerStatics;
struct IConversationalAgentSession;
struct IConversationalAgentSessionInterruptedEventArgs;
struct IConversationalAgentSessionStatics;
struct IConversationalAgentSignal;
struct IConversationalAgentSignalDetectedEventArgs;
struct IConversationalAgentSystemStateChangedEventArgs;
struct IDetectionConfigurationAvailabilityChangedEventArgs;
struct IDetectionConfigurationAvailabilityInfo;
struct ActivationSignalDetectionConfiguration;
struct ActivationSignalDetector;
struct ConversationalAgentDetectorManager;
struct ConversationalAgentSession;
struct ConversationalAgentSessionInterruptedEventArgs;
struct ConversationalAgentSignal;
struct ConversationalAgentSignalDetectedEventArgs;
struct ConversationalAgentSystemStateChangedEventArgs;
struct DetectionConfigurationAvailabilityChangedEventArgs;
struct DetectionConfigurationAvailabilityInfo;
}
namespace winrt::impl
{
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManagerStatics>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionStatics>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo>{ using type = interface_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentDetectorManager>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionInterruptedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignal>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignalDetectedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityInfo>{ using type = class_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorKind>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorPowerState>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentState>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangeType>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangeKind>{ using type = enum_category; };
template <> struct category<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationTrainingStatus>{ using type = enum_category; };
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration> = L"Windows.ApplicationModel.ConversationalAgent.ActivationSignalDetectionConfiguration";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector> = L"Windows.ApplicationModel.ConversationalAgent.ActivationSignalDetector";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentDetectorManager> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentDetectorManager";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSession";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionInterruptedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSessionInterruptedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignal> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSignal";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignalDetectedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSignalDetectedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSystemStateChangedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.DetectionConfigurationAvailabilityChangedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityInfo> = L"Windows.ApplicationModel.ConversationalAgent.DetectionConfigurationAvailabilityInfo";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat> = L"Windows.ApplicationModel.ConversationalAgent.ActivationSignalDetectionTrainingDataFormat";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorKind> = L"Windows.ApplicationModel.ConversationalAgent.ActivationSignalDetectorKind";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorPowerState> = L"Windows.ApplicationModel.ConversationalAgent.ActivationSignalDetectorPowerState";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSessionUpdateResponse";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentState> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentState";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangeType> = L"Windows.ApplicationModel.ConversationalAgent.ConversationalAgentSystemStateChangeType";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangeKind> = L"Windows.ApplicationModel.ConversationalAgent.DetectionConfigurationAvailabilityChangeKind";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationTrainingStatus> = L"Windows.ApplicationModel.ConversationalAgent.DetectionConfigurationTrainingStatus";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration> = L"Windows.ApplicationModel.ConversationalAgent.IActivationSignalDetectionConfiguration";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector> = L"Windows.ApplicationModel.ConversationalAgent.IActivationSignalDetector";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentDetectorManager";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManagerStatics> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentDetectorManagerStatics";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSession";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSessionInterruptedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionStatics> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSessionStatics";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSignal";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSignalDetectedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.IConversationalAgentSystemStateChangedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs> = L"Windows.ApplicationModel.ConversationalAgent.IDetectionConfigurationAvailabilityChangedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo> = L"Windows.ApplicationModel.ConversationalAgent.IDetectionConfigurationAvailabilityInfo";
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration>{ 0x40D8BE16,0x5217,0x581C,{ 0x9A,0xB2,0xCE,0x9B,0x2F,0x2E,0x8E,0x00 } }; // 40D8BE16-5217-581C-9AB2-CE9B2F2E8E00
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector>{ 0xB5BF345F,0xA4D0,0x5B2B,{ 0x8E,0x65,0xB3,0xC5,0x5E,0xE7,0x56,0xFF } }; // B5BF345F-A4D0-5B2B-8E65-B3C55EE756FF
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager>{ 0xDE94FBB0,0x597A,0x5DF8,{ 0x8C,0xFB,0x9D,0xBB,0x58,0x3B,0xA3,0xFF } }; // DE94FBB0-597A-5DF8-8CFB-9DBB583BA3FF
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManagerStatics>{ 0x36A8D283,0xFA0E,0x5693,{ 0x84,0x89,0x0F,0xB2,0xF0,0xAB,0x40,0xD3 } }; // 36A8D283-FA0E-5693-8489-0FB2F0AB40D3
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>{ 0xDAAAE09A,0xB7BA,0x57E5,{ 0xAD,0x13,0xDF,0x52,0x0F,0x9B,0x6F,0xA7 } }; // DAAAE09A-B7BA-57E5-AD13-DF520F9B6FA7
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs>{ 0x9766591F,0xF63D,0x5D3E,{ 0x9B,0xF2,0xBD,0x07,0x60,0x55,0x26,0x86 } }; // 9766591F-F63D-5D3E-9BF2-BD0760552686
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionStatics>{ 0xA005166E,0xE954,0x576E,{ 0xBE,0x04,0x11,0xB8,0xED,0x10,0xF3,0x7B } }; // A005166E-E954-576E-BE04-11B8ED10F37B
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal>{ 0x20ED25F7,0xB120,0x51F2,{ 0x86,0x03,0x26,0x5D,0x6A,0x47,0xF2,0x32 } }; // 20ED25F7-B120-51F2-8603-265D6A47F232
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs>{ 0x4D57EB8F,0xF88A,0x599B,{ 0x91,0xD3,0xD6,0x04,0x87,0x67,0x08,0xBC } }; // 4D57EB8F-F88A-599B-91D3-D604876708BC
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs>{ 0x1C2C6E3E,0x2785,0x59A7,{ 0x8E,0x71,0x38,0xAD,0xEE,0xF7,0x99,0x28 } }; // 1C2C6E3E-2785-59A7-8E71-38ADEEF79928
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs>{ 0x5129C9FB,0x4BE8,0x5F14,{ 0xAF,0x2B,0x88,0xD6,0x2B,0x1B,0x44,0x62 } }; // 5129C9FB-4BE8-5F14-AF2B-88D62B1B4462
template <> inline constexpr guid guid_v<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo>{ 0xB5AFFEB0,0x40F0,0x5398,{ 0xB8,0x38,0x91,0x97,0x9C,0x2C,0x62,0x08 } }; // B5AFFEB0-40F0-5398-B838-91979C2C6208
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentDetectorManager>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionInterruptedEventArgs>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignal>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignalDetectedEventArgs>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangedEventArgs>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangedEventArgs>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs; };
template <> struct default_interface<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityInfo>{ using type = winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo; };
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_SignalId(void**) noexcept = 0;
virtual int32_t __stdcall get_ModelId(void**) noexcept = 0;
virtual int32_t __stdcall get_DisplayName(void**) noexcept = 0;
virtual int32_t __stdcall get_IsActive(bool*) noexcept = 0;
virtual int32_t __stdcall SetEnabled(bool) noexcept = 0;
virtual int32_t __stdcall SetEnabledAsync(bool, void**) noexcept = 0;
virtual int32_t __stdcall get_AvailabilityInfo(void**) noexcept = 0;
virtual int32_t __stdcall add_AvailabilityChanged(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_AvailabilityChanged(winrt::event_token) noexcept = 0;
virtual int32_t __stdcall SetModelData(void*, void*) noexcept = 0;
virtual int32_t __stdcall SetModelDataAsync(void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall GetModelDataType(void**) noexcept = 0;
virtual int32_t __stdcall GetModelDataTypeAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetModelData(void**) noexcept = 0;
virtual int32_t __stdcall GetModelDataAsync(void**) noexcept = 0;
virtual int32_t __stdcall ClearModelData() noexcept = 0;
virtual int32_t __stdcall ClearModelDataAsync(void**) noexcept = 0;
virtual int32_t __stdcall get_TrainingStepsCompleted(uint32_t*) noexcept = 0;
virtual int32_t __stdcall get_TrainingStepsRemaining(uint32_t*) noexcept = 0;
virtual int32_t __stdcall get_TrainingDataFormat(int32_t*) noexcept = 0;
virtual int32_t __stdcall ApplyTrainingData(int32_t, void*, int32_t*) noexcept = 0;
virtual int32_t __stdcall ApplyTrainingDataAsync(int32_t, void*, void**) noexcept = 0;
virtual int32_t __stdcall ClearTrainingData() noexcept = 0;
virtual int32_t __stdcall ClearTrainingDataAsync(void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_ProviderId(void**) noexcept = 0;
virtual int32_t __stdcall get_Kind(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_CanCreateConfigurations(bool*) noexcept = 0;
virtual int32_t __stdcall get_SupportedModelDataTypes(void**) noexcept = 0;
virtual int32_t __stdcall get_SupportedTrainingDataFormats(void**) noexcept = 0;
virtual int32_t __stdcall get_SupportedPowerStates(void**) noexcept = 0;
virtual int32_t __stdcall GetSupportedModelIdsForSignalId(void*, void**) noexcept = 0;
virtual int32_t __stdcall GetSupportedModelIdsForSignalIdAsync(void*, void**) noexcept = 0;
virtual int32_t __stdcall CreateConfiguration(void*, void*, void*) noexcept = 0;
virtual int32_t __stdcall CreateConfigurationAsync(void*, void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall GetConfigurations(void**) noexcept = 0;
virtual int32_t __stdcall GetConfigurationsAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetConfiguration(void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall GetConfigurationAsync(void*, void*, void**) noexcept = 0;
virtual int32_t __stdcall RemoveConfiguration(void*, void*) noexcept = 0;
virtual int32_t __stdcall RemoveConfigurationAsync(void*, void*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall GetAllActivationSignalDetectors(void**) noexcept = 0;
virtual int32_t __stdcall GetAllActivationSignalDetectorsAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetActivationSignalDetectors(int32_t, void**) noexcept = 0;
virtual int32_t __stdcall GetActivationSignalDetectorsAsync(int32_t, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManagerStatics>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Default(void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall add_SessionInterrupted(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_SessionInterrupted(winrt::event_token) noexcept = 0;
virtual int32_t __stdcall add_SignalDetected(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_SignalDetected(winrt::event_token) noexcept = 0;
virtual int32_t __stdcall add_SystemStateChanged(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_SystemStateChanged(winrt::event_token) noexcept = 0;
virtual int32_t __stdcall get_AgentState(int32_t*) noexcept = 0;
virtual int32_t __stdcall get_Signal(void**) noexcept = 0;
virtual int32_t __stdcall get_IsIndicatorLightAvailable(bool*) noexcept = 0;
virtual int32_t __stdcall get_IsScreenAvailable(bool*) noexcept = 0;
virtual int32_t __stdcall get_IsUserAuthenticated(bool*) noexcept = 0;
virtual int32_t __stdcall get_IsVoiceActivationAvailable(bool*) noexcept = 0;
virtual int32_t __stdcall get_IsInterruptible(bool*) noexcept = 0;
virtual int32_t __stdcall get_IsInterrupted(bool*) noexcept = 0;
virtual int32_t __stdcall RequestInterruptibleAsync(bool, void**) noexcept = 0;
virtual int32_t __stdcall RequestInterruptible(bool, int32_t*) noexcept = 0;
virtual int32_t __stdcall RequestAgentStateChangeAsync(int32_t, void**) noexcept = 0;
virtual int32_t __stdcall RequestAgentStateChange(int32_t, int32_t*) noexcept = 0;
virtual int32_t __stdcall RequestForegroundActivationAsync(void**) noexcept = 0;
virtual int32_t __stdcall RequestForegroundActivation(int32_t*) noexcept = 0;
virtual int32_t __stdcall GetAudioClientAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetAudioClient(void**) noexcept = 0;
virtual int32_t __stdcall CreateAudioDeviceInputNodeAsync(void*, void**) noexcept = 0;
virtual int32_t __stdcall CreateAudioDeviceInputNode(void*, void**) noexcept = 0;
virtual int32_t __stdcall GetAudioCaptureDeviceIdAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetAudioCaptureDeviceId(void**) noexcept = 0;
virtual int32_t __stdcall GetAudioRenderDeviceIdAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetAudioRenderDeviceId(void**) noexcept = 0;
virtual int32_t __stdcall GetSignalModelIdAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetSignalModelId(uint32_t*) noexcept = 0;
virtual int32_t __stdcall SetSignalModelIdAsync(uint32_t, void**) noexcept = 0;
virtual int32_t __stdcall SetSignalModelId(uint32_t, bool*) noexcept = 0;
virtual int32_t __stdcall GetSupportedSignalModelIdsAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetSupportedSignalModelIds(void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionStatics>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall GetCurrentSessionAsync(void**) noexcept = 0;
virtual int32_t __stdcall GetCurrentSessionSync(void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_IsSignalVerificationRequired(bool*) noexcept = 0;
virtual int32_t __stdcall put_IsSignalVerificationRequired(bool) noexcept = 0;
virtual int32_t __stdcall get_SignalId(void**) noexcept = 0;
virtual int32_t __stdcall put_SignalId(void*) noexcept = 0;
virtual int32_t __stdcall get_SignalName(void**) noexcept = 0;
virtual int32_t __stdcall put_SignalName(void*) noexcept = 0;
virtual int32_t __stdcall get_SignalContext(void**) noexcept = 0;
virtual int32_t __stdcall put_SignalContext(void*) noexcept = 0;
virtual int32_t __stdcall get_SignalStart(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_SignalStart(int64_t) noexcept = 0;
virtual int32_t __stdcall get_SignalEnd(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_SignalEnd(int64_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_SystemStateChangeType(int32_t*) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Kind(int32_t*) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_IsEnabled(bool*) noexcept = 0;
virtual int32_t __stdcall get_HasSystemResourceAccess(bool*) noexcept = 0;
virtual int32_t __stdcall get_HasPermission(bool*) noexcept = 0;
virtual int32_t __stdcall get_HasLockScreenPermission(bool*) noexcept = 0;
};
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IActivationSignalDetectionConfiguration
{
[[nodiscard]] WINRT_IMPL_AUTO(hstring) SignalId() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) ModelId() const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) DisplayName() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsActive() const;
WINRT_IMPL_AUTO(void) SetEnabled(bool value) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetEnabledAsync(bool value) const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityInfo) AvailabilityInfo() const;
WINRT_IMPL_AUTO(winrt::event_token) AvailabilityChanged(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration, winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangedEventArgs> const& handler) const;
using AvailabilityChanged_revoker = impl::event_revoker<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration, &impl::abi_t<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration>::remove_AvailabilityChanged>;
[[nodiscard]] AvailabilityChanged_revoker AvailabilityChanged(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration, winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangedEventArgs> const& handler) const;
WINRT_IMPL_AUTO(void) AvailabilityChanged(winrt::event_token const& token) const noexcept;
WINRT_IMPL_AUTO(void) SetModelData(param::hstring const& dataType, winrt::Windows::Storage::Streams::IInputStream const& data) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) SetModelDataAsync(param::hstring const& dataType, winrt::Windows::Storage::Streams::IInputStream const& data) const;
WINRT_IMPL_AUTO(hstring) GetModelDataType() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<hstring>) GetModelDataTypeAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::Storage::Streams::IInputStream) GetModelData() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Storage::Streams::IInputStream>) GetModelDataAsync() const;
WINRT_IMPL_AUTO(void) ClearModelData() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) ClearModelDataAsync() const;
[[nodiscard]] WINRT_IMPL_AUTO(uint32_t) TrainingStepsCompleted() const;
[[nodiscard]] WINRT_IMPL_AUTO(uint32_t) TrainingStepsRemaining() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat) TrainingDataFormat() const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationTrainingStatus) ApplyTrainingData(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat const& trainingDataFormat, winrt::Windows::Storage::Streams::IInputStream const& trainingData) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationTrainingStatus>) ApplyTrainingDataAsync(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat const& trainingDataFormat, winrt::Windows::Storage::Streams::IInputStream const& trainingData) const;
WINRT_IMPL_AUTO(void) ClearTrainingData() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) ClearTrainingDataAsync() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetectionConfiguration>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IActivationSignalDetectionConfiguration<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IActivationSignalDetector
{
[[nodiscard]] WINRT_IMPL_AUTO(hstring) ProviderId() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorKind) Kind() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) CanCreateConfigurations() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<hstring>) SupportedModelDataTypes() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionTrainingDataFormat>) SupportedTrainingDataFormats() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorPowerState>) SupportedPowerStates() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<hstring>) GetSupportedModelIdsForSignalId(param::hstring const& signalId) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<hstring>>) GetSupportedModelIdsForSignalIdAsync(param::hstring const& signalId) const;
WINRT_IMPL_AUTO(void) CreateConfiguration(param::hstring const& signalId, param::hstring const& modelId, param::hstring const& displayName) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) CreateConfigurationAsync(param::hstring const& signalId, param::hstring const& modelId, param::hstring const& displayName) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration>) GetConfigurations() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration>>) GetConfigurationsAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration) GetConfiguration(param::hstring const& signalId, param::hstring const& modelId) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectionConfiguration>) GetConfigurationAsync(param::hstring const& signalId, param::hstring const& modelId) const;
WINRT_IMPL_AUTO(void) RemoveConfiguration(param::hstring const& signalId, param::hstring const& modelId) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncAction) RemoveConfigurationAsync(param::hstring const& signalId, param::hstring const& modelId) const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IActivationSignalDetector>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IActivationSignalDetector<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentDetectorManager
{
WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>) GetAllActivationSignalDetectors() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>>) GetAllActivationSignalDetectorsAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>) GetActivationSignalDetectors(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorKind const& kind) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetector>>) GetActivationSignalDetectorsAsync(winrt::Windows::ApplicationModel::ConversationalAgent::ActivationSignalDetectorKind const& kind) const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManager>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentDetectorManager<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentDetectorManagerStatics
{
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentDetectorManager) Default() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentDetectorManagerStatics>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentDetectorManagerStatics<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSession
{
WINRT_IMPL_AUTO(winrt::event_token) SessionInterrupted(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionInterruptedEventArgs> const& handler) const;
using SessionInterrupted_revoker = impl::event_revoker<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession, &impl::abi_t<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>::remove_SessionInterrupted>;
[[nodiscard]] SessionInterrupted_revoker SessionInterrupted(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionInterruptedEventArgs> const& handler) const;
WINRT_IMPL_AUTO(void) SessionInterrupted(winrt::event_token const& token) const noexcept;
WINRT_IMPL_AUTO(winrt::event_token) SignalDetected(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignalDetectedEventArgs> const& handler) const;
using SignalDetected_revoker = impl::event_revoker<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession, &impl::abi_t<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>::remove_SignalDetected>;
[[nodiscard]] SignalDetected_revoker SignalDetected(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignalDetectedEventArgs> const& handler) const;
WINRT_IMPL_AUTO(void) SignalDetected(winrt::event_token const& token) const noexcept;
WINRT_IMPL_AUTO(winrt::event_token) SystemStateChanged(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangedEventArgs> const& handler) const;
using SystemStateChanged_revoker = impl::event_revoker<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession, &impl::abi_t<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>::remove_SystemStateChanged>;
[[nodiscard]] SystemStateChanged_revoker SystemStateChanged(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession, winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangedEventArgs> const& handler) const;
WINRT_IMPL_AUTO(void) SystemStateChanged(winrt::event_token const& token) const noexcept;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentState) AgentState() const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSignal) Signal() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsIndicatorLightAvailable() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsScreenAvailable() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsUserAuthenticated() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsVoiceActivationAvailable() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsInterruptible() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsInterrupted() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse>) RequestInterruptibleAsync(bool interruptible) const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse) RequestInterruptible(bool interruptible) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse>) RequestAgentStateChangeAsync(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentState const& state) const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse) RequestAgentStateChange(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentState const& state) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse>) RequestForegroundActivationAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSessionUpdateResponse) RequestForegroundActivation() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::IInspectable>) GetAudioClientAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IInspectable) GetAudioClient() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Audio::AudioDeviceInputNode>) CreateAudioDeviceInputNodeAsync(winrt::Windows::Media::Audio::AudioGraph const& graph) const;
WINRT_IMPL_AUTO(winrt::Windows::Media::Audio::AudioDeviceInputNode) CreateAudioDeviceInputNode(winrt::Windows::Media::Audio::AudioGraph const& graph) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<hstring>) GetAudioCaptureDeviceIdAsync() const;
WINRT_IMPL_AUTO(hstring) GetAudioCaptureDeviceId() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<hstring>) GetAudioRenderDeviceIdAsync() const;
WINRT_IMPL_AUTO(hstring) GetAudioRenderDeviceId() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<uint32_t>) GetSignalModelIdAsync() const;
WINRT_IMPL_AUTO(uint32_t) GetSignalModelId() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<bool>) SetSignalModelIdAsync(uint32_t signalModelId) const;
WINRT_IMPL_AUTO(bool) SetSignalModelId(uint32_t signalModelId) const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Foundation::Collections::IVectorView<uint32_t>>) GetSupportedSignalModelIdsAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::Foundation::Collections::IVectorView<uint32_t>) GetSupportedSignalModelIds() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSession>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSession<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSessionInterruptedEventArgs
{
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionInterruptedEventArgs>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSessionInterruptedEventArgs<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSessionStatics
{
WINRT_IMPL_AUTO(winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession>) GetCurrentSessionAsync() const;
WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSession) GetCurrentSessionSync() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSessionStatics>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSessionStatics<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSignal
{
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsSignalVerificationRequired() const;
WINRT_IMPL_AUTO(void) IsSignalVerificationRequired(bool value) const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) SignalId() const;
WINRT_IMPL_AUTO(void) SignalId(param::hstring const& value) const;
[[nodiscard]] WINRT_IMPL_AUTO(hstring) SignalName() const;
WINRT_IMPL_AUTO(void) SignalName(param::hstring const& value) const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::IInspectable) SignalContext() const;
WINRT_IMPL_AUTO(void) SignalContext(winrt::Windows::Foundation::IInspectable const& value) const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::TimeSpan) SignalStart() const;
WINRT_IMPL_AUTO(void) SignalStart(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::Foundation::TimeSpan) SignalEnd() const;
WINRT_IMPL_AUTO(void) SignalEnd(winrt::Windows::Foundation::TimeSpan const& value) const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignal>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSignal<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSignalDetectedEventArgs
{
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSignalDetectedEventArgs>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSignalDetectedEventArgs<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSystemStateChangedEventArgs
{
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::ConversationalAgentSystemStateChangeType) SystemStateChangeType() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IConversationalAgentSystemStateChangedEventArgs>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IConversationalAgentSystemStateChangedEventArgs<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IDetectionConfigurationAvailabilityChangedEventArgs
{
[[nodiscard]] WINRT_IMPL_AUTO(winrt::Windows::ApplicationModel::ConversationalAgent::DetectionConfigurationAvailabilityChangeKind) Kind() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityChangedEventArgs>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IDetectionConfigurationAvailabilityChangedEventArgs<D>;
};
template <typename D>
struct consume_Windows_ApplicationModel_ConversationalAgent_IDetectionConfigurationAvailabilityInfo
{
[[nodiscard]] WINRT_IMPL_AUTO(bool) IsEnabled() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) HasSystemResourceAccess() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) HasPermission() const;
[[nodiscard]] WINRT_IMPL_AUTO(bool) HasLockScreenPermission() const;
};
template <> struct consume<winrt::Windows::ApplicationModel::ConversationalAgent::IDetectionConfigurationAvailabilityInfo>
{
template <typename D> using type = consume_Windows_ApplicationModel_ConversationalAgent_IDetectionConfigurationAvailabilityInfo<D>;
};
}
#endif
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
cb07691999f4431351e6526c23faa03a72503e77 | bbc61fe39037810826b481d965f295ef5a21dd36 | /src/governance-exceptions.h | cf70397f422ac343da451ca92f7551d46438b273 | [
"MIT"
] | permissive | matthewchincy92/unionew | df7d58f39b752b1b31deb3a0917f7528e3771ef0 | 91951af8a98fb85eefa556d52cff5c1bd52a2e33 | refs/heads/master | 2021-04-03T02:53:01.283946 | 2018-10-23T04:53:45 | 2018-10-23T04:53:45 | 124,864,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | h | // Copyright (c) 2014-2017 The Unio Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GOVERNANCE_EXCEPTIONS_H
#define GOVERNANCE_EXCEPTIONS_H
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
enum governance_exception_type_enum_t {
/// Default value, normally indicates no exception condition occurred
GOVERNANCE_EXCEPTION_NONE = 0,
/// Unusual condition requiring no caller action
GOVERNANCE_EXCEPTION_WARNING = 1,
/// Requested operation cannot be performed
GOVERNANCE_EXCEPTION_PERMANENT_ERROR = 2,
/// Requested operation not currently possible, may resubmit later
GOVERNANCE_EXCEPTION_TEMPORARY_ERROR = 3,
/// Unexpected error (ie. should not happen unless there is a bug in the code)
GOVERNANCE_EXCEPTION_INTERNAL_ERROR = 4
};
inline std::ostream& operator<<(std::ostream& os, governance_exception_type_enum_t eType)
{
switch(eType) {
case GOVERNANCE_EXCEPTION_NONE:
os << "GOVERNANCE_EXCEPTION_NONE";
break;
case GOVERNANCE_EXCEPTION_WARNING:
os << "GOVERNANCE_EXCEPTION_WARNING";
break;
case GOVERNANCE_EXCEPTION_PERMANENT_ERROR:
os << "GOVERNANCE_EXCEPTION_PERMANENT_ERROR";
break;
case GOVERNANCE_EXCEPTION_TEMPORARY_ERROR:
os << "GOVERNANCE_EXCEPTION_TEMPORARY_ERROR";
break;
case GOVERNANCE_EXCEPTION_INTERNAL_ERROR:
os << "GOVERNANCE_EXCEPTION_INTERNAL_ERROR";
break;
}
return os;
}
/**
* A class which encapsulates information about a governance exception condition
*
* Derives from std::exception so is suitable for throwing
* (ie. will be caught by a std::exception handler) but may also be used as a
* normal object.
*/
class CGovernanceException : public std::exception
{
private:
std::string strMessage;
governance_exception_type_enum_t eType;
int nNodePenalty;
public:
CGovernanceException(const std::string& strMessageIn = "",
governance_exception_type_enum_t eTypeIn = GOVERNANCE_EXCEPTION_NONE,
int nNodePenaltyIn = 0)
: strMessage(),
eType(eTypeIn),
nNodePenalty(nNodePenaltyIn)
{
std::ostringstream ostr;
ostr << eType << ":" << strMessageIn;
strMessage = ostr.str();
}
virtual ~CGovernanceException() throw() {}
virtual const char* what() const throw()
{
return strMessage.c_str();
}
const std::string& GetMessage() const
{
return strMessage;
}
governance_exception_type_enum_t GetType() const
{
return eType;
}
int GetNodePenalty() const {
return nNodePenalty;
}
};
#endif
| [
"matthew@wtech.software"
] | matthew@wtech.software |
39e1cbf90a88dd32009ea8fe663a3351880a73c5 | 125ba4d5f464c00fb2c8131bf6e04954e45fc0c0 | /dict/selection.cpp | 128be0443bd46e514dc60d90cb634d2cfb4c8421 | [] | no_license | mariolamacchia/algorithms-and-data-structures | 95a1ffe45809036a24e49b3fae8455ffbdbeda06 | 778022fd39dda6f147d9771527374197bd71cf33 | refs/heads/master | 2021-01-02T09:38:51.051937 | 2015-01-19T19:39:48 | 2015-01-19T19:39:48 | 29,060,244 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include "selection.h"
int selectQuadratic(int hash, int i, int m)
{
return (hash + i * (i-1) / 2) % m;
}
int selectDoubleHash(int hash1, int hash2, int i, int m)
{
return (hash1 + i * hash2) % m;
}
| [
"mariolamacchia@gmail.com"
] | mariolamacchia@gmail.com |
0d8ca0605cb08f60a04c3603e94f70dfbe4ceedb | 97fde28997b618180cfa5dd979b142fd54dd2105 | /core/dep/acelite/ace/os_include/os_pthread.h | a0b0f02db1bfd0dbf080418b3029d7084e672ebd | [] | no_license | Refuge89/sunwell-2 | 5897f4e78c693e791e368761904e79d2b7af20da | f01a89300394065f33eaec799c8779c2cac5c320 | refs/heads/master | 2020-12-31T05:55:43.496145 | 2016-02-16T20:46:50 | 2016-02-16T20:46:50 | 80,622,543 | 1 | 0 | null | 2017-02-01T13:30:06 | 2017-02-01T13:30:06 | null | UTF-8 | C++ | false | false | 15,022 | h | // -*- C++ -*-
//=============================================================================
/**
* @file os_pthread.h
*
* threads
*
* @author Don Hinton <dhinton@dresystems.com>
* @author This code was originally in various places including ace/OS.h.
*/
//=============================================================================
#ifndef ACE_OS_INCLUDE_OS_PTHREAD_H
#define ACE_OS_INCLUDE_OS_PTHREAD_H
#include /**/ "ace/pre.h"
#include /**/ "ace/config-all.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#if defined (ACE_HAS_PRIOCNTL)
// Need to #include thread.h before #defining THR_BOUND, etc.,
// when building without threads on SunOS 5.x.
# if defined (sun)
# include /**/ <thread.h>
# endif /* sun */
// Need to #include these before #defining USYNC_PROCESS on SunOS 5.x.
# include /**/ <sys/rtpriocntl.h>
# include /**/ <sys/tspriocntl.h>
#endif /* ACE_HAS_PRIOCNTL */
#include "ace/os_include/sys/os_types.h"
// This needs to go here *first* to avoid problems with AIX.
# if defined (ACE_HAS_PTHREADS)
# define ACE_DONT_INCLUDE_ACE_SIGNAL_H
# include "ace/os_include/os_signal.h"
# undef ACE_DONT_INCLUDE_ACE_SIGNAL_H
# endif /* ACE_HAS_PTHREADS */
#if !defined (ACE_LACKS_PTHREAD_H)
extern "C" {
# include /**/ <pthread.h>
}
#endif /* !ACE_LACKS_PTHREAD_H */
#if defined (ACE_HAS_PTHREAD_NP_H)
// FreeBSD declares _np (non-portable) pthread extensions in <pthread_np.h>
# include /**/ <pthread_np.h>
#endif
// @todo: need to reoganize to put includes at the top and the rest of the
// code at the bottom. Also, move the classes out of this file.
#if defined (ACE_HAS_PTHREADS)
# define ACE_SCHED_OTHER SCHED_OTHER
# define ACE_SCHED_FIFO SCHED_FIFO
# define ACE_SCHED_RR SCHED_RR
// Definitions for THREAD- and PROCESS-LEVEL priorities...some
// implementations define these while others don't. In order to
// further complicate matters, we don't redefine the default (*_DEF)
// values if they've already been defined, which allows individual
// programs to have their own ACE-wide "default".
// PROCESS-level values
# if (defined (_POSIX_PRIORITY_SCHEDULING) || defined (ACE_TANDEM_T1248_PTHREADS))
# define ACE_PROC_PRI_FIFO_MIN (sched_get_priority_min(SCHED_FIFO))
# define ACE_PROC_PRI_RR_MIN (sched_get_priority_min(SCHED_RR))
# if defined (HPUX)
// HP-UX's other is the SCHED_HPUX class, which uses historical
// values that have reverse semantics from POSIX (low value is
// more important priority). To use these in pthreads calls,
// the values need to be converted. The other scheduling classes
// don't need this special treatment.
# define ACE_PROC_PRI_OTHER_MIN \
(sched_get_priority_min(SCHED_OTHER))
# else
# define ACE_PROC_PRI_OTHER_MIN (sched_get_priority_min(SCHED_OTHER))
# endif /* HPUX */
# else /* UNICOS is missing a sched_get_priority_min() implementation */
# define ACE_PROC_PRI_FIFO_MIN 0
# define ACE_PROC_PRI_RR_MIN 0
# define ACE_PROC_PRI_OTHER_MIN 0
# endif
# if defined (_POSIX_PRIORITY_SCHEDULING)
# define ACE_PROC_PRI_FIFO_MAX (sched_get_priority_max(SCHED_FIFO))
# define ACE_PROC_PRI_RR_MAX (sched_get_priority_max(SCHED_RR))
# if defined (HPUX)
# define ACE_PROC_PRI_OTHER_MAX \
(sched_get_priority_max(SCHED_OTHER))
# else
# define ACE_PROC_PRI_OTHER_MAX (sched_get_priority_max(SCHED_OTHER))
# endif /* HPUX */
# else
# define ACE_PROC_PRI_FIFO_MAX 59
# define ACE_PROC_PRI_RR_MAX 59
# define ACE_PROC_PRI_OTHER_MAX 59
# endif
# if !defined(ACE_PROC_PRI_FIFO_DEF)
# define ACE_PROC_PRI_FIFO_DEF (ACE_PROC_PRI_FIFO_MIN + (ACE_PROC_PRI_FIFO_MAX - ACE_PROC_PRI_FIFO_MIN)/2)
# endif
# if !defined(ACE_PROC_PRI_RR_DEF)
# define ACE_PROC_PRI_RR_DEF (ACE_PROC_PRI_RR_MIN + (ACE_PROC_PRI_RR_MAX - ACE_PROC_PRI_RR_MIN)/2)
# endif
# if !defined(ACE_PROC_PRI_OTHER_DEF)
# define ACE_PROC_PRI_OTHER_DEF (ACE_PROC_PRI_OTHER_MIN + (ACE_PROC_PRI_OTHER_MAX - ACE_PROC_PRI_OTHER_MIN)/2)
# endif
// THREAD-level values
# if defined(PRI_FIFO_MIN) && defined(PRI_FIFO_MAX) && defined(PRI_RR_MIN) && defined(PRI_RR_MAX) && defined(PRI_OTHER_MIN) && defined(PRI_OTHER_MAX)
# if !defined (ACE_THR_PRI_FIFO_MIN)
# define ACE_THR_PRI_FIFO_MIN (long) PRI_FIFO_MIN
# endif /* !ACE_THR_PRI_FIFO_MIN */
# if !defined (ACE_THR_PRI_FIFO_MAX)
# define ACE_THR_PRI_FIFO_MAX (long) PRI_FIFO_MAX
# endif /* !ACE_THR_PRI_FIFO_MAX */
# if !defined (ACE_THR_PRI_RR_MIN)
# define ACE_THR_PRI_RR_MIN (long) PRI_RR_MIN
# endif /* !ACE_THR_PRI_RR_MIN */
# if !defined (ACE_THR_PRI_RR_MAX)
# define ACE_THR_PRI_RR_MAX (long) PRI_RR_MAX
# endif /* !ACE_THR_PRI_RR_MAX */
# if !defined (ACE_THR_PRI_OTHER_MIN)
# define ACE_THR_PRI_OTHER_MIN (long) PRI_OTHER_MIN
# endif /* !ACE_THR_PRI_OTHER_MIN */
# if !defined (ACE_THR_PRI_OTHER_MAX)
# define ACE_THR_PRI_OTHER_MAX (long) PRI_OTHER_MAX
# endif /* !ACE_THR_PRI_OTHER_MAX */
# elif defined (AIX)
// AIX's priority range is 1 (low) to 127 (high). There aren't
// any preprocessor macros I can find. PRIORITY_MIN is for
// process priorities, as far as I can see, and does not apply
// to thread priority. The 1 to 127 range is from the
// pthread_attr_setschedparam man page (Steve Huston, 18-May-2001).
# if !defined (ACE_THR_PRI_FIFO_MIN)
# define ACE_THR_PRI_FIFO_MIN (long) 1
# endif /* !ACE_THR_PRI_FIFO_MIN */
# if !defined (ACE_THR_PRI_FIFO_MAX)
# define ACE_THR_PRI_FIFO_MAX (long) 127
# endif /* !ACE_THR_PRI_FIFO_MAX */
# if !defined (ACE_THR_PRI_RR_MIN)
# define ACE_THR_PRI_RR_MIN (long) 1
# endif /* !ACE_THR_PRI_RR_MIN */
# if !defined (ACE_THR_PRI_RR_MAX)
# define ACE_THR_PRI_RR_MAX (long) 127
# endif /* !ACE_THR_PRI_RR_MAX */
# if !defined (ACE_THR_PRI_OTHER_MIN)
# define ACE_THR_PRI_OTHER_MIN (long) 1
# endif /* !ACE_THR_PRI_OTHER_MIN */
# if !defined (ACE_THR_PRI_OTHER_MAX)
# define ACE_THR_PRI_OTHER_MAX (long) 127
# endif /* !ACE_THR_PRI_OTHER_MAX */
# elif defined (sun)
# if !defined (ACE_THR_PRI_FIFO_MIN)
# define ACE_THR_PRI_FIFO_MIN (long) 0
# endif /* !ACE_THR_PRI_FIFO_MIN */
# if !defined (ACE_THR_PRI_FIFO_MAX)
# define ACE_THR_PRI_FIFO_MAX (long) 59
# endif /* !ACE_THR_PRI_FIFO_MAX */
# if !defined (ACE_THR_PRI_RR_MIN)
# define ACE_THR_PRI_RR_MIN (long) 0
# endif /* !ACE_THR_PRI_RR_MIN */
# if !defined (ACE_THR_PRI_RR_MAX)
# define ACE_THR_PRI_RR_MAX (long) 59
# endif /* !ACE_THR_PRI_RR_MAX */
# if !defined (ACE_THR_PRI_OTHER_MIN)
# define ACE_THR_PRI_OTHER_MIN (long) 0
# endif /* !ACE_THR_PRI_OTHER_MIN */
# if !defined (ACE_THR_PRI_OTHER_MAX)
# define ACE_THR_PRI_OTHER_MAX (long) 127
# endif /* !ACE_THR_PRI_OTHER_MAX */
# else
# if !defined (ACE_THR_PRI_FIFO_MIN)
# define ACE_THR_PRI_FIFO_MIN (long) ACE_PROC_PRI_FIFO_MIN
# endif /* !ACE_THR_PRI_FIFO_MIN */
# if !defined (ACE_THR_PRI_FIFO_MAX)
# define ACE_THR_PRI_FIFO_MAX (long) ACE_PROC_PRI_FIFO_MAX
# endif /* !ACE_THR_PRI_FIFO_MAX */
# if !defined (ACE_THR_PRI_RR_MIN)
# define ACE_THR_PRI_RR_MIN (long) ACE_PROC_PRI_RR_MIN
# endif /* !ACE_THR_PRI_RR_MIN */
# if !defined (ACE_THR_PRI_RR_MAX)
# define ACE_THR_PRI_RR_MAX (long) ACE_PROC_PRI_RR_MAX
# endif /* !ACE_THR_PRI_RR_MAX */
# if !defined (ACE_THR_PRI_OTHER_MIN)
# define ACE_THR_PRI_OTHER_MIN (long) ACE_PROC_PRI_OTHER_MIN
# endif /* !ACE_THR_PRI_OTHER_MIN */
# if !defined (ACE_THR_PRI_OTHER_MAX)
# define ACE_THR_PRI_OTHER_MAX (long) ACE_PROC_PRI_OTHER_MAX
# endif /* !ACE_THR_PRI_OTHER_MAX */
# endif
# if !defined(ACE_THR_PRI_FIFO_DEF)
# define ACE_THR_PRI_FIFO_DEF ((ACE_THR_PRI_FIFO_MIN + ACE_THR_PRI_FIFO_MAX)/2)
# endif
# if !defined(ACE_THR_PRI_RR_DEF)
# define ACE_THR_PRI_RR_DEF ((ACE_THR_PRI_RR_MIN + ACE_THR_PRI_RR_MAX)/2)
# endif
# if !defined(ACE_THR_PRI_OTHER_DEF)
# define ACE_THR_PRI_OTHER_DEF ((ACE_THR_PRI_OTHER_MIN + ACE_THR_PRI_OTHER_MAX)/2)
# endif
// Typedefs to help compatibility with Windows NT and Pthreads.
typedef pthread_t ACE_hthread_t;
typedef pthread_t ACE_thread_t;
// native TSS key type
typedef pthread_key_t ACE_OS_thread_key_t;
// TSS key type to be used by application
# if defined (ACE_HAS_TSS_EMULATION)
typedef u_int ACE_thread_key_t;
# else /* ! ACE_HAS_TSS_EMULATION */
typedef ACE_OS_thread_key_t ACE_thread_key_t;
# endif /* ! ACE_HAS_TSS_EMULATION */
# if !defined (ACE_LACKS_COND_T)
typedef pthread_mutex_t ACE_mutex_t;
typedef pthread_cond_t ACE_cond_t;
typedef pthread_condattr_t ACE_condattr_t;
typedef pthread_mutexattr_t ACE_mutexattr_t;
# endif /* ! ACE_LACKS_COND_T */
typedef pthread_mutex_t ACE_thread_mutex_t;
# define THR_CANCEL_DISABLE 0x00000100
# define THR_CANCEL_ENABLE 0x00000200
# define THR_CANCEL_DEFERRED 0x00000400
# define THR_CANCEL_ASYNCHRONOUS 0x00000800
# if !defined (PTHREAD_CREATE_JOINABLE)
# if defined (PTHREAD_CREATE_UNDETACHED)
# define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED
# else
# define PTHREAD_CREATE_JOINABLE 0
# endif /* PTHREAD_CREATE_UNDETACHED */
# endif /* PTHREAD_CREATE_JOINABLE */
# if !defined (PTHREAD_CREATE_DETACHED)
# define PTHREAD_CREATE_DETACHED 1
# endif /* PTHREAD_CREATE_DETACHED */
# if !defined (PTHREAD_PROCESS_PRIVATE) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM)
# if defined (PTHREAD_MUTEXTYPE_FAST)
# define PTHREAD_PROCESS_PRIVATE PTHREAD_MUTEXTYPE_FAST
# else
# define PTHREAD_PROCESS_PRIVATE 0
# endif /* PTHREAD_MUTEXTYPE_FAST */
# endif /* PTHREAD_PROCESS_PRIVATE */
# if !defined (PTHREAD_PROCESS_SHARED) && !defined (ACE_HAS_PTHREAD_PROCESS_ENUM)
# if defined (PTHREAD_MUTEXTYPE_FAST)
# define PTHREAD_PROCESS_SHARED PTHREAD_MUTEXTYPE_FAST
# else
# define PTHREAD_PROCESS_SHARED 1
# endif /* PTHREAD_MUTEXTYPE_FAST */
# endif /* PTHREAD_PROCESS_SHARED */
# if !defined (ACE_HAS_STHREADS)
# if !defined (USYNC_THREAD)
# define USYNC_THREAD PTHREAD_PROCESS_PRIVATE
# endif /* ! USYNC_THREAD */
# if !defined (USYNC_PROCESS)
# define USYNC_PROCESS PTHREAD_PROCESS_SHARED
# endif /* ! USYNC_PROCESS */
# endif /* ACE_HAS_STHREADS */
/* MM-Graz: prevent warnings */
# undef THR_BOUND
# undef THR_NEW_LWP
# undef THR_DETACHED
# undef THR_SUSPENDED
# undef THR_DAEMON
# define THR_BOUND 0x00000001
# define THR_NEW_LWP 0x00000002
# define THR_DAEMON 0x00000010
# define THR_DETACHED 0x00000040
# define THR_SUSPENDED 0x00000080
# define THR_SCHED_FIFO 0x00020000
# define THR_SCHED_RR 0x00040000
# define THR_SCHED_DEFAULT 0x00080000
# define THR_JOINABLE 0x00010000
# define THR_SCOPE_SYSTEM 0x00100000
# define THR_SCOPE_PROCESS 0x00200000
# define THR_INHERIT_SCHED 0x00400000
# define THR_EXPLICIT_SCHED 0x00800000
# define THR_SCHED_IO 0x01000000
# if !defined (ACE_HAS_STHREADS)
# if !defined (ACE_HAS_POSIX_SEM) && !defined (ACE_USES_FIFO_SEM)
// This needs to be moved out of here.
#include /**/ "ace/ACE_export.h"
/**
* @class ACE_sema_t
*
* @brief This is used to implement semaphores for platforms that support
* POSIX pthreads, but do *not* support POSIX semaphores, i.e.,
* it's a different type than the POSIX <sem_t>.
*/
class ACE_Export ACE_sema_t
{
public:
/// Serialize access to internal state.
ACE_mutex_t lock_;
/// Block until there are no waiters.
ACE_cond_t count_nonzero_;
/// Count of the semaphore.
u_long count_;
/// Number of threads that have called <ACE_OS::sema_wait>.
u_long waiters_;
};
# endif /* !ACE_HAS_POSIX_SEM */
# if defined (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD)
// If we are on Solaris we can just reuse the existing
// implementations of these synchronization types.
# if !defined (ACE_LACKS_RWLOCK_T) && !defined (ACE_HAS_PTHREADS_UNIX98_EXT)
# include /**/ <synch.h>
typedef rwlock_t ACE_rwlock_t;
# endif /* !ACE_LACKS_RWLOCK_T */
# include /**/ <thread.h>
# endif /* (ACE_LACKS_PTHREAD_YIELD) && defined (ACE_HAS_THR_YIELD) */
# else
# if !defined (ACE_HAS_POSIX_SEM)
typedef sema_t ACE_sema_t;
# endif /* !ACE_HAS_POSIX_SEM */
# endif /* !ACE_HAS_STHREADS */
# if defined (ACE_HAS_PTHREADS_UNIX98_EXT)
typedef pthread_rwlock_t ACE_rwlock_t;
# endif /* ACE_HAS_PTHREADS_UNIX98_EXT */
# if defined (__GLIBC__) && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
// glibc 2.2.x or better has pthread_mutex_timedlock()
# ifndef ACE_HAS_MUTEX_TIMEOUTS
# define ACE_HAS_MUTEX_TIMEOUTS
# endif /* ACE_HAS_MUTEX_TIMEOUTS */
// Use new pthread_attr_setstack if XPG6 support is enabled.
# if defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600
# define ACE_LACKS_PTHREAD_ATTR_SETSTACK
# endif /* (_XOPEN_SOURCE - 0) < 600 */
# if !defined (_XOPEN_SOURCE) \
|| (defined (_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) < 600)
// pthread_mutex_timedlock() prototype is not visible if _XOPEN_SOURCE
// is not >= 600 (i.e. for XPG6).
extern "C" int pthread_mutex_timedlock (pthread_mutex_t *mutex,
const struct timespec * abstime);
# endif /* _XOPEN_SOURCE && _XOPEN_SOURCE < 600 */
# endif /* ACE_LINUX && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) */
#elif defined (ACE_HAS_STHREADS)
# if !defined (ACE_THR_PRI_FIFO_MIN)
# define ACE_THR_PRI_FIFO_MIN (long) 0
# endif /* !ACE_THR_PRI_FIFO_MIN */
# if !defined (ACE_THR_PRI_FIFO_MAX)
# define ACE_THR_PRI_FIFO_MAX (long) 59
# endif /* !ACE_THR_PRI_FIFO_MAX */
# if !defined (ACE_THR_PRI_RR_MIN)
# define ACE_THR_PRI_RR_MIN (long) 0
# endif /* !ACE_THR_PRI_RR_MIN */
# if !defined (ACE_THR_PRI_RR_MAX)
# define ACE_THR_PRI_RR_MAX (long) 59
# endif /* !ACE_THR_PRI_RR_MAX */
# if !defined (ACE_THR_PRI_OTHER_MIN)
# define ACE_THR_PRI_OTHER_MIN (long) 0
# endif /* !ACE_THR_PRI_OTHER_MIN */
# if !defined (ACE_THR_PRI_OTHER_MAX)
# define ACE_THR_PRI_OTHER_MAX (long) 127
# endif /* !ACE_THR_PRI_OTHER_MAX */
#endif /* ACE_HAS_PTHREADS */
#include /**/ "ace/post.h"
#endif /* ACE_OS_INCLUDE_OS_PTHREAD_H */
| [
"root@wow.playstar.se"
] | root@wow.playstar.se |
83e3285c72a26947b776be5d166514490ab11152 | ef0d2c235368ac55b816056ba9b29cf5b70bca37 | /Cluster.h | 692421547d9923107044d85e5c93fb61afa99f3d | [] | no_license | stephenwike/ucd-csci-2312-pa4 | a779ca179823cd442095934872039a577643291b | c22d4f161b209765214702b1e12226c37019499d | refs/heads/master | 2021-01-10T03:28:43.573370 | 2015-12-15T20:45:56 | 2015-12-15T20:45:56 | 45,935,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,804 | h | //
// Created by Stephen on 11/10/2015.
//
#ifndef PA4_CLUSTER_H
#define PA4_CLUSTER_H
#include <forward_list>
#include <unordered_map>
#include "Point.h"
namespace Clustering {
//Forward declarations of Cluster friend functions
template<typename T, int dim> class Cluster;
template<typename T, int dim>
bool operator==(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
bool operator!=(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
const Cluster<T,dim> operator+(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
const Cluster<T,dim> operator-(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
const Cluster<T,dim> operator+(const Cluster<T,dim> &, const T &);
template<typename T, int dim>
const Cluster<T,dim> operator-(const Cluster<T,dim> &, const T &);
template<typename T, int dim>
std::ostream &operator<<(std::ostream &, const Cluster<T,dim> &);
template<typename T, int dim>
std::istream &operator>>(std::istream &, Cluster<T,dim> &);
template<typename T, int dim>
double interClusterDistance(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
double interClusterEdges(const Cluster<T,dim> &, const Cluster<T,dim> &);
template<typename T, int dim>
class Cluster {
//Centroid Class
class Centroid : public T{
T __centroid;
unsigned int __dimension;
public:
Centroid() :
__dimension(dim),
__centroid(T(false))
{}
const T get() const{
return __centroid;
}
void set(const T &point){
__centroid = point;
}
};
int c_dim;
Centroid c_cent;
unsigned int c_size = 0;
unsigned int c_id;
bool c_valid = false;
public:
static const char CLUSTER_VALUE_DELIM = ':';
static std::unordered_map<unsigned int,double> distMap;
std::forward_list<T> c_points;
//Move Class
class Move{
public:
T m_point;
Cluster<T,dim> *from;
Cluster<T,dim> *to;
Move() {};
Move(const T &p, Cluster *f, Cluster *t) : m_point(p), from(f), to(t) {};
void perform(){
from->remove(m_point);
to->add(m_point);
};
};
//Constructor, Copy, Assignment
Cluster();
Cluster(const Cluster &);
Cluster &operator=(const Cluster &);
~Cluster() { };
//Setters and Getters
unsigned int getSize() const { return c_size; };
void setSize(unsigned int s) { c_size = s; };
unsigned int getId() const { return c_id; };
void setId(unsigned int i) { c_id = i; };
bool getValid() const { return c_valid; };
void setValid(bool v) { c_valid = v; };
T getCent() const { return c_cent.get(); };
void setCent(const T point) { c_cent.set(point); };
//Selector Operators
T &operator[](int index) {
auto it = c_points.begin();
for (std::size_t i = 0; i < index; i++){
it++;
}
return *it;
}
//Comparison Operators
friend bool operator==<>(const Cluster &, const Cluster &);
friend bool operator!=<>(const Cluster &, const Cluster &);
//Arithmetic Operators
Cluster &operator+=(const Cluster &); // Cluster Union
Cluster &operator-=(const Cluster &); // Cluster Difference (Asymmetric)
Cluster &operator+=(const T &); // Add Point
Cluster &operator-=(const T &); // Remove Point
friend const Cluster operator+<>(const Cluster &, const Cluster &);
friend const Cluster operator-<>(const Cluster &, const Cluster &);
friend const Cluster operator+<>(const Cluster &, const T &);
friend const Cluster operator-<>(const Cluster &, const T &);
//IOStream Operators
friend std::ostream &operator<<<>(std::ostream &, const Cluster &);
friend std::istream &operator>><>(std::istream &, Cluster &);
//Functions
void add(const T &);
const T &remove(const T &);
void computeCentroid();
void pickPoints(int k, Cluster&);
//Functions for Kmeans Algorithm
double intraClusterDistance() const;
friend double interClusterDistance<>(const Cluster &, const Cluster &);
friend double interClusterEdges<>(const Cluster &, const Cluster &);
int getClusterEdges();
};
};
#include "Cluster.cpp"
#endif //PA4_CLUSTER_H
| [
"stephen.c.wise@gmail.com"
] | stephen.c.wise@gmail.com |
3dde442748e40248dda13b8402ed0515905f5a9d | 8920a382ae9904eb851ea33f7df2940e94bfc22b | /Arrays/N-BonnaciNumbers.cpp | 4fb03813b1b1b5141e440694ce4730f3f3985639 | [] | no_license | Kushagra-Kapoor25/Revising-CPP | d7f8a4a34503d2fecc5b6e234598a70e5ca57434 | 4b3e7039325248e69995eeff9caa24f99f5616c0 | refs/heads/main | 2023-07-18T23:47:33.185037 | 2021-09-09T03:54:55 | 2021-09-09T03:54:55 | 394,882,243 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 4, m = 10;
int arr[m] = {0};
for (int i = 0; i < n - 1; i++)
arr[i] = 0;
arr[n - 1] = 1;
int s = arr[n - 1];
for (int i = 0; i < m; i++)
{
arr[n + i] = s;
s += arr[n + i] - arr[i];
}
for (int i = 0; i < m; i++)
cout << arr[i] << " ";
return 0;
} | [
"kushagrakapoor27@gmail.com"
] | kushagrakapoor27@gmail.com |
259ed0bff3da33080c54b0e710dcd8350facb106 | e46a8ed6a3dfe2fb6e29cccaf2ce9916f629da42 | /MyMario/Utils.h | 872668d045ca7ebc5e5abaeb0929f90b762febff | [] | no_license | salprince/MyMario | 56ca696eaa284eb4694f33091c0f5d90c03e8b37 | 9bf965e96a5ab04c2c5824ed4a9fa8e02d76b75f | refs/heads/master | 2023-02-17T10:46:12.743782 | 2021-01-22T18:58:52 | 2021-01-22T18:58:52 | 305,434,686 | 0 | 0 | null | 2020-10-25T18:34:03 | 2020-10-19T15:45:59 | C++ | UTF-8 | C++ | false | false | 347 | h | #pragma once
#include <Windows.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <stdlib.h>
#include <vector>
#include <string>
using namespace std;
void DebugOut(wchar_t* fmt, ...);
vector<string> split(string line, string delimeter = "\t");
wstring ToWSTR(string st);
LPCWSTR ToLPCWSTR(string st);
| [
"18520265@gm.uit.edu.vn"
] | 18520265@gm.uit.edu.vn |
4281c59900ea4d944cfaaf60f7f22bfe3c9e6e01 | 4b65a00a678db582fa1082721368f82de897faf1 | /src/univalue/lib/univalue.cpp | 46be6507bbbcf3f5ee762c0951b64ed08aab0c6d | [
"MIT",
"Apache-2.0"
] | permissive | smirnoffalexx/pocketnet.core | c79d3461ebf11c6477a0feb12d2fad1962017c0a | e30f54eee61625f51e2ff9aead46790d56e8d7a6 | refs/heads/master | 2023-06-27T04:41:28.973297 | 2021-06-24T01:03:50 | 2021-06-24T01:03:50 | 378,153,766 | 0 | 0 | Apache-2.0 | 2021-06-18T13:07:53 | 2021-06-18T13:07:53 | null | UTF-8 | C++ | false | false | 4,547 | cpp | // Copyright 2014 BitPay Inc.
// Copyright 2015 Pocketcoin Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <iomanip>
#include <sstream>
#include <stdlib.h>
#include "univalue.h"
const UniValue NullUniValue;
void UniValue::clear()
{
typ = VNULL;
val.clear();
keys.clear();
values.clear();
}
bool UniValue::setNull()
{
clear();
return true;
}
bool UniValue::setBool(bool val_)
{
clear();
typ = VBOOL;
if (val_)
val = "1";
return true;
}
static bool validNumStr(const std::string& s)
{
std::string tokenVal;
unsigned int consumed;
enum jtokentype tt = getJsonToken(tokenVal, consumed, s.data(), s.data() + s.size());
return (tt == JTOK_NUMBER);
}
bool UniValue::setNumStr(const std::string& val_)
{
if (!validNumStr(val_))
return false;
clear();
typ = VNUM;
val = val_;
return true;
}
bool UniValue::setInt(uint64_t val_)
{
std::ostringstream oss;
oss << val_;
return setNumStr(oss.str());
}
bool UniValue::setInt(int64_t val_)
{
std::ostringstream oss;
oss << val_;
return setNumStr(oss.str());
}
bool UniValue::setFloat(double val_)
{
std::ostringstream oss;
oss << std::setprecision(16) << val_;
bool ret = setNumStr(oss.str());
typ = VNUM;
return ret;
}
bool UniValue::setStr(const std::string& val_)
{
clear();
typ = VSTR;
val = val_;
return true;
}
bool UniValue::setArray()
{
clear();
typ = VARR;
return true;
}
bool UniValue::setObject()
{
clear();
typ = VOBJ;
return true;
}
bool UniValue::push_back(const UniValue& val_)
{
if (typ != VARR)
return false;
values.push_back(val_);
return true;
}
bool UniValue::push_backV(const std::vector<UniValue>& vec)
{
if (typ != VARR)
return false;
values.insert(values.end(), vec.begin(), vec.end());
return true;
}
void UniValue::__pushKV(const std::string& key, const UniValue& val_)
{
keys.push_back(key);
values.push_back(val_);
}
bool UniValue::pushKV(const std::string& key, const UniValue& val_)
{
if (typ != VOBJ)
return false;
size_t idx;
if (findKey(key, idx))
values[idx] = val_;
else
__pushKV(key, val_);
return true;
}
bool UniValue::pushKVs(const UniValue& obj)
{
if (typ != VOBJ || obj.typ != VOBJ)
return false;
for (size_t i = 0; i < obj.keys.size(); i++)
__pushKV(obj.keys[i], obj.values.at(i));
return true;
}
void UniValue::getObjMap(std::map<std::string,UniValue>& kv) const
{
if (typ != VOBJ)
return;
kv.clear();
for (size_t i = 0; i < keys.size(); i++)
kv[keys[i]] = values[i];
}
bool UniValue::findKey(const std::string& key, size_t& retIdx) const
{
for (size_t i = 0; i < keys.size(); i++) {
if (keys[i] == key) {
retIdx = i;
return true;
}
}
return false;
}
bool UniValue::checkObject(const std::map<std::string,UniValue::VType>& t) const
{
if (typ != VOBJ)
return false;
for (std::map<std::string,UniValue::VType>::const_iterator it = t.begin();
it != t.end(); ++it) {
size_t idx = 0;
if (!findKey(it->first, idx))
return false;
if (values.at(idx).getType() != it->second)
return false;
}
return true;
}
const UniValue& UniValue::operator[](const std::string& key) const
{
if (typ != VOBJ)
return NullUniValue;
size_t index = 0;
if (!findKey(key, index))
return NullUniValue;
return values.at(index);
}
const UniValue& UniValue::operator[](size_t index) const
{
if (typ != VOBJ && typ != VARR)
return NullUniValue;
if (index >= values.size())
return NullUniValue;
return values.at(index);
}
const char *uvTypeName(UniValue::VType t)
{
switch (t) {
case UniValue::VNULL: return "null";
case UniValue::VBOOL: return "bool";
case UniValue::VOBJ: return "object";
case UniValue::VARR: return "array";
case UniValue::VSTR: return "string";
case UniValue::VNUM: return "number";
}
// not reached
return NULL;
}
const UniValue& find_value(const UniValue& obj, const std::string& name)
{
for (unsigned int i = 0; i < obj.keys.size(); i++)
if (obj.keys[i] == name)
return obj.values.at(i);
return NullUniValue;
}
| [
"andy.oknen@gmail.com"
] | andy.oknen@gmail.com |
df0bb8c8c761c95fca87ae329696b93f747e8c07 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /media/filters/ffmpeg_video_decoder.cc | 9d8b1c23fbfaeca3a936e79c74316e0b891ef268 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 14,686 | cc | // Copyright (c) 2012 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 "media/filters/ffmpeg_video_decoder.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/decoder_buffer.h"
#include "media/base/limits.h"
#include "media/base/media_log.h"
#include "media/base/timestamp_constants.h"
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/ffmpeg/ffmpeg_decoding_loop.h"
namespace media {
// Returns the number of threads given the FFmpeg CodecID. Also inspects the
// command line for a valid --video-threads flag.
static int GetFFmpegVideoDecoderThreadCount(const VideoDecoderConfig& config) {
// Most codecs are so old that more threads aren't really needed.
int desired_threads = limits::kMinVideoDecodeThreads;
// Some ffmpeg codecs don't actually benefit from using more threads.
// Only add more threads for those codecs that we know will benefit.
switch (config.codec()) {
case kUnknownVideoCodec:
case kCodecVC1:
case kCodecMPEG2:
case kCodecHEVC:
case kCodecVP9:
case kCodecAV1:
case kCodecDolbyVision:
// We do not compile ffmpeg with support for any of these codecs.
break;
case kCodecTheora:
case kCodecMPEG4:
// No extra threads for these codecs.
break;
case kCodecH264:
case kCodecVP8:
// Normalize to three threads for 1080p content, then scale linearly
// with number of pixels.
// Examples:
// 4k: 12 threads
// 1440p: 5 threads
// 1080p: 3 threads
// anything lower than 1080p: 2 threads
desired_threads = config.coded_size().width() *
config.coded_size().height() * 3 / 1920 / 1080;
}
return VideoDecoder::GetRecommendedThreadCount(desired_threads);
}
static int GetVideoBufferImpl(struct AVCodecContext* s,
AVFrame* frame,
int flags) {
FFmpegVideoDecoder* decoder = static_cast<FFmpegVideoDecoder*>(s->opaque);
return decoder->GetVideoBuffer(s, frame, flags);
}
static void ReleaseVideoBufferImpl(void* opaque, uint8_t* data) {
if (opaque)
static_cast<VideoFrame*>(opaque)->Release();
}
// static
bool FFmpegVideoDecoder::IsCodecSupported(VideoCodec codec) {
return avcodec_find_decoder(VideoCodecToCodecID(codec)) != nullptr;
}
FFmpegVideoDecoder::FFmpegVideoDecoder(MediaLog* media_log)
: media_log_(media_log), state_(kUninitialized), decode_nalus_(false) {
DVLOG(1) << __func__;
thread_checker_.DetachFromThread();
}
int FFmpegVideoDecoder::GetVideoBuffer(struct AVCodecContext* codec_context,
AVFrame* frame,
int flags) {
// Don't use |codec_context_| here! With threaded decoding,
// it will contain unsynchronized width/height/pix_fmt values,
// whereas |codec_context| contains the current threads's
// updated width/height/pix_fmt, which can change for adaptive
// content.
const VideoPixelFormat format =
AVPixelFormatToVideoPixelFormat(codec_context->pix_fmt);
if (format == PIXEL_FORMAT_UNKNOWN)
return AVERROR(EINVAL);
DCHECK(format == PIXEL_FORMAT_I420 || format == PIXEL_FORMAT_I422 ||
format == PIXEL_FORMAT_I444 || format == PIXEL_FORMAT_YUV420P9 ||
format == PIXEL_FORMAT_YUV420P10 || format == PIXEL_FORMAT_YUV422P9 ||
format == PIXEL_FORMAT_YUV422P10 || format == PIXEL_FORMAT_YUV444P9 ||
format == PIXEL_FORMAT_YUV444P10 || format == PIXEL_FORMAT_YUV420P12 ||
format == PIXEL_FORMAT_YUV422P12 || format == PIXEL_FORMAT_YUV444P12);
gfx::Size size(codec_context->width, codec_context->height);
const int ret = av_image_check_size(size.width(), size.height(), 0, NULL);
if (ret < 0)
return ret;
gfx::Size natural_size;
if (codec_context->sample_aspect_ratio.num > 0) {
natural_size = GetNaturalSize(size,
codec_context->sample_aspect_ratio.num,
codec_context->sample_aspect_ratio.den);
} else {
natural_size =
GetNaturalSize(gfx::Rect(size), config_.GetPixelAspectRatio());
}
// FFmpeg has specific requirements on the allocation size of the frame. The
// following logic replicates FFmpeg's allocation strategy to ensure buffers
// are not overread / overwritten. See ff_init_buffer_info() for details.
//
// When lowres is non-zero, dimensions should be divided by 2^(lowres), but
// since we don't use this, just DCHECK that it's zero.
DCHECK_EQ(codec_context->lowres, 0);
gfx::Size coded_size(std::max(size.width(), codec_context->coded_width),
std::max(size.height(), codec_context->coded_height));
// FFmpeg expects the initial allocation to be zero-initialized. Failure to
// do so can lead to uninitialized value usage. See http://crbug.com/390941
scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(
format, coded_size, gfx::Rect(size), natural_size, kNoTimestamp);
if (!video_frame)
return AVERROR(EINVAL);
// Prefer the color space from the codec context. If it's not specified (or is
// set to an unsupported value), fall back on the value from the config.
VideoColorSpace color_space = AVColorSpaceToColorSpace(
codec_context->colorspace, codec_context->color_range);
if (!color_space.IsSpecified())
color_space = config_.color_space_info();
video_frame->set_color_space(color_space.ToGfxColorSpace());
if (codec_context->codec_id == AV_CODEC_ID_VP8 &&
codec_context->color_primaries == AVCOL_PRI_UNSPECIFIED &&
codec_context->color_trc == AVCOL_TRC_UNSPECIFIED &&
codec_context->colorspace == AVCOL_SPC_BT470BG) {
// vp8 has no colorspace information, except for the color range.
// However, because of a comment in the vp8 spec, ffmpeg sets the
// colorspace to BT470BG. We detect this and treat it as unset.
// If the color range is set to full range, we use the jpeg color space.
if (codec_context->color_range == AVCOL_RANGE_JPEG) {
video_frame->set_color_space(gfx::ColorSpace::CreateJpeg());
}
} else if (codec_context->color_primaries != AVCOL_PRI_UNSPECIFIED ||
codec_context->color_trc != AVCOL_TRC_UNSPECIFIED ||
codec_context->colorspace != AVCOL_SPC_UNSPECIFIED) {
media::VideoColorSpace video_color_space = media::VideoColorSpace(
codec_context->color_primaries, codec_context->color_trc,
codec_context->colorspace,
codec_context->color_range != AVCOL_RANGE_MPEG
? gfx::ColorSpace::RangeID::FULL
: gfx::ColorSpace::RangeID::LIMITED);
video_frame->set_color_space(video_color_space.ToGfxColorSpace());
}
for (size_t i = 0; i < VideoFrame::NumPlanes(video_frame->format()); i++) {
frame->data[i] = video_frame->data(i);
frame->linesize[i] = video_frame->stride(i);
}
frame->width = coded_size.width();
frame->height = coded_size.height();
frame->format = codec_context->pix_fmt;
frame->reordered_opaque = codec_context->reordered_opaque;
// Now create an AVBufferRef for the data just allocated. It will own the
// reference to the VideoFrame object.
VideoFrame* opaque = video_frame.get();
opaque->AddRef();
frame->buf[0] =
av_buffer_create(frame->data[0],
VideoFrame::AllocationSize(format, coded_size),
ReleaseVideoBufferImpl,
opaque,
0);
return 0;
}
std::string FFmpegVideoDecoder::GetDisplayName() const {
return "FFmpegVideoDecoder";
}
void FFmpegVideoDecoder::Initialize(const VideoDecoderConfig& config,
bool low_delay,
CdmContext* /* cdm_context */,
InitCB init_cb,
const OutputCB& output_cb,
const WaitingCB& /* waiting_cb */) {
DVLOG(1) << __func__ << ": " << config.AsHumanReadableString();
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(config.IsValidConfig());
DCHECK(output_cb);
InitCB bound_init_cb = BindToCurrentLoop(std::move(init_cb));
if (config.is_encrypted()) {
std::move(bound_init_cb).Run(false);
return;
}
if (!ConfigureDecoder(config, low_delay)) {
std::move(bound_init_cb).Run(false);
return;
}
// Success!
config_ = config;
output_cb_ = output_cb;
state_ = kNormal;
std::move(bound_init_cb).Run(true);
}
void FFmpegVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer,
DecodeCB decode_cb) {
DVLOG(3) << __func__;
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(buffer.get());
DCHECK(decode_cb);
CHECK_NE(state_, kUninitialized);
DecodeCB decode_cb_bound = BindToCurrentLoop(std::move(decode_cb));
if (state_ == kError) {
std::move(decode_cb_bound).Run(DecodeStatus::DECODE_ERROR);
return;
}
if (state_ == kDecodeFinished) {
std::move(decode_cb_bound).Run(DecodeStatus::OK);
return;
}
DCHECK_EQ(state_, kNormal);
// During decode, because reads are issued asynchronously, it is possible to
// receive multiple end of stream buffers since each decode is acked. There
// are three states the decoder can be in:
//
// kNormal: This is the starting state. Buffers are decoded. Decode errors
// are discarded.
// kDecodeFinished: All calls return empty frames.
// kError: Unexpected error happened.
//
// These are the possible state transitions.
//
// kNormal -> kDecodeFinished:
// When EOS buffer is received and the codec has been flushed.
// kNormal -> kError:
// A decoding error occurs and decoding needs to stop.
// (any state) -> kNormal:
// Any time Reset() is called.
if (!FFmpegDecode(*buffer)) {
state_ = kError;
std::move(decode_cb_bound).Run(DecodeStatus::DECODE_ERROR);
return;
}
if (buffer->end_of_stream())
state_ = kDecodeFinished;
// VideoDecoderShim expects that |decode_cb| is called only after
// |output_cb_|.
std::move(decode_cb_bound).Run(DecodeStatus::OK);
}
void FFmpegVideoDecoder::Reset(base::OnceClosure closure) {
DVLOG(2) << __func__;
DCHECK(thread_checker_.CalledOnValidThread());
avcodec_flush_buffers(codec_context_.get());
state_ = kNormal;
// PostTask() to avoid calling |closure| inmediately.
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(closure));
}
FFmpegVideoDecoder::~FFmpegVideoDecoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ != kUninitialized)
ReleaseFFmpegResources();
}
bool FFmpegVideoDecoder::FFmpegDecode(const DecoderBuffer& buffer) {
// Create a packet for input data.
// Due to FFmpeg API changes we no longer have const read-only pointers.
AVPacket packet;
av_init_packet(&packet);
if (buffer.end_of_stream()) {
packet.data = NULL;
packet.size = 0;
} else {
packet.data = const_cast<uint8_t*>(buffer.data());
packet.size = buffer.data_size();
DCHECK(packet.data);
DCHECK_GT(packet.size, 0);
// Let FFmpeg handle presentation timestamp reordering.
codec_context_->reordered_opaque = buffer.timestamp().InMicroseconds();
}
switch (decoding_loop_->DecodePacket(
&packet, base::BindRepeating(&FFmpegVideoDecoder::OnNewFrame,
base::Unretained(this)))) {
case FFmpegDecodingLoop::DecodeStatus::kSendPacketFailed:
MEDIA_LOG(ERROR, media_log_)
<< "Failed to send video packet for decoding: "
<< buffer.AsHumanReadableString();
return false;
case FFmpegDecodingLoop::DecodeStatus::kFrameProcessingFailed:
// OnNewFrame() should have already issued a MEDIA_LOG for this.
return false;
case FFmpegDecodingLoop::DecodeStatus::kDecodeFrameFailed:
MEDIA_LOG(DEBUG, media_log_)
<< GetDisplayName() << " failed to decode a video frame: "
<< AVErrorToString(decoding_loop_->last_averror_code()) << ", at "
<< buffer.AsHumanReadableString();
return false;
case FFmpegDecodingLoop::DecodeStatus::kOkay:
break;
}
return true;
}
bool FFmpegVideoDecoder::OnNewFrame(AVFrame* frame) {
// TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675
// The decoder is in a bad state and not decoding correctly.
// Checking for NULL avoids a crash in CopyPlane().
if (!frame->data[VideoFrame::kYPlane] || !frame->data[VideoFrame::kUPlane] ||
!frame->data[VideoFrame::kVPlane]) {
DLOG(ERROR) << "Video frame was produced yet has invalid frame data.";
return false;
}
scoped_refptr<VideoFrame> video_frame =
reinterpret_cast<VideoFrame*>(av_buffer_get_opaque(frame->buf[0]));
video_frame->set_timestamp(
base::TimeDelta::FromMicroseconds(frame->reordered_opaque));
video_frame->metadata()->SetBoolean(VideoFrameMetadata::POWER_EFFICIENT,
false);
output_cb_.Run(video_frame);
return true;
}
void FFmpegVideoDecoder::ReleaseFFmpegResources() {
decoding_loop_.reset();
codec_context_.reset();
}
bool FFmpegVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config,
bool low_delay) {
DCHECK(config.IsValidConfig());
DCHECK(!config.is_encrypted());
// Release existing decoder resources if necessary.
ReleaseFFmpegResources();
// Initialize AVCodecContext structure.
codec_context_.reset(avcodec_alloc_context3(NULL));
VideoDecoderConfigToAVCodecContext(config, codec_context_.get());
codec_context_->thread_count = GetFFmpegVideoDecoderThreadCount(config);
codec_context_->thread_type =
FF_THREAD_SLICE | (low_delay ? 0 : FF_THREAD_FRAME);
codec_context_->opaque = this;
codec_context_->get_buffer2 = GetVideoBufferImpl;
if (decode_nalus_)
codec_context_->flags2 |= AV_CODEC_FLAG2_CHUNKS;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
if (!codec || avcodec_open2(codec_context_.get(), codec, NULL) < 0) {
ReleaseFFmpegResources();
return false;
}
decoding_loop_.reset(new FFmpegDecodingLoop(codec_context_.get()));
return true;
}
} // namespace media
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
bdb4e2f15df25e94aa7559c191de3623befbcb79 | ffde62396112ecbf34ebbba357e32cb288b2b5b9 | /Source/Components.h | 3b6e3f781bce4c06aeabb7577316f1220b384a10 | [] | no_license | gostopa1/ApresMIDI | 5fe484575971ea545d6c3f2f1d4fce9d89cfba6e | ce1bc9f8626c78b33012cf6ca89ade643187c649 | refs/heads/master | 2020-05-15T04:37:54.930513 | 2019-11-13T13:09:31 | 2019-11-13T13:09:31 | 182,090,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,179 | h | /*
==============================================================================
Components.h
Created: 6 Oct 2019 1:42:46pm
Author: Athanasios Gotsopoulos
==============================================================================
*/
#pragma once
class Analyzer : public Component
{
public:
TextButton loadButton;
Analyzer(ApresMidiAudioProcessor * proc)
{
processor = proc;
addAndMakeVisible(loadButton);
loadButton.setButtonText("Analyze track");
loadButton.onClick = [this]
{
processor->m1.is_ready = 0;
processor->m1.reset();
processor->m1.analyze_track();
processor->m1.is_ready = 1;
};
}
void paint (Graphics& g) override
{
Path p1;
float offset=0.01;
float rounding=10;
p1.addRoundedRectangle(offset*getWidth(),offset*getHeight(),(1-2*offset)*getWidth(),(1-2*offset)*getHeight(),rounding);
g.setColour(Colours::darkblue);
g.fillPath(p1);
loadButton.setBounds(0,0,getWidth(),getHeight());
};
private:
ApresMidiAudioProcessor* processor;
};
class FileComp : public Component
{
public:
TextButton loadButton;
FileComp(ApresMidiAudioProcessor * proc)
{
processor = proc;
addAndMakeVisible(loadButton);
loadButton.setButtonText("Choose file...");
loadButton.onClick = [this]
{
FileChooser chooser ("Load a MIDI file",
{},
"*.mid");
if (chooser.browseForFileToOpen())
{
File file = chooser.getResult();
processor->m1.is_ready = 0;
processor->m1.reset();
processor->m1.analyze_file((const char *)file.getFullPathName().toUTF8());
processor->m1.analyze_track();
processor->m1.is_ready = 1;
}
};
}
void paint (Graphics& g) override
{
Path p1;
float offset=0.01;
float rounding=10;
p1.addRoundedRectangle(offset*getWidth(),offset*getHeight(),(1-2*offset)*getWidth(),(1-2*offset)*getHeight(),rounding);
g.setColour(Colours::darkblue);
g.fillPath(p1);
loadButton.setBounds(0,0,getWidth(),0.2*getHeight());
};
private:
ApresMidiAudioProcessor* processor;
};
class PianoRoll : public Component
{
public:
Slider speed_slider;
PianoRoll(ApresMidiAudioProcessor * proc)
{
processor = proc;
}
void paint (Graphics& g) override
{
Path p1;
float offset=0.01;
float rounding=10;
p1.addRoundedRectangle(offset*getWidth(),offset*getHeight(),(1-2*offset)*getWidth(),(1-2*offset)*getHeight(),rounding);
g.setColour(Colours::darkblue);
g.fillPath(p1);
addAndMakeVisible(speed_slider);
speed_slider.setBounds(4*offset*getWidth(),offset*getHeight(),(1-2*4*offset)*getWidth(),(1-2*offset)*getHeight());
};
private:
ApresMidiAudioProcessor* processor;
};
class GenerateMarkov : public Component
{
public:
Slider speed_slider;
GenerateMarkov(ApresMidiAudioProcessor * proc) : processor(proc)
{
//processor = proc; // This is the same as the initializer above
}
void paint (Graphics& g) override
{
Path p1;
float offset=0.01;
float rounding=10;
p1.addRoundedRectangle(offset*getWidth(),offset*getHeight(),(1-2*offset)*getWidth(),(1-2*offset)*getHeight(),rounding);
//g.setColour(Colours::darkblue);
//g.fillPath(p1);
addAndMakeVisible(speed_slider);
speed_slider.setBounds(4*offset*getWidth(),offset*getHeight(),(1-2*4*offset)*getWidth(),(1-2*offset)*getHeight());
};
private:
ApresMidiAudioProcessor* processor;
};
class PlayingComponent : public Component
{
public:
Slider speed_slider;
PlayingComponent(ApresMidiAudioProcessor * proc)
{
processor = proc;
addAndMakeVisible(speed_slider);
speed_slider.setRange(1, 1000, 1);
speed_slider.setValue(processor->m1.speed);
speed_slider.onValueChange = [this] {processor->m1.speed = speed_slider.getValue(); };
addAndMakeVisible(speed_slider);
}
void paint (Graphics& g) override
{
Path p1;
float offset=0.01;
float rounding=10;
p1.addRoundedRectangle(offset*getWidth(),offset*getHeight(),(1-2*offset)*getWidth(),(1-2*offset)*getHeight(),rounding);
//g.setColour(Colours::darkblue);
//g.fillPath(p1);
speed_slider.setBounds(4*offset*getWidth(),offset*getHeight(),(1-2*4*offset)*getWidth(),(1-2*offset)*getHeight());
g.setColour(Colours::white);
g.drawFittedText("Duration", offset*getWidth(), 0.20*getHeight(), (1-2*offset)*getWidth(), getHeight() , Justification::centredTop, 1);
};
private:
ApresMidiAudioProcessor* processor;
};
| [
"tanilas@hotmail.com"
] | tanilas@hotmail.com |
d44abb70fb95a48eecc03d47681c337c7add985b | dc27a0ae3e5689d353ca138496e520d5564df0b6 | /Source/Arpg/Private/Item/ManualPickup.cpp | 60c15e7fed7a376f765f8cb328ceb290599f8b28 | [] | no_license | el-freeman/UE4_InventorySystem_TopDownTemplate | 69db17cef262a2d91d88ad3c18c78d2878f6ae37 | a6a8a45c2028508c34d77c8735005c9b7541744f | refs/heads/master | 2020-03-16T19:49:07.864961 | 2019-04-05T14:07:32 | 2019-04-05T14:07:32 | 132,933,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "ManualPickup.h"
#include "ArpgPlayerController.h"
AManualPickup::AManualPickup()
{
Super::Name = "Item";
Super::Action = "pickup";
}
void AManualPickup::Interact_Implementation(APlayerController * Controller)
{
Super::Interact_Implementation(Controller);
AArpgPlayerController* IController = Cast<AArpgPlayerController>(Controller);
if (IController->AddItemToInventoryByID(ItemID))
Destroy();
}
| [
"kbsdb112@gmail.com"
] | kbsdb112@gmail.com |
6de8ea2ebf63566fe4d4e6730dd4a2bffa901d07 | 8e57405aa788e066f60d907d4e5fa78f9386c973 | /divDy1/4/alpha.water | 1eb190474f21f51f0faa7f80fdb99d6c776d08a8 | [] | no_license | daihui-lu/dynamicMesh | 06394bdf1538d6ce95ff9d836ecf7ff2b2917820 | 7cf4fc5f0c84b19dc330083cf4899677017383fc | refs/heads/master | 2020-03-22T03:55:07.843849 | 2018-07-02T15:38:58 | 2018-07-02T15:38:58 | 139,460,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82,360 | water | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "4";
object alpha.water;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField nonuniform List<scalar>
8941
(
1.09782
0.960789
1.00418
0.9793
0.999026
1.02395
0.292856
-1.54925e-21
-1.61562e-20
9.82503e-21
2.17582e-18
7.11187e-20
1.85009e-22
3.35441e-26
3.56906e-30
1.25344e-33
5.18782e-37
2.2933e-40
1.00341e-43
4.03893e-47
1.97068e-50
8.24787e-54
3.68103e-57
1.35684e-60
8.34055e-64
1.06859e-66
3.60873e-70
6.50245e-74
3.36486e-76
5.63362e-80
5.8068e-83
8.71998e-87
1.51289e-89
5.50105e-92
2.15199e-95
1.46196e-98
4.35171e-102
2.11302e-104
4.36664e-108
3.72333e-112
5.73023e-115
1.16827e-117
1.25178e-120
3.07755e-123
6.26696e-127
5.53541e-130
8.79708e-134
1.2776e-137
3.72237e-139
2.40389e-142
1.08405
0.84966
1.00428
1.01776
0.961356
1.02726
0.668453
-2.82775e-19
-6.83226e-20
1.51098e-16
3.93639e-18
8.58253e-21
3.85641e-23
2.28839e-26
1.96811e-30
5.1287e-34
2.10132e-37
8.92244e-41
3.81232e-44
1.58259e-47
6.70936e-51
2.85142e-54
1.36416e-57
6.04213e-61
2.28678e-64
1.15513e-67
6.38151e-71
2.11353e-74
1.43207e-77
6.27573e-81
3.2537e-84
8.77397e-87
1.19846e-90
2.49118e-93
6.6795e-97
7.4164e-100
3.22399e-103
2.72989e-107
1.00502e-108
9.08227e-112
1.13692e-115
1.13863e-118
1.86789e-122
3.14063e-126
7.12231e-129
7.53119e-132
5.83967e-136
1.41953e-139
5.96766e-143
8.54292e-144
1.00199
1.04511
1.02217
0.998172
0.973664
0.997703
1.00027
-7.9402e-16
-1.36991e-18
-6.86485e-37
1.90361e-17
1.56594e-18
4.71533e-21
3.88933e-25
3.40708e-29
1.24619e-32
5.24358e-36
2.51633e-39
1.08448e-42
4.02992e-46
1.88244e-49
7.5742e-53
4.46946e-56
1.29177e-59
1.04766e-62
9.04468e-66
5.66157e-69
6.13047e-73
2.41746e-75
3.31819e-78
2.4951e-82
4.22099e-86
4.39673e-87
5.68535e-90
4.80817e-94
1.7906e-97
7.20939e-101
8.29581e-105
1.09126e-106
5.56984e-110
2.37326e-113
1.02174e-116
1.35151e-119
1.16494e-123
1.85037e-126
9.41012e-131
1.23276e-132
1.62645e-135
9.50308e-140
9.3055e-144
1.01562
1.01769
1.02232
1.04831
1.00121
0.996082
0.999804
0.000633983
-8.88846e-19
-1.26983e-21
4.74895e-18
7.76852e-19
1.29714e-20
1.39325e-23
1.07812e-27
1.89664e-31
7.48354e-35
3.3439e-38
1.3444e-41
5.59602e-45
2.50738e-48
9.96117e-52
9.38775e-55
3.76074e-58
1.68068e-61
7.29041e-65
1.66324e-68
1.01526e-70
3.65329e-74
2.99843e-78
2.19986e-80
1.84964e-83
2.98395e-87
7.38307e-91
3.44902e-93
8.17085e-97
2.74869e-100
4.23814e-103
1.46142e-105
1.15213e-108
1.73796e-112
4.00603e-115
1.34532e-118
1.18976e-121
1.61639e-124
6.3235e-128
3.97314e-132
3.94824e-135
3.18499e-138
9.02526e-141
1.02341
1.05946
1.00919
0.976903
0.936274
0.997746
1.00189
0.310922
-8.00951e-18
-2.50536e-20
1.63101e-17
4.585e-18
1.10583e-19
1.96086e-22
2.28846e-26
3.16447e-30
1.11105e-33
4.79095e-37
2.03341e-40
1.08441e-43
3.58599e-47
2.58915e-50
6.98488e-54
3.70158e-57
1.37471e-60
1.30817e-63
4.92781e-67
5.06794e-70
1.61077e-72
7.49411e-76
7.05766e-79
7.58352e-83
3.18969e-85
5.0128e-89
5.58477e-93
5.35605e-96
3.81449e-98
1.19323e-101
8.0706e-106
8.80003e-109
4.39959e-112
7.92743e-115
2.62304e-117
3.95465e-120
1.31457e-123
2.61757e-127
2.5283e-129
1.22037e-132
1.02373e-135
1.34407e-139
1.00129
0.970123
1
1.20397
1.01158
0.982678
1.00186
0.485102
-3.09728e-18
-2.3586e-20
1.23066e-17
3.60575e-18
8.70699e-20
1.56792e-22
1.84161e-26
2.4055e-30
8.89538e-34
5.58489e-37
1.94103e-40
1.44421e-43
4.5418e-47
1.67377e-50
6.05233e-54
1.27591e-56
3.62961e-60
2.08386e-62
6.0319e-66
5.93622e-70
2.932e-72
9.48271e-75
6.69268e-78
7.17228e-82
1.03719e-85
9.9613e-89
2.19327e-91
3.07193e-95
3.35015e-98
5.19544e-101
4.72636e-105
1.84789e-107
1.50921e-110
3.89658e-113
1.70009e-116
4.20809e-120
8.47391e-124
1.51767e-126
1.40367e-130
2.80257e-134
1.03032e-137
2.69608e-141
1.0108
1.00511
0.858856
0.987619
0.947277
1.01801
1.00367
0.179009
-3.12817e-19
-4.84874e-22
4.48196e-18
7.29426e-19
1.2008e-20
1.25293e-23
9.51885e-28
1.69853e-31
6.68704e-35
2.85761e-38
1.19996e-41
5.15522e-45
3.44881e-48
9.58025e-52
5.13444e-55
1.72895e-58
1.44686e-61
3.36745e-65
1.23632e-68
2.04359e-71
8.0772e-74
1.36584e-77
1.71103e-81
7.16645e-84
6.26944e-88
9.34614e-91
3.41237e-94
6.41135e-97
1.3517e-100
5.92563e-103
4.70545e-106
4.99324e-109
4.71481e-113
6.13191e-116
3.75442e-119
1.76286e-122
1.58203e-125
3.19539e-129
3.86444e-131
1.2807e-134
7.07934e-139
1.39083e-140
0.99403
1.00477
0.964707
0.900778
1.0259
1.02069
1.00175
-2.81722e-16
-1.05051e-18
-5.28066e-38
1.84097e-17
1.4977e-18
5.12302e-21
5.00769e-25
4.06297e-29
1.4392e-32
6.00792e-36
2.54501e-39
1.17833e-42
5.60717e-46
2.04188e-49
1.33005e-52
6.5301e-56
1.49098e-59
5.68644e-63
2.64833e-65
2.33875e-68
1.87974e-72
3.62805e-76
7.01596e-78
2.03058e-81
1.60022e-84
1.26849e-87
2.06933e-91
1.26138e-94
5.71555e-97
6.20343e-101
8.39609e-104
5.83872e-107
7.69838e-110
1.84535e-113
1.41607e-116
1.25383e-119
6.21849e-123
2.6755e-126
1.4999e-130
4.47457e-134
1.72975e-137
6.76711e-141
7.55987e-144
1.05463
0.833144
0.940095
1.01718
0.909207
0.985048
1.00004
-7.92291e-18
-4.45277e-20
1.30205e-16
6.72531e-18
1.79706e-20
3.47521e-23
2.44277e-26
3.11386e-30
7.54512e-34
3.08228e-37
1.3178e-40
5.68198e-44
2.40423e-47
1.0097e-50
4.36513e-54
1.81156e-57
7.75555e-61
6.21729e-64
1.45093e-67
5.81779e-71
2.61912e-74
1.13213e-77
5.22473e-81
3.55385e-83
5.20554e-87
6.86974e-91
2.20484e-94
2.16366e-96
5.54687e-100
4.16601e-103
3.79438e-107
7.6698e-111
1.00978e-112
1.11979e-115
2.15611e-118
5.56233e-122
1.25345e-125
9.65803e-129
3.21059e-132
1.23904e-134
1.57596e-137
2.37526e-140
2.0236e-144
1.01419
1.01739
1.04767
1.01553
1.00714
1.00966
0.704202
-2.23073e-19
-1.92335e-19
2.86537e-22
1.85374e-18
1.0534e-19
3.3216e-22
6.37281e-26
6.35812e-30
2.10946e-33
8.77134e-37
3.72718e-40
1.59159e-43
7.17975e-47
2.8906e-50
1.21462e-53
5.10779e-57
2.13316e-60
9.68528e-64
3.98036e-67
2.75573e-70
9.94232e-74
2.75297e-76
9.15355e-80
4.39527e-83
7.11071e-86
3.97628e-89
2.64817e-92
2.56598e-96
4.45488e-99
7.74611e-102
1.40547e-105
7.81395e-108
2.07203e-111
1.70732e-115
5.75196e-119
1.04747e-120
4.77291e-124
1.07426e-127
2.2545e-130
3.34355e-134
5.80507e-137
6.5005e-141
4.25907e-144
1.04486
0.925762
0.997249
0.939746
1.00134
1.01988
0.30803
5.18497e-13
1.23507e-15
6.0161e-18
5.16298e-18
5.3314e-19
6.69299e-21
8.88948e-24
1.84062e-27
5.60592e-31
3.96157e-34
2.97422e-37
2.15476e-40
1.54496e-43
1.10769e-46
7.93018e-50
5.66238e-53
4.03573e-56
2.86981e-59
2.03567e-62
1.44182e-65
1.01896e-68
7.18108e-72
5.05044e-75
3.54267e-78
2.47865e-81
1.7318e-84
1.20745e-87
8.40421e-91
5.8373e-94
4.04249e-97
2.79139e-100
1.92447e-103
1.32499e-106
9.10203e-110
6.23999e-113
4.26755e-116
2.91155e-119
1.98262e-122
1.34657e-125
9.12448e-129
6.17598e-132
4.17015e-135
1.66292e-138
1.10436
0.999895
1.00155
1.05597
1.01516
1.03588
0.667069
6.0514e-13
3.34952e-15
8.43163e-15
4.81587e-16
7.29852e-19
4.08332e-22
2.76532e-25
8.15588e-29
3.8651e-32
2.83192e-35
2.09885e-38
1.50993e-41
1.08422e-44
7.80233e-48
5.58028e-51
4.02665e-54
2.87532e-57
2.03452e-60
1.44497e-63
1.02821e-66
7.27126e-70
5.11668e-73
3.60239e-76
2.53887e-79
1.77905e-82
1.24694e-85
8.71931e-89
6.03557e-92
4.19126e-95
2.9067e-98
2.00762e-101
1.3847e-104
9.52371e-108
6.54019e-111
4.47712e-114
3.06243e-117
2.09312e-120
1.42208e-123
9.65703e-127
6.56262e-130
4.42781e-133
2.98665e-136
1.19366e-139
1.04527
1.05683
1.01193
0.945352
0.946897
1
1.00051
9.27458e-10
6.76458e-16
1.97916e-16
3.25258e-16
5.13503e-17
6.46872e-19
4.004e-22
3.43014e-26
1.50226e-29
1.11975e-32
7.94506e-36
5.52634e-39
3.83761e-42
2.663e-45
1.84487e-48
1.2753e-51
8.80462e-55
6.06287e-58
4.16722e-61
2.86066e-64
1.95883e-67
1.33867e-70
9.14795e-74
6.23943e-77
4.2481e-80
2.88927e-83
1.96006e-86
1.32519e-89
8.95462e-93
6.0419e-96
4.06765e-99
2.73464e-102
1.83401e-105
1.22735e-108
8.20173e-112
5.4726e-115
3.64607e-118
2.42626e-121
1.61166e-124
1.06807e-127
7.06389e-131
4.66189e-134
1.82391e-137
1.02355
1.02357
1.01243
1.02493
1.01478
0.998491
0.999534
0.00252483
1.08219e-13
1.41247e-16
3.85061e-17
7.55832e-18
3.19067e-19
1.61815e-21
6.57023e-25
9.67468e-29
5.40996e-32
4.03401e-35
2.89773e-38
2.0473e-41
1.44464e-44
1.01767e-47
7.14946e-51
5.02265e-54
3.51416e-57
2.45537e-60
1.71302e-63
1.19332e-66
8.31133e-70
5.75154e-73
3.97834e-76
2.74772e-79
1.8925e-82
1.30127e-85
8.94033e-89
6.12202e-92
4.1864e-95
2.8572e-98
1.94483e-101
1.32121e-104
8.96409e-108
6.08881e-111
4.11225e-114
2.77646e-117
1.86247e-120
1.25061e-123
8.37925e-127
5.6061e-130
3.74209e-133
1.47877e-136
1.02566
1.05074
0.999256
1.00159
0.994631
1.00465
1.00227
0.323698
1.01239e-12
1.34946e-15
1.25227e-16
8.44329e-17
6.17221e-18
5.54337e-20
3.93467e-23
4.98161e-27
2.16517e-30
1.61476e-33
1.1681e-36
8.23682e-40
5.79601e-43
4.07515e-46
2.85791e-49
2.00166e-52
1.39878e-55
9.75199e-59
6.79016e-62
4.71795e-65
3.26961e-68
2.26169e-71
1.56162e-74
1.07554e-77
7.39806e-81
5.07592e-84
3.47511e-87
2.37601e-90
1.62081e-93
1.10279e-96
7.49204e-100
5.08138e-103
3.44059e-106
2.32596e-109
1.56843e-112
1.05503e-115
7.0857e-119
4.75015e-122
3.17689e-125
2.1215e-128
1.41392e-131
5.57508e-135
1.15553
1.05783
0.834496
0.993035
1.01251
1
1.00244
0.486698
9.0047e-13
1.49516e-15
3.92636e-16
1.66861e-16
1.3208e-17
1.29434e-19
9.66813e-23
1.18819e-26
4.99523e-30
3.7231e-33
2.69091e-36
1.89442e-39
1.33032e-42
9.3372e-46
6.53921e-49
4.57102e-52
3.18822e-55
2.21833e-58
1.54236e-61
1.07008e-64
7.40638e-68
5.11741e-71
3.52539e-74
2.42261e-77
1.6641e-80
1.14077e-83
7.7983e-87
5.32281e-90
3.6254e-93
2.46423e-96
1.67273e-99
1.13301e-102
7.65815e-106
5.16865e-109
3.48064e-112
2.33781e-115
1.56764e-118
1.04891e-121
7.00192e-125
4.67033e-128
3.11103e-131
1.22643e-134
1.07638
1.00278
0.823831
1.00616
0.945834
1.01937
1.00292
0.185795
1.06569e-13
1.28305e-16
2.89693e-17
5.2247e-18
2.05084e-19
9.9865e-22
4.07461e-25
6.35723e-29
3.5428e-32
2.62158e-35
1.8719e-38
1.32051e-41
9.36691e-45
6.62846e-48
4.62651e-51
3.264e-54
2.28957e-57
1.58867e-60
1.10777e-63
7.72139e-67
5.37638e-70
3.76042e-73
2.58438e-76
1.7843e-79
1.23224e-82
8.48569e-86
5.88746e-89
4.00764e-92
2.73861e-95
1.8803e-98
1.28487e-101
8.68516e-105
5.89045e-108
3.9953e-111
2.70178e-114
1.82504e-117
1.22721e-120
8.24346e-124
5.61018e-127
3.71179e-130
2.48121e-133
1.06281e-136
1.0446
1.03388
1.24529
1.00751
1.01707
1.03419
1.0021
8.86211e-07
1.4067e-15
3.03392e-16
3.93091e-16
6.45562e-17
9.21283e-19
6.72764e-22
5.90967e-26
2.38825e-29
1.78181e-32
1.26812e-35
8.82904e-39
6.13661e-42
4.26297e-45
2.95546e-48
2.04445e-51
1.41239e-54
9.73871e-58
6.70025e-61
4.602e-64
3.15428e-67
2.15732e-70
1.47445e-73
1.00667e-76
6.8582e-80
4.66369e-83
3.16361e-86
2.14154e-89
1.44825e-92
9.77446e-96
6.58307e-99
4.42951e-102
2.97359e-105
1.992e-108
1.33226e-111
8.89394e-115
5.92468e-118
3.9419e-121
2.61736e-124
1.73322e-127
1.14642e-130
7.57738e-134
2.9684e-137
1.07906
0.991086
0.983639
1.00545
0.983413
0.934279
1.00025
1.40265e-10
6.77374e-15
6.84522e-15
7.811e-16
5.36422e-18
1.51423e-21
1.94117e-25
8.91121e-29
6.08433e-32
4.22104e-35
2.85049e-38
1.92204e-41
1.31337e-44
9.0428e-48
6.23179e-51
4.29221e-54
2.94063e-57
2.11189e-60
1.42404e-63
9.54276e-67
6.5439e-70
4.54063e-73
3.0572e-76
2.14815e-79
1.42786e-82
9.88085e-86
6.57872e-89
4.45003e-92
3.02504e-95
2.04896e-98
1.38236e-101
9.3121e-105
6.27983e-108
4.22779e-111
2.84759e-114
1.9216e-117
1.27852e-120
8.58607e-124
5.83907e-127
3.83589e-130
2.54211e-133
1.69304e-136
6.72836e-140
1.04269
1.06578
1.03928
1.03237
1.00545
1.00695
0.704402
1.42654e-12
5.84925e-15
7.33682e-18
3.22981e-18
2.58654e-19
2.55586e-21
2.70327e-24
5.46015e-28
1.94214e-31
1.39807e-34
1.05383e-37
7.6784e-41
5.53683e-44
3.98988e-47
2.87016e-50
2.05935e-53
1.47523e-56
1.05429e-59
7.5144e-63
5.34632e-66
3.79575e-69
2.68909e-72
1.90053e-75
1.33973e-78
9.41891e-82
6.60519e-85
4.62364e-88
3.2291e-91
2.25177e-94
1.56613e-97
1.08619e-100
7.51654e-104
5.19358e-107
3.58011e-110
2.4627e-113
1.69009e-116
1.15709e-119
7.90685e-123
5.3895e-126
3.66531e-129
2.48986e-132
1.68644e-135
6.74167e-139
1.0364
0.956381
0.994159
0.931234
0.952802
1.00996
0.305942
-1.64759e-21
-1.54589e-20
-5.3359e-25
1.04516e-18
3.758e-20
9.96844e-23
2.04974e-26
2.1695e-30
7.74168e-34
3.0748e-37
1.33004e-40
6.15178e-44
3.92312e-47
1.26948e-50
6.09716e-54
2.85188e-57
8.69754e-61
7.03314e-64
9.08362e-67
3.03751e-70
9.76087e-74
1.07231e-76
1.71236e-80
9.97979e-83
5.69259e-86
2.18911e-89
4.29291e-92
1.88328e-95
6.82575e-99
5.78136e-102
5.94964e-105
5.12866e-109
6.90349e-111
3.25995e-114
3.14465e-118
1.31754e-120
2.03369e-124
8.18597e-128
5.32359e-130
1.25339e-133
1.03363e-136
1.33102e-139
2.23609e-142
1.0503
1.03929
1.04668
0.999891
0.992907
1.01596
0.66777
2.13284e-13
-6.69434e-20
1.48637e-16
4.32297e-18
1.04491e-20
4.66867e-23
2.84523e-26
2.45498e-30
6.30938e-34
2.58132e-37
1.0955e-40
4.64373e-44
1.94166e-47
8.41702e-51
3.47133e-54
1.59423e-57
6.38523e-61
2.69945e-64
1.14787e-67
6.66524e-71
2.32871e-74
5.1983e-77
1.06769e-80
1.2378e-83
1.45157e-86
1.21344e-89
2.25211e-93
1.69682e-96
9.43503e-100
1.52289e-103
4.11533e-107
2.70306e-108
4.31772e-111
4.84441e-115
7.20571e-119
3.4491e-122
1.77271e-124
4.72805e-128
1.53303e-131
1.61022e-134
1.74822e-138
3.7861e-142
3.76179e-145
0.993113
1.03098
1.01962
0.984522
0.977385
1.00837
1.00053
4.79561e-10
-1.42671e-18
6.31076e-33
1.89885e-17
1.5625e-18
4.72922e-21
3.95742e-25
3.50804e-29
1.27998e-32
5.36277e-36
2.44034e-39
1.15356e-42
4.03707e-46
2.37019e-49
7.41164e-53
5.12744e-56
2.61754e-59
1.52629e-62
3.24872e-66
5.67061e-69
7.38991e-73
2.51073e-76
3.39306e-78
7.47457e-82
5.29022e-86
1.72897e-89
4.29023e-91
1.54937e-94
1.40474e-97
7.30843e-101
2.73934e-104
2.46555e-107
6.53024e-111
3.49637e-113
8.15298e-117
1.35598e-120
2.87216e-123
5.02565e-126
9.15416e-131
2.16377e-132
1.99321e-135
4.01782e-139
9.96989e-142
1.02645
1.01218
0.969986
1.01453
1.01529
1.00057
0.999842
0.00220161
-8.5447e-19
-1.19975e-21
4.90238e-18
8.03082e-19
1.34418e-20
1.44319e-23
1.11503e-27
1.96032e-31
7.73822e-35
3.32799e-38
1.37838e-41
5.83232e-45
2.46988e-48
1.00794e-51
4.97949e-55
3.63055e-58
1.32473e-61
5.90373e-65
1.51207e-68
1.74114e-70
1.25551e-73
7.74063e-78
1.89275e-80
1.80398e-83
3.17141e-87
5.35178e-91
1.50123e-93
2.62215e-97
3.45212e-100
4.45306e-103
2.87588e-107
2.04683e-109
1.50245e-112
2.93166e-115
3.45729e-118
2.04675e-121
1.36103e-124
6.19294e-128
4.30451e-131
2.88498e-135
6.59788e-139
2.5812e-142
1.00183
1.04166
0.917747
1.00006
0.994785
1.01672
1.00216
0.325353
-7.63327e-18
-2.42626e-20
1.66869e-17
4.74812e-18
1.15339e-19
2.05489e-22
2.40281e-26
3.16842e-30
1.15323e-33
4.88987e-37
2.43682e-40
9.64363e-44
3.60822e-47
1.62443e-50
7.25609e-54
3.78859e-57
2.74195e-60
3.81039e-63
4.59049e-67
1.13619e-70
7.69711e-74
5.91074e-76
5.44282e-79
3.39341e-83
1.62552e-85
6.73631e-89
6.67524e-92
7.60657e-96
5.07406e-98
1.17729e-101
4.41194e-104
2.79413e-107
2.36895e-111
1.19241e-113
5.00213e-117
1.26509e-120
1.13536e-123
1.60074e-127
3.78021e-129
2.08423e-132
6.93923e-136
1.41908e-138
1.05098
1.06814
0.973893
0.999998
1.00386
0.997636
1.0023
0.486357
-3.14336e-18
-2.24246e-20
1.22181e-17
3.69506e-18
8.9387e-20
1.6106e-22
1.89394e-26
2.47614e-30
9.16747e-34
4.07022e-37
1.70472e-40
2.68916e-43
5.0508e-47
4.92559e-50
1.34877e-53
5.15795e-57
1.76086e-60
5.5574e-64
5.88604e-67
1.23095e-70
3.84156e-74
4.36298e-75
6.81093e-78
4.29044e-81
5.21969e-85
2.26504e-88
2.79148e-92
5.05031e-95
2.54459e-98
5.38365e-101
5.63815e-105
1.30197e-107
1.1139e-110
2.08063e-114
1.0534e-116
5.23853e-120
1.63902e-123
1.34208e-127
3.86252e-131
1.85951e-132
1.09681e-135
4.21873e-140
1.02764
0.984924
0.703239
1.13903
0.885702
1.01771
1.00287
0.185525
-3.6967e-19
-4.96891e-22
4.36413e-18
7.08527e-19
1.16086e-20
1.21104e-23
9.21214e-28
1.64563e-31
6.47838e-35
2.8209e-38
1.17483e-41
4.95312e-45
3.8704e-48
1.0265e-51
4.26211e-55
2.31614e-58
1.1141e-61
8.80036e-65
1.84602e-68
7.2462e-72
7.09223e-74
3.00433e-77
2.18098e-81
9.37762e-85
2.8031e-88
6.57454e-91
1.82447e-93
4.97981e-97
7.27696e-101
4.22144e-103
9.45264e-107
1.041e-110
2.44633e-113
3.24471e-116
4.55307e-119
2.63856e-122
7.03692e-126
6.01611e-130
1.55464e-133
6.0204e-137
4.25001e-140
2.69222e-140
0.999606
1.06891
1.01999
0.996834
1.00946
1.04149
1.00204
6.88509e-07
-1.05182e-18
-5.28066e-38
1.84732e-17
1.51232e-18
5.22874e-21
5.16443e-25
4.15564e-29
1.46997e-32
6.19977e-36
2.57055e-39
1.23161e-42
5.32341e-46
2.0821e-49
1.35013e-52
8.73055e-56
1.54047e-59
2.50959e-62
3.69315e-66
1.68526e-68
1.91901e-71
1.28663e-75
9.56318e-79
4.83142e-82
4.93921e-85
1.23012e-87
4.61659e-91
5.7585e-95
1.68421e-97
7.63447e-101
4.06805e-104
5.59608e-107
2.71578e-109
2.51225e-113
5.17637e-116
2.29695e-119
6.21734e-123
2.65802e-126
2.07734e-130
6.70111e-134
2.60196e-137
1.01885e-140
3.56215e-144
1.03825
1.03367
0.999305
1.02993
0.927308
0.951021
1.00017
6.51567e-11
-4.44328e-20
1.39836e-16
7.48707e-18
1.96739e-20
3.1901e-23
2.14066e-26
2.78195e-30
6.87746e-34
2.80839e-37
1.19618e-40
5.14925e-44
2.19583e-47
9.20995e-51
3.95954e-54
1.65292e-57
7.09497e-61
2.99043e-64
1.89802e-67
5.59073e-71
2.34997e-74
9.14987e-78
3.95634e-81
2.2889e-83
3.3783e-87
3.62511e-90
3.73472e-93
2.42455e-96
8.83446e-100
3.61794e-103
2.29543e-106
1.71622e-110
1.1862e-112
1.69281e-116
2.22074e-120
2.76247e-122
3.79949e-125
8.64613e-129
2.24674e-132
3.99564e-135
4.60606e-138
2.64349e-140
5.45269e-144
1.01563
1.09369
1.00795
1.0492
1.01575
1.00855
0.705448
-2.39904e-19
-1.91252e-19
-2.405e-24
1.35082e-18
7.60909e-20
2.34091e-22
4.43413e-26
4.49975e-30
1.4952e-33
6.2349e-37
2.68546e-40
1.13415e-43
4.79141e-47
2.05629e-50
8.86782e-54
3.66071e-57
1.56093e-60
7.71556e-64
3.65079e-67
1.59493e-70
5.48675e-74
1.07049e-76
6.08542e-80
7.01641e-84
8.23241e-86
3.66148e-89
2.93696e-93
9.17403e-97
4.53783e-99
2.37728e-102
3.5893e-106
7.90722e-108
5.12375e-111
1.18542e-114
2.45712e-117
8.80555e-121
1.51541e-124
2.33772e-127
2.38919e-130
1.29554e-133
9.70444e-137
8.31583e-141
1.51165e-144
0.972057
1.0475
1.00045
1.0212
0.96511
1.04687
1.00132
1.00028
1.02198
1.00057
1.03489
1.00066
1.02514
1.00129
1.00133
0.993626
1.00218
0.996623
1.00174
0.99167
1.00234
1.00143
0.999124
1.00521
0.996741
1.00195
0.997813
1.00454
1.00403
0.995062
1.00267
1.0022
1.004
0.993745
1.0022
1.00183
1.02036
1.00541
0.998573
1.00141
1.02202
1.00567
1.00364
1.00929
1.00365
1.02127
1.00464
1.00331
1.00289
1.00468
0.999956
1.00124
1.03249
1.00444
1
1.00091
1.00028
1.00246
1
0.918185
1.00024
1.00098
1
1.00071
1
1
1.0072
1.0005
0.998389
0.999071
0.963666
1.04663
1.00139
1.01272
0.963154
1.02872
1.00111
1.00103
1.02538
1.00172
1.03023
1.00073
1.02499
1.00151
1.00232
1.00059
1.00297
1.00933
1.00186
0.999655
1.00236
1.0027
0.994837
1.00531
1
1.00235
0.996444
1.00365
1.00479
0.980726
1.00282
1.01832
1.0041
0.99761
1.00203
1.00167
1.0264
1.00594
0.993589
1.00163
1.02705
1.00562
1.00527
1.00166
1.00372
1.0184
1.00599
1.00011
1.0038
1.00467
0.997854
1.00119
1.04061
1.0046
1
1.0009
1.0004
1.00075
1
0.961777
1.00013
1.00082
1
1.00094
0.99637
0.998805
1.00652
1.00089
0.993775
0.998255
0.964622
1.02676
1.00115
1.00267
0.973331
1.02558
1.00059
1.00085
1.01185
1.00181
1.00029
1.00038
1
1.00139
1.00228
0.998917
1.00294
1.01401
1.00158
1
1.0021
1.00264
0.996809
1.00456
0.990284
1.00188
0.99686
1.00336
1.00451
0.988039
1.00267
1.0183
1.00392
1
1.00233
1.00195
1.02664
1.00577
0.982748
1.00183
1.02916
1.0055
1.00574
1.00102
1.00317
1.01635
1.00624
1.00361
1.00371
1.0048
1
1.00111
1.04004
1.0051
0.996556
1.00119
1.00018
1.00076
1
1
1.00028
1.00022
1
1.00094
0.993556
0.99918
1.0118
1.00031
0.998718
1
0.961524
0.995639
1.05927
0.998968
0.987395
1.0095
1.05875
1.00942
1.00625
1.02937
1.02335
1.02232
1.00975
1.00529
-2.92266e-20
0.536439
-1.11293e-17
0.305722
4.01712e-10
0.53542
4.01712e-10
1.03118
1.00074
0.999876
0.994835
1.02266
0.99887
1.02845
1.01595
1.01493
1.04241
1.02921
1.01494
1.05709
1.01693
-1.58168e-20
1
-2.33554e-17
0.667966
1.85885e-10
1.00003
1.23047e-08
1.00015
1.02009
0.957571
0.94687
1.00368
0.998089
0.993868
0.992227
1.00169
0.921317
0.994159
1.00152
0.943216
0.996874
-5.05683e-19
1.00114
0.172124
1.00096
4.35337e-07
1.00107
0.1803
0.923907
0.975042
0.982242
0.996373
0.945791
0.960075
0.970749
1.00028
1.00157
0.969824
0.996226
1.00295
0.964706
1.00011
0.467033
1.00007
0.920641
0.999879
0.468243
1.00013
0.918156
0.999152
0.971743
0.834143
0.974274
0.999584
0.975263
0.873196
0.993359
1.00283
0.976772
1.00061
1.00306
0.97089
0.992498
0.984038
1.00188
1.00014
1.00239
0.974518
1.00229
1.00012
0.933879
1.00525
0.97382
1.0117
0.928732
1.03574
0.993136
1.0001
1.00005
0.993584
0.986464
1.00019
0.998017
1.00007
1.00019
1.00361
0.979807
1.00267
1.00012
1.0042
0.970323
0.983256
1.11364
1.04387
0.948749
0.990114
1.07805
1.03302
1.01492
1.01811
1.00234
1.03019
1.01832
1.03579
1.01342
0.903784
1.0018
0.458247
1.00413
0.902242
1.00207
0.460412
0.949124
0.870924
0.945107
1.02522
0.958319
0.997324
0.950078
1.00942
1.01144
1.04056
1.03801
1.0129
1.0377
1.00789
0.204311
1.00027
-8.61659e-20
1.00233
0.212257
1.00035
2.04337e-06
0.856378
1.01804
1.00249
0.989018
0.843926
1.00796
0.999647
0.997512
1
0.984684
0.969928
0.999905
0.995633
0.996422
-8.33407e-21
0.840403
-8.43594e-20
1.00032
5.12791e-08
0.841331
5.35628e-10
0.995716
1
0.966052
1.01595
0.995559
0.994685
0.943696
1.0043
1.01183
0.997513
1.00954
1.01167
0.996698
1.00401
-1.8725e-17
0.350402
-2.54034e-19
0.705351
2.18995e-09
0.354017
2.18995e-09
0.993851
1.02888
1.0426
0.96062
1
1.0108
1.03874
1.00543
1.00512
1.03794
1.01922
1.01134
1.03377
1.00563
1.49816e-09
0.53521
1.33988e-09
0.308354
1.40363e-09
0.535289
1.33988e-09
1.03946
0.999547
1.02146
1
1.05377
1.00586
1.00016
1.00687
1.01213
1.06411
1.03655
1.00727
1.01122
1.06027
3.93005e-10
1.00017
2.1032e-08
0.667586
3.94843e-10
1.00005
2.10472e-08
0.995427
0.968282
1.00081
0.997887
1.01126
0.972417
1.0025
0.998999
1.00227
0.95398
1.00845
0.995108
1.00269
0.953908
6.41076e-07
1.00154
0.179754
1.00112
6.37719e-07
1.00107
0.179941
0.986624
1.002
0.992608
1.01748
1
1.00151
0.974473
1.00116
1.00487
0.970767
0.998422
1.00107
1.00477
0.984877
0.468019
0.999719
0.919037
0.999809
0.468177
1.00086
0.919149
0.999959
1
0.872643
0.997271
0.998004
0.99979
0.870923
0.997655
1.00328
0.970237
1.0087
0.998688
1.00401
0.97049
0.976243
1.00253
1.00016
1.00265
0.976225
1.0025
1.00006
0.890139
0.992093
1.06063
1.00205
0.943949
0.919918
1.03562
1.0006
1
1.00413
1
1.00052
1
1.0046
1.00022
1.00456
0.971373
1.00287
1.00006
1.00441
0.970989
1.00003
1.09013
1.09524
0.890957
0.915634
1.21309
1.00812
1.01814
1.01858
1.01423
1.01051
1.01783
1.01892
1.00023
0.902387
1.00174
0.460264
1.00329
0.903518
1.00181
0.460127
1.01541
0.938141
0.961612
1.07458
1.00436
0.855403
0.976203
1.01581
1.0125
1.04178
1.03818
1.01517
1.01246
1.0398
0.211374
1.00078
2.97827e-06
1.00241
0.212224
1.00037
2.97762e-06
0.931307
1.0409
0.994296
0.986446
0.80571
0.991538
0.997686
0.992144
0.999199
0.987075
0.962362
0.984085
0.994206
0.983947
8.30586e-08
0.841615
9.80117e-10
1.00041
8.32407e-08
0.841526
9.92582e-10
0.998581
0.974943
0.945505
1.00933
0.999486
0.993581
0.973827
1.00483
1.01006
1.00094
1.0065
1.00502
1.01032
1.00042
6.37695e-09
0.354814
6.37695e-09
0.705129
6.37695e-09
0.355838
6.37695e-09
1
0.99793
1.03902
0.95683
0.98799
0.985797
1.03113
1.00201
1.00416
1.02429
1.00706
1.00413
1.01165
1.00356
3.88167e-10
0.535422
3.88167e-10
0.290875
-5.45194e-20
0.535661
-7.39025e-18
1
0.952751
0.988623
1.01341
0.981764
0.996367
0.979008
0.998324
1.00882
0.938493
1.00778
0.998991
1.00849
0.910559
1.85644e-10
1.00017
1.23449e-08
0.668151
-1.41081e-20
1
-2.29026e-17
1.01551
1
0.996744
0.939147
0.998972
0.98474
0.952258
0.998656
1.00402
0.994065
1.0101
0.997678
1.00434
0.993983
4.32148e-07
1.00149
0.179906
1.00033
-5.0118e-19
1.00116
0.171952
1.01005
1.00374
0.973773
1.01522
0.980835
1.00168
0.97062
1.00227
1.00444
0.998369
1.00228
1.00103
1.00498
1.00101
0.468525
0.999846
0.917601
0.99991
0.466993
1.00056
0.921024
0.997561
0.992098
0.871774
0.998529
1
0.954827
0.828106
1.00067
1.0045
0.972939
1.01847
1.00043
1.00457
0.992453
0.974926
1.0024
1.00023
1.00197
0.984246
1.00171
1.00013
0.964207
1.00389
0.973608
1.00636
0.941572
1.01133
1.0652
1.001
0.997516
1.00459
0.977993
1.00084
0.999197
1.00658
1.00026
1.00451
0.970754
1.0021
1.00019
1.0035
0.980006
0.835876
1.23489
1.02023
0.970131
1.00795
1.11924
1.018
1.01873
1.01943
0.987424
1.00771
1.01904
1.02013
0.98343
0.902579
1.00195
0.460139
1.0033
0.902962
1.00171
0.45777
1.00625
0.887281
0.956493
1.02757
1.04434
0.987778
0.993614
1.01335
1.0138
1.042
1.04025
1.01605
1.01437
1.04235
0.211422
1.00071
2.0416e-06
1.00172
0.203772
1.00022
-2.56247e-19
0.808153
0.995173
0.997415
0.99326
0.672708
1.00815
0.979699
0.994652
1
0.994358
0.964591
0.994505
1.00001
0.966922
5.14957e-08
0.841637
5.11228e-10
1.00004
-1.88239e-16
0.839895
-9.48967e-20
1
0.994633
0.991898
1.0066
1.00223
0.982287
0.964163
1.00378
1.01292
0.999029
1.00585
1.00367
1.01308
0.999859
2.20399e-09
0.354128
2.20399e-09
0.706068
-1.97671e-17
0.35079
-3.65672e-19
1.00234
1.0005
0.985385
0.968502
0.980616
1.00213
1.00057
1.00842
1.00237
1.01817
1.04753
1.0223
1.0145
1.00733
1.00123
0.99806
1.00557
1.00114
0.993703
1.00587
1.00134
1.01274
1.02147
1.00554
1.0222
1.02359
1.01036
1.00587
1.00286
0.965841
1.0003
0.975125
0.977101
1.00253
1.00069
1.00616
1.04861
1.0295
1.0129
1.03534
1.01303
1.00419
1.00148
1.00161
0.988725
1.00617
0.991277
1.00611
1.00144
1.00606
1.00579
1.00105
1.00044
1.00591
1.00118
1.00631
1.01135
1.0365
1.00583
1.02507
1.03765
1.00531
1.01099
1.00242
1.00064
1.0013
1.00071
1.00085
1.00145
1.00276
1.01378
1.03261
1.01334
1.06622
1.01438
1.06947
1.00858
1.00587
1.00087
1.00541
1.00154
1.00574
1.00155
1.00533
1.01226
1.02484
1.03289
1.00611
1.03394
1.0052
1.01153
1.00256
1.00152
1.00102
1.00231
1.00138
1.00213
1.00222
1.00001
1.00174
1.0024
1.00155
1.002
1.0021
1.00147
0.982255
0.949734
1
0.993465
0.945498
1.00007
0.982135
1
1.00365
1.0022
1.0025
1.00114
1.0021
1.00013
0.993248
0.991518
1.00221
0.981046
1.00235
0.991879
0.989372
1
1.0023
1.00213
1.00217
1.00237
1.00246
1
0.981435
0.994378
0.978752
1.00021
0.952679
1.00028
0.979664
1.00003
1.00304
1.00263
1.0022
1.00155
1.0024
1
1.001
1.00063
1.00043
1.00352
1.00138
1.00182
1.00063
0.99809
0.977948
1.00077
0.998667
0.977784
1.00036
0.998071
1.00022
1.00165
1.00176
1.00934
1.00347
1.0014
1.00056
1.00013
0.996065
1.00426
0.962274
1.00425
0.981175
1.00063
1.00115
1.00328
1.00219
1.00346
1.00205
1.00309
1.00123
0.99785
0.996818
0.979628
1
0.975802
1
0.996364
1.00028
1.00979
1.00423
1.00216
1.00476
1.00179
1.00012
1.00277
1.00409
1.00454
1.0042
1.004
1.00424
1.00302
0.999987
0.990068
1
0.985662
0.988887
1
0.999992
1.00155
1.00342
1.00104
1.00244
1.00307
1.00073
1.00223
0.999913
1.00007
1.00302
0.970879
1.00222
0.971111
0.996781
1.00295
1.00485
1.0039
1.00388
1.00418
1.00453
1.00256
1
0.97648
0.988299
1
0.990243
1
1
1.00196
1.00286
1.00276
1.00069
1.0036
1.00107
1.00147
1.00076
1.00046
1.00268
1.00155
1.00037
1.00253
1.0011
0.998747
1.00257
1.01325
1.03745
1.00117
1.01355
1.00305
1.00299
1.00429
1.008
1.00548
1.004
1.00831
1.00448
1.00022
0.993308
1.00002
1.00258
1.00003
1.00308
1.00021
1.00091
1.00175
1.00021
1.00246
1.00041
1.00283
1.00044
1.00913
1.0319
1.00398
1.01431
1.00873
1.01451
1.00779
1.00667
1.00573
1.00479
1.00861
1.00511
1.00865
1.0072
1.01274
1.01001
1.00912
0.999728
1.01139
1.01073
1.01238
0.999487
0.944709
0.998163
1.01286
0.946811
0.991537
0.999631
1.00704
1.00515
1.00501
1.00227
1.00538
1.00552
1.00664
1.01611
1.02886
1.0184
1.03321
1.01825
1.05412
1.01698
1.01285
0.998909
1.01146
1.0107
1.01058
1.01014
1.0132
0.995343
1.00336
0.968886
0.997842
0.949056
0.991788
0.990051
1.00703
1.00242
1.00609
1.00642
1.0058
1.00666
1.0068
1.00745
1.01022
1.00286
1.00445
1.01001
1.00302
1.00794
1.0041
1.00537
1.00011
0.998301
1.00627
1.00024
1.00402
1.00622
1.0026
1.00245
1.00105
1.00248
1.00228
1.00642
1.01065
1.02669
1.01281
1.03696
1.01286
1.03911
1.01336
1.00719
1.00461
1.00957
1.00301
1.00986
1.00323
1.00717
1.00412
1
1.00843
1.00026
1.00688
1.00031
1.00422
1.00619
1.00129
1.00227
1.00243
1.00255
1.00258
1.00597
0.998197
1.00025
1
1.00032
1.00008
0.999987
0.999347
0.956185
1
1.00213
1.00128
0.999974
1.0012
0.943925
0.995634
1
0.998577
1
0.999997
0.998932
1
0.996797
0.981589
1
0.983266
0.999907
0.993999
0.984272
0.998529
1.00051
1.00002
0.999972
1.00009
0.999997
0.998515
0.991927
1.00058
0.995088
1.00025
0.995504
0.99984
0.991367
0.992222
1
0.999714
0.998369
0.999754
0.998435
0.991136
1.00179
1.00397
1.00017
1.00057
1.00398
1.00021
1.00161
1.00123
0.997317
1.0018
0.999337
0.99994
1.00118
1.00077
1.00087
1
1.00058
1
1.00001
1.00107
1.00071
1.00501
1.0082
1.01012
0.999411
1.01033
1.00099
1.00452
1.0021
1.00062
1.00476
1.00014
1.00465
1.00038
1.00202
1.00143
0.998179
1.00005
1.00022
0.998374
1.00133
1.00083
1.00107
0.998816
1
1.00046
1.00013
1.0008
1.00106
1.00196
1.00047
0.974371
0.963521
1.00281
0.975161
1.00036
1.00121
1.03724
1.01317
1.04472
1.00291
1.02527
1.01418
1.00099
0.987351
1.00622
1.00108
1.00137
0.98648
1.00632
1.00443
1.01555
1.00515
1.03768
1.0338
1.00464
1.00537
1.00188
0.963121
1.00063
0.977572
0.976484
1.00133
1.00065
0.999846
1.02524
1.00868
1.01603
1.00819
1.01508
0.998317
1.00068
1.00136
0.987909
1.00645
0.986877
1.00675
1
1.00513
1.00568
1.0021
1.00081
1.00545
1.0054
1.00198
1.00951
1.01541
1.00453
1.03696
1.01206
1.01328
1.00428
1.00298
1.00157
1.00247
1.00147
1.00306
1.00126
1.00243
1.00634
1.03909
1.00961
1
1.01038
1.03463
1.0034
1.00528
1.00124
1.00519
1.00223
1.00557
1.00247
1.00503
1.0075
1.03681
0.995413
1.00463
1.0067
1.00443
1.0031
1.0033
1.00178
1.0014
1.00315
1.00169
1.00293
1.00268
1.00068
1.00235
1.00262
1.00173
1.00049
1.00227
1.00177
0.976259
0.953465
1.00003
1.0019
0.981886
0.9535
1.00046
0.999947
1.00302
1.00253
1.0024
1
1.00089
1.00226
0.997059
1.00582
1.00406
0.983366
1.00306
0.96593
0.99857
1.00072
1.00218
1.00258
1.00236
1.00255
1.00209
1.00051
0.976488
0.998961
0.998798
1.00004
0.9799
1.00074
0.977015
1.00028
1.00302
1.00256
1.00228
1.00129
1.00257
1.00006
1.00167
1.0027
1.00379
1.00289
1.00152
1.00261
1.00345
0.99592
0.980913
0.999921
0.995169
0.993606
0.982045
1
1.00025
1.00414
1.00287
1.00605
1.00034
1.00387
1.00242
1.00116
1
1.00483
0.998806
1.00488
0.999484
1.00085
1.00181
1.00307
1.00296
1.00335
1.00294
1.00398
1.00171
0.999639
0.995557
0.977075
1.00074
0.97943
1.00035
1
1.00053
1.00764
1.00305
1.00253
1.00398
1.00262
1.00046
1.00234
1.0042
1.00433
1.00412
1.00271
1.00395
1.00389
1
0.986759
1
0.982858
0.999873
0.983576
0.999999
1.0015
1.00356
1.00104
1.0021
1.00194
1.00262
1.00082
0.997818
1.0128
1.00421
0.972974
1.00396
0.976193
1.00039
1.00248
1.00488
1.00392
1.00392
1.00419
1.00429
1.00257
0.999964
0.981508
0.993865
1
0.989168
1
1
1.00159
1.00281
1.00261
1.00078
1.0035
1.001
1.00123
1.00049
1.00024
1.00289
1.00146
1.00059
1.00009
1.0024
1.00876
1.01414
1.01491
1.02572
1.00903
1.01107
1.0152
1.00736
1.00532
1.00875
1.00572
1.00751
1.00504
1.00869
1.00071
0.998952
0.994812
1.00371
0.997772
1.00463
1.00059
1.00064
1.00179
0.999947
1.00245
1.00005
1.00283
1.00055
1.0088
0.99701
0.961694
1.01483
0.987791
1.01388
1.00945
1.00752
1.00587
1.00505
1.00819
1.0054
1.0086
1.00731
1.01318
1.01086
1.01009
1.00416
1.01299
1.0115
1.01136
0.99994
0.945062
1.00031
1.00213
0.99365
0.929243
1.00218
1.00728
1.00623
1.00673
1.0011
1.00695
1.00597
1.00666
1.01832
1.0101
1.01938
0.996045
1.01892
0.993666
1.01868
1.01295
1.00349
1.011
1.01124
1.0105
1.01071
1.01308
0.997961
1
0.937026
1.00472
0.937062
1.00358
1.00147
1.00758
1.00114
1.00615
1.00684
1.00604
1.00691
1.0077
1.00724
1.00956
1.00325
1.00449
1.00736
1.00933
1.00304
1.0042
1.00901
1.00023
0.999041
1.00421
1.0115
1.00026
1.00585
1.00256
1.0026
1.0009
1.00601
1.00224
1.0025
1.01818
1.03963
1.01307
1.04108
1.0127
1.04066
1.01581
1.00766
1.00472
1.00936
1.00325
1.00933
1.00335
1.00773
1.00433
1.00039
1.01336
1.00023
1.01275
1.00025
1.00483
1.00598
1.00113
1.00228
1.0025
1.0026
1.0026
1.00595
0.997526
1.00006
0.999932
1.00016
0.997352
1
0.999938
0.945552
0.986818
1.00042
1.00084
0.955652
0.981829
1.00168
0.980665
0.999571
0.99835
1
0.981465
0.999994
0.998593
0.99086
0.935881
1
0.859992
1
0.814204
0.992745
0.998101
1.00026
1
0.999553
1
0.99987
0.998251
0.945258
1.0014
0.963819
1.00117
0.970826
1.00276
0.945111
0.984449
1
0.999993
0.998182
0.999995
0.998017
0.976052
1.00201
1.00479
1.00031
1.00096
1.0023
1.0039
1.00021
1.00089
1
1.00002
0.994367
1.00128
1
1
1.00065
1.00003
1.00066
0.998584
1.00089
1
1.00021
1.00483
1.00728
1.01166
0.996567
1.01103
0.999065
1.00421
1.00205
1.00108
1.00277
1.00035
1.0034
1.00042
1.00182
1.001
0.992712
1
1
1
1.00094
1
1.00082
0.998822
1.00001
1.00044
1.00004
1.00071
1.00058
1.00089
1.00083
0.979504
0.96647
1.00135
0.98156
1.00071
0.999421
1.00978
1.0158
1.02587
0.998821
1.00127
1.01557
1
0.990118
1.00673
1.00075
1
0.992289
1.00645
1.00169
1.00387
1.00266
0.989383
1.00259
1.00029
1.00246
1.00095
0.969847
1.00058
0.991279
0.985775
1.00057
1.00073
1.00869
1.02609
1.01402
1.01543
1.01548
1.01601
1.00396
1.00181
1.00078
0.997312
1.00619
0.993897
1.00615
1.00053
1.005
1.00536
1.00263
1.00076
1.00519
1.0051
1.00225
1.00226
0.991116
1.00441
1.00268
1.00316
0.973015
1.00368
1.00259
1.00178
1.0035
1.00151
1.00291
1.00144
1.00343
1.00215
1.00382
1.00773
0.907772
1.00809
0.909226
0.998178
1.00545
1.001
1.0052
1.00206
1.00512
1.00237
1.0053
1.00246
1.00647
0.965691
1.0049
0.975638
1.00484
1.00277
1.00274
1.0015
1.00118
1.00381
1.00148
1.00365
1.00271
1.00034
1.00286
1.00279
1.0017
1.00044
1.00266
1.00168
0.984346
0.99395
0.999038
0.998691
0.99245
0.984931
0.999499
0.998773
1.0028
1.0026
1.00249
0.998557
1.00062
1.00226
0.999938
1.0135
1.00389
0.990316
1.00416
0.991003
1
1.00042
1.0018
1.00284
1.00203
1.00274
1.00189
1.00039
0.981645
0.999342
0.983634
1.00038
0.985572
0.999702
0.978866
0.999104
1.00257
1.00319
1.00206
1.00068
1.00222
1.00037
1.00191
1.00333
1.00392
1.00288
1.00188
1.0031
1.00333
0.999863
0.978372
1.00154
0.99674
1.00015
0.980347
1.00178
1.00051
1.00337
1.00313
1.00553
1.0007
1.00236
1.00281
1
0.989104
1.00618
0.984801
1.00434
0.990329
1.00264
1.00186
1.00357
1.00315
1.00121
1.0032
1.00265
1.00164
0.999732
0.997049
0.988411
1.00325
0.988422
1.00282
0.999999
1.00086
1.00666
1.00092
1.0026
1.0019
1.003
1.00067
1.0024
1.00405
1.00426
1.00419
1.00258
1.00378
1.00399
1.00014
0.99584
1
0.968476
0.999981
1
1
1.00123
1.00331
1.00098
1.00214
1.00152
1.0027
1.00082
1.00265
1.01755
1.00558
1.0094
1.00548
1.00059
1.00329
1.00284
1.00409
1.0037
1.00432
1.00363
1.00418
1.00238
1.00048
0.984621
0.999747
1
0.999583
1
1.00068
1.00178
1.00253
1.00289
1.00103
1.00295
1.00084
1.00155
1.00088
1.00028
1.00278
1.00173
1.00091
1.00028
1.00253
1.01034
0.978709
1.01505
1.02481
1.01009
0.996665
1.0146
1.00665
1.00532
1.00767
1.0055
1.0073
1.00477
1.00774
1.00178
0.98141
1
1.00997
0.999608
1.01306
1.00165
1.00112
1.00188
1.00056
1.00272
1.00042
1.00275
1.00108
1.01089
1.02865
1.02044
1.01472
1.01894
1.01501
1.0109
1.00652
1.00561
1.00431
1.00774
1.00471
1.00774
1.00563
1.01271
1.01058
1.01081
1.00471
1.01303
1.01057
1.01088
1.00287
0.936832
1.00537
1.02423
1.00064
0.93179
1.00616
1.0075
1.00603
1.00675
1.00278
1.00767
1.00567
1.00719
1.01972
1.01651
1.0209
1.00467
1.02069
1.00493
1.02024
1.01252
1.00357
1.01007
1.00979
1.01014
1.01153
1.0127
0.999966
1.0024
0.972114
1.01079
0.932571
1.00761
0.998625
1.00721
1.00236
1.00533
1.0073
1.00539
1.00743
1.00669
1.0075
1.00944
1.00367
1.00468
1.00791
1.00956
1.00357
1.00601
1.01147
1.00027
1.00018
1.00559
1.00864
1.00022
1.00607
1.00264
1.00256
1.00102
1.00611
1.00255
1.0025
1.01156
1.04193
1.01606
1.0461
1.01482
1.04711
1.01095
1.00737
1.00491
1.00977
1.00373
1.00957
1.0037
1.00747
1.00587
1.00005
1.0053
0.999994
1.00551
1.0003
1.00644
1.0062
1.00109
1.00289
1.00265
1.00279
1.00254
1.00615
0.99536
1.00002
0.999457
1.00025
0.996355
1.00006
0.999513
0.943359
0.969128
1.00003
1.00024
0.944827
0.962601
1.00046
0.980508
0.999996
0.99815
1
0.979629
0.999993
0.997734
1
0.991187
1
0.932216
1
0.857058
0.999986
0.997623
1.00014
1
0.999563
1
0.999521
0.996605
0.938146
1.00045
0.95745
1.00513
0.964556
1.00188
0.920898
0.978634
1
1
0.997493
0.999996
0.998316
0.983043
1.00172
1.00224
1.00053
1.00061
1.00184
1.00166
1.00029
1.00098
1
0.999581
0.992721
1.00114
1
0.999862
1.00061
1.00007
1.00082
1
1.00085
1.00001
1.00065
1.00361
1.01317
1.01313
0.992479
1.01334
0.995149
1.00477
1.00169
1.0006
1.00166
1.00015
1.00159
1.00026
1.00141
1.00099
0.995631
1
1.00061
1
1.00059
1
1.00088
1
1.00001
1.00084
1
1.0005
1.00069
1.00131
1.00243
1.0015
1.00014
1.00059
1.00042
1.00082
1.00127
1.00228
1.00146
1.00013
1.00078
1.00041
1.00101
1.0029
1.00101
1.00276
1.00122
1.00034
1.00121
1.00058
1.00153
1.0027
1.00297
1.00157
1.00033
1.00061
1.00091
1.00217
1.00151
1.00132
1.0004
1.0009
1.00055
1.00019
1.00112
1.002
1.00122
1.00013
1.00053
1.00071
1.0003
1.00306
1.0011
1.00264
1.00094
1.0002
1.0002
1.00061
1.00148
1.00299
1.00265
1.0012
1.00061
1.00018
1.00082
1.00204
1.00148
1.00125
1.00035
1.00103
1.00075
1.00018
1.00336
1.00112
1.00289
1.00124
1.00064
1.00109
1.00022
1.00132
1.00333
1.00298
1.0015
1.00022
1.00029
1.00037
1.00192
1.00111
1.00118
1.00031
1.00048
1.00065
1.00007
1.00076
1.00093
1.00129
1.00007
0.936666
0.935801
1.00015
1.00144
1.00038
1.00095
1.00001
0.935646
1.00015
0.93584
1.00073
1.00097
1.0015
1.00015
0.93619
0.935391
1.00003
1.00145
1.00038
1.00093
1.00005
0.935989
1.00018
0.936329
1.00069
1.00033
1.00077
1.00013
0.938789
0.937233
1
1.00031
1.00079
1.00099
1
0.938326
0.937679
1
1.00191
1.00105
1.00235
0.999063
0.860724
1
0.859628
1.00193
1.00097
1.002
1
0.860706
1
0.858859
1.00037
1.00214
1.00168
1
0.85965
0.860434
1
1.0006
1.00227
1.00204
0.999399
0.85938
0.860489
0.999663
1.00113
1.00037
1.0016
1
0.860782
0.86112
1
1.00048
1.00115
1.0017
1
0.860746
0.860624
1
1.00069
0.996871
0.937641
0.862562
1.0671
0.677459
0.974919
1.03945
1.00028
1.01356
1.0595
1.06597
0.821872
0.998497
0.977054
1.00322
1.00738
0.963626
0.887517
1.02358
1.01293
1.0068
0.983819
1.02046
0.977899
1.01639
0.994652
1.01971
0.972588
1.05132
1.01785
1
0.999901
0.932831
0.976485
1.02992
1.02138
1.01804
1.01402
1.02343
1.03381
1.033
1.2296e-09
0.305586
1.69028e-09
0.48672
1.2296e-09
0.306131
1.71011e-09
1.00211
1.00185
1.00004
1.00001
1.00239
1.00246
1.00015
1.00269
1.00012
1.00198
1.00001
1.0024
1.00009
1.00208
-2.71698e-16
0.292403
-1.61562e-16
0.486693
3.35642e-10
0.307018
3.35643e-10
3.3732e-10
0.306152
3.37321e-10
0.484734
-2.47243e-16
0.291783
-1.50034e-16
1.00185
1.00028
1.00242
1.00017
1.00178
1.00011
1.00243
1.00172
1.0024
1.00021
1.00021
1.00247
1.00172
1.0001
1.84026e-09
0.485498
1.36396e-09
0.323645
1.85046e-09
0.485687
1.36396e-09
1.00193
1
1.00181
1.00001
1.00236
1.00013
1.00233
1.00251
1.00011
1.00001
1.00179
1.00012
1.00236
1.00177
3.80021e-10
0.4852
3.80018e-10
0.310457
-1.35698e-17
0.483593
-7.20662e-16
1.00154
1.00013
1.0023
1.00018
1.00249
1.00003
1.00162
-2.18503e-17
0.483816
-7.10706e-16
0.325961
3.72141e-10
0.485553
3.72137e-10
1.00162
1.00027
1.00014
1.00236
1.00005
1.00155
1.00233
1.00207
1.00111
1.00005
1.00022
1.00135
1.00013
1.00118
1.00205
1.00024
1.00117
1.00005
1.0014
1.00013
1.0012
1.00198
1.00018
1.00006
1.00101
1.00006
1.00119
1.00103
1.00207
1.00007
1.00111
1.00019
1.00007
1.00134
1.00118
1
1.00041
1.00021
0.536935
0.752541
0.537623
0.75205
1.00022
1
1.00019
0.536936
0.75228
0.752311
0.537356
1.00008
1.00045
1
0.536015
0.752879
0.537244
0.75134
1.00016
1.00007
1
0.536452
0.752704
0.752027
0.5376
1.00004
1
1
0.536122
0.75202
0.752553
0.535291
1
1.0001
1
0.536536
0.752035
0.75263
0.535762
1.00018
0.983903
0.983364
0.338544
0.608017
0.607601
0.337897
0.983958
1.00006
0.983863
0.337931
0.607925
0.337968
0.607659
1.00245
0.990926
1.00219
0.969136
1.00288
0.992049
1.00249
0.983881
1.00004
0.985106
0.334671
0.608006
0.337561
0.607371
1.0021
0.974604
0.992085
1.00255
0.996236
1.00191
1.00276
1.00309
0.968724
0.992226
1.00208
0.99054
1.00269
1.00244
1.00218
0.992745
1.00262
0.973607
1.00291
0.9958
1.00198
1.00254
1
1.00149
0.977335
0.997329
1.00184
1.00167
1.00139
1.00096
0.993121
0.973006
1.00192
1.00158
0.994117
1.00215
0.972867
1.00092
0.994626
1.00167
0.992701
1.00131
1
0.988107
0.985913
0.333148
0.607364
0.607833
0.329218
1.00258
0.977179
1
1.00147
0.997227
1.00184
1.00164
0.989544
1
0.987231
0.331689
0.607536
0.607703
0.327674
1.0001
0.985132
0.985394
0.334597
0.608241
0.607353
0.336136
1.00115
0.978706
1.00169
0.993825
1.0009
0.997926
1.00188
1.00102
1.00164
0.994991
0.978968
1.00197
1.00084
0.998202
1.00179
1.00073
1
0.98104
1.0009
0.99831
1.00087
1.00177
0.981243
1.00065
1
1.00086
0.999208
1.00075
1.87457e-10
0.205727
1.15742e-10
0.00248425
1.87435e-10
0.205606
1.15742e-10
1.0001
0.83231
1.00071
0.917191
1.00054
0.833798
1.00106
1.00072
0.916823
0.833125
1.00068
0.831925
1.00129
1.00027
4.00688e-11
0.206918
3.07317e-11
0.000628968
-6.22096e-17
0.198592
-1.51651e-16
1.00006
0.832497
1.00122
0.920023
1.00059
0.833417
1.00053
-6.4265e-17
0.199383
-1.72754e-16
0.00223025
4.03257e-11
0.2066
3.07925e-11
1.00032
0.92018
0.831553
1.00104
0.832553
1.00052
1.00064
1.08761e-10
0.00192116
1.78932e-10
0.184959
1.08761e-10
0.00189463
1.79305e-10
1.0011
0.902032
1.00102
0.813129
1.0015
0.814183
1.0013
-8.61999e-17
0.000521296
-3.9529e-17
0.185664
2.68391e-11
0.00171961
3.39741e-11
1.00137
0.900637
1.00141
0.812209
1.00168
0.812297
1.00173
1.00146
1.00143
0.812559
0.902832
1.00143
1.00118
0.812878
2.90632e-11
0.00172619
3.8177e-11
0.180287
-9.85532e-17
0.00051831
-3.99898e-17
1.00062
0.832595
1.00049
0.921531
0.831163
1.00049
1.00014
1.00069
0.920981
0.832549
1.00054
0.831348
1.00073
1.00015
1.00075
1.00139
0.812948
0.904794
1.00144
1.00073
0.814511
1.00157
1.0011
0.814728
0.902333
1.00138
0.812399
1.00072
1.00138
0.903781
1.00099
0.814049
1.00108
0.81273
1.00075
0.975378
0.971337
1.00115
1.0027
0.988979
1.04123
1.02651
1.00021
0.46807
1
0.642412
1.00003
0.642993
1.00048
1.00032
0.636797
1
0.460176
1.00063
0.637519
1
1.00054
0.460163
0.63735
1
0.637027
1
1.00036
1.0001
1
0.642635
0.467724
1.00047
1
0.642886
1.00034
0.459329
0.637081
1
0.63702
1
1.00062
1.00044
1
0.642958
0.46772
1.00024
1.00002
0.642577
1.0002
0.637185
1
0.459041
1.00057
0.637118
1
1.0004
0.467667
1
0.642752
1
0.642445
1
1.00017
0.467633
1
0.643045
1
0.642718
1.00042
1.00056
0.637168
1
0.4592
0.63685
1
1.00016
1.00051
0.458785
0.636881
1
0.636796
1
1.00016
1.00035
1
0.643
0.467584
1
0.642864
1
1.02863
0.850884
1.00072
1.03764
1.0151
0.848465
1
0.973244
0.959822
0.905566
0.987093
1.02303
1.00459
1.00114
0.994741
1
0.985834
0.955272
0.933482
0.985961
1.02241
0.994969
0.984444
0.979721
0.987622
0.991116
1.00588
1
0.975227
0.928006
1.05751
0.940876
0.989235
1.95929
1.00043
0.841042
0.934761
0.930541
0.257522
0.118437
0.120777
0.250152
0.8417
0.927691
0.928386
0.264764
0.124227
0.124633
0.264675
0.929852
0.841643
0.92723
0.266318
0.124349
0.264118
0.124741
0.928587
0.840902
0.929727
0.259198
0.123678
0.262989
0.12173
0.840977
0.931118
0.932391
0.259309
0.12429
0.122039
0.262217
0.934229
0.841225
0.932218
0.258929
0.118563
0.120972
0.254659
0.9788
0.972638
1.03865
1.11963
1.03379
0.995266
1.01864
0.980441
0.999891
0.873666
1.03567
0.982887
1.00183
0.947083
5.48024e-13
7.1358e-07
5.48032e-13
9.22576e-10
5.48032e-13
7.17019e-07
5.4804e-13
0.715031
0.0550712
0.883745
0.18171
0.715438
0.0562787
0.88275
0.713985
0.181397
0.0548802
0.884034
0.056395
0.882397
0.716471
-1.97998e-17
-1.67716e-16
-1.48996e-17
4.83138e-10
1.07402e-13
5.70532e-07
1.07455e-13
0.714987
0.176455
0.0539137
0.883369
0.0522933
0.884435
0.716746
1.07427e-13
5.717e-07
1.0748e-13
-8.02652e-16
-1.94005e-17
-1.72638e-16
-1.44865e-17
0.714873
0.0539523
0.883099
0.1766
0.715972
0.0527203
0.884517
0.71579
0.0468898
0.885279
0.175036
0.0507898
0.885434
0.716566
0.71417
0.174955
0.0465806
0.885217
0.0516618
0.885
0.717237
2.62115e-12
4.36127e-09
1.8165e-12
8.83768e-07
2.61631e-12
4.36034e-09
1.81653e-12
0.7529
0.918872
0.070576
0.212502
0.752575
0.918544
0.0713082
0.752204
0.21188
0.918451
0.0705429
0.918623
0.0714017
0.753054
-1.20862e-17
-1.24298e-15
-2.96225e-17
6.95816e-07
3.87805e-13
2.35856e-09
3.69893e-13
3.85209e-13
2.35654e-09
3.69354e-13
-3.20808e-16
-1.25303e-17
-1.24909e-15
-2.99416e-17
0.752082
0.209579
0.918119
0.0698659
0.918406
0.0677044
0.753383
0.752371
0.918378
0.0699727
0.210276
0.752665
0.91787
0.0676633
0.752813
0.920643
0.0634112
0.207806
0.919748
0.0665107
0.751957
0.752033
0.207707
0.920919
0.0631634
0.91944
0.066761
0.752247
0.666461
0.839886
0.839824
0.126347
0.0385971
0.0394924
0.125966
0.84087
0.66725
0.840777
0.12587
0.0386503
0.125326
0.0393769
0.839258
0.667287
0.83927
0.123493
0.037449
0.125795
0.035645
0.667131
0.842205
0.841837
0.121871
0.0376826
0.0356449
0.124059
0.667121
0.838966
0.838994
0.122831
0.0306578
0.034435
0.11974
0.841876
0.66819
0.842484
0.120944
0.0305453
0.0340521
0.118444
1.1119
0.669029
0.99959
1.02417
1.06412
1
0.889126
0.566339
0.704401
0.566676
0.0125152
0.0442845
0.0121674
0.0447091
0.70488
0.566647
0.565494
0.00997979
0.043298
0.0414318
0.0114185
0.565222
0.705187
0.565894
0.00861673
0.0381353
0.040363
0.00616728
0.566176
0.705816
0.565988
0.00978478
0.0428235
0.0113616
0.0407951
0.704597
0.566437
0.566362
0.0124742
0.0437701
0.0443565
0.0121668
0.706095
0.565458
0.566112
0.00842228
0.0369833
0.0395524
0.00611479
1.00477
1.02015
1.0154
1.15686
0.952518
0.890978
1.26829
0.978839
0.971119
0.961149
0.909224
0.967004
0.949306
0.965979
0.89195
0.93632
0.943821
0.919765
0.918937
0.919075
0.924137
1.0228
0.848668
1.00055
1.02338
1.01609
0.855402
0.992063
0.402077
6.37719e-07
0.151175
0.000176963
0.150716
0.000187974
0.401793
0.519978
2.04337e-06
0.00665474
0.248596
0.0057159
0.247488
0.520905
0.402556
0.150493
0.000162689
6.41076e-07
0.401473
0.151205
0.00019864
0.520789
0.00725013
0.250262
2.97827e-06
0.520952
0.00757789
0.249953
0.520512
2.97762e-06
0.00724371
0.249575
0.00759016
0.250529
0.52112
0.519858
0.00666271
0.249467
2.0416e-06
0.520764
0.00571828
0.246861
0.399809
4.35337e-07
0.150887
0.00013007
0.147992
8.06153e-05
0.401061
0.399319
0.149926
0.000129106
4.32148e-07
0.400861
0.148699
6.99226e-05
0.519758
0.00285518
0.241333
6.14786e-07
0.00467124
0.245077
0.519818
0.519884
6.0912e-07
0.00284663
0.241852
0.00462634
0.244605
0.519556
0.399578
0.144442
3.37517e-05
9.98547e-08
0.146603
6.69174e-05
0.399247
0.39922
9.89913e-08
0.143829
3.41022e-05
0.146705
5.59526e-05
0.398567
0.370474
0.535604
0.371617
3.45623e-06
0.00891689
3.45623e-06
0.00926759
0.534985
0.369972
0.371959
3.46958e-06
0.00904411
0.00931204
3.46958e-06
0.534418
0.367813
0.363661
2.47305e-06
0.00831042
0.00718634
2.47305e-06
0.367624
0.535685
0.362467
2.37167e-06
0.00818205
2.37167e-06
0.00679407
0.535995
0.353758
0.359964
7.17317e-07
0.00351517
0.00541876
-6.64739e-17
0.352303
0.535538
0.359633
7.57517e-07
0.00342995
0.00578798
-1.38555e-16
1.02334
1.03612
1.05353
0.963426
1.0193
1.03039
1.01785
0.430204
0.355578
0.43039
0.000414337
1.10334e-06
0.00039731
1.10334e-06
0.355073
0.43014
0.430341
0.000414924
1.08876e-06
0.000398631
1.08876e-06
0.428147
0.351251
0.429017
0.000195073
-2.31031e-18
8.32579e-05
1.63452e-07
0.429896
0.351957
0.429176
0.000281647
7.26748e-07
0.000356507
7.26748e-07
0.353487
0.430044
0.429069
0.000276051
7.0498e-07
0.00036299
7.0498e-07
0.351744
0.428024
0.428931
0.000195443
-1.73809e-18
8.273e-05
1.65911e-07
0.934345
1.00132
1
0.987153
0.939073
0.95035
0.994095
0.336844
0.308386
0.336335
4.91567e-07
4.91567e-07
4.91567e-07
4.91567e-07
0.454696
0.486923
0.454752
0.00120306
0.00309677
0.00116524
0.00321865
0.303503
0.335413
0.33168
3.1342e-07
3.1342e-07
3.1342e-07
3.1342e-07
0.486781
0.45469
0.454537
0.00120469
0.00309598
0.00320943
0.00116214
0.454104
0.485728
0.453636
0.00281363
0.00106857
0.000858885
0.00230939
0.485884
0.454509
0.4539
0.00281977
0.00105569
0.000859802
0.00230323
0.466732
0.485851
0.466811
0.00296421
0.00311249
0.00181288
0.00174837
0.48556
0.46674
0.466565
0.00299175
0.0030181
0.00180414
0.00170481
0.330757
0.302245
0.327214
3.23068e-07
3.23068e-07
3.23068e-07
3.23068e-07
0.308774
0.333484
0.334889
5.07424e-07
5.07424e-07
5.07424e-07
5.07424e-07
0.466252
0.48465
0.465739
0.00269008
0.00221044
0.00159033
0.00128244
0.484575
0.466604
0.466046
0.00271458
0.00217141
0.00155317
0.00126599
0.297132
0.312176
0.32094
1.18034e-07
-2.25933e-17
-9.03205e-16
1.18034e-07
0.318691
0.299247
0.326514
1.10985e-07
-1.64958e-17
-9.55685e-16
1.10985e-07
0.452936
0.485846
0.453806
0.000621734
0.000878371
0.001744
0.000279796
0.485627
0.452486
0.453385
0.000614059
0.000874577
0.00173441
0.000276684
0.484512
0.464424
0.465441
0.000826093
0.00164852
0.000910842
0.000429406
0.464964
0.484675
0.465962
0.000829289
0.00166728
0.000916389
0.000432398
0.3684
0.308836
0.366846
4.77055e-07
4.77055e-07
4.77055e-07
4.77055e-07
0.309215
0.366479
0.369074
4.63678e-07
4.63678e-07
4.63678e-07
4.63678e-07
0.300482
0.366565
0.359801
3.45006e-07
3.45006e-07
3.45006e-07
3.45006e-07
0.36558
0.301683
0.360392
3.51856e-07
3.51856e-07
3.51856e-07
3.51856e-07
0.38382
0.328255
0.382437
5.55874e-07
5.55874e-07
5.55874e-07
5.55874e-07
0.973303
1.01206
0.999532
1.04199
0.99745
1.03675
0.973947
0.328459
0.381627
0.384724
5.6471e-07
5.6471e-07
5.6471e-07
5.6471e-07
0.381095
0.319041
0.375428
4.41999e-07
4.41999e-07
4.41999e-07
4.41999e-07
0.319512
0.382506
0.375612
4.06029e-07
4.06029e-07
4.06029e-07
4.06029e-07
0.353295
0.296731
0.358067
1.2156e-07
-1.26702e-15
1.2156e-07
-5.93889e-16
0.296594
0.353108
0.358109
1.14603e-07
-1.10456e-15
1.14603e-07
-5.76211e-16
0.371374
0.316094
0.374835
1.44542e-07
-1.04918e-15
1.44542e-07
-1.2187e-15
0.315708
0.371636
0.373788
1.48686e-07
-8.85494e-16
1.48686e-07
-1.43998e-15
0.962156
1.2173
1.04162
0.992322
1
1.02677
1.02961
1.08716
1.12197
1.04465
0.684233
1.07171
1.08971
1.06312
0.982168
1.01168
1
0.991469
0.969804
0.972004
1.02221
1.05804
0.938843
1
0.964676
1.03204
1.00329
1.06776
0.980601
0.886198
0.976013
0.98847
0.871934
0.98812
0.871154
0.92122
0.853422
0.888822
0.703618
1.31139
0.876153
0.970376
0.942933
1.00384
0.96526
0.99244
0.936201
1.00404
0.813101
0.112703
0.208334
0.112218
3.04393e-07
3.04393e-07
3.04393e-07
3.04393e-07
0.208497
0.112153
0.113536
3.00992e-07
3.00992e-07
3.00992e-07
3.00992e-07
0.111958
0.202733
0.109364
1.99192e-07
1.99192e-07
1.99192e-07
1.99192e-07
0.20265
0.112999
0.110003
1.99144e-07
1.99144e-07
1.99144e-07
1.99144e-07
0.186823
0.101971
0.101797
2.82625e-07
2.82625e-07
2.82625e-07
2.82625e-07
0.102539
0.186097
0.102796
2.79294e-07
2.79294e-07
2.79294e-07
2.79294e-07
0.200971
0.106027
0.110074
-7.55671e-18
4.5613e-08
4.5613e-08
-3.50958e-19
0.106075
0.200734
0.110434
-8.93307e-17
4.65427e-08
4.65427e-08
-3.64062e-19
0.185479
0.102244
0.100165
1.71169e-07
1.71169e-07
1.71169e-07
1.71169e-07
0.101723
0.181608
0.0983545
1.86655e-07
1.86655e-07
1.86655e-07
1.86655e-07
0.0941545
0.183123
0.0992294
-1.92118e-16
3.83676e-08
3.83676e-08
-1.65649e-17
0.181998
0.0947345
0.0989585
-4.89215e-16
4.16658e-08
4.16658e-08
-4.86927e-16
4.95801e-14
1.47267e-12
8.9039e-14
1.43264e-10
4.95743e-14
1.49021e-12
8.89964e-14
0.0101206
0.0718505
8.30586e-08
8.30586e-08
0.00970049
0.0723206
8.30586e-08
0.0101449
8.32407e-08
0.0717555
8.32407e-08
0.0722931
8.32407e-08
0.0097478
-5.4247e-17
-5.35011e-19
-6.93684e-19
6.37566e-11
7.60886e-15
6.02089e-13
1.18209e-14
7.75671e-15
5.75256e-13
1.23354e-14
-8.02608e-18
-5.37804e-17
-5.65598e-19
-6.86859e-19
0.00770042
5.12791e-08
0.0710321
5.12791e-08
0.068906
5.12791e-08
0.00896572
0.0077778
0.0709437
5.14957e-08
5.14957e-08
0.00907224
0.0691136
5.14957e-08
0.00649456
0.0647519
-2.27905e-20
1.0776e-08
0.067416
1.0776e-08
0.00455855
0.0065531
1.0754e-08
0.0644779
-6.62445e-20
0.0673186
1.0754e-08
0.0045824
0.943534
0.970429
0.884221
0.999535
0.970674
0.975215
0.949094
0.962678
0.882334
0.974562
0.961874
0.650715
0.79824
0.946511
1.00633
1.05528
0.983647
0.986855
0.996889
1.02507
0.973152
0.884795
1.00525
0.990144
0.94782
0.99199
0.966862
0.884654
0.871154
0.95835
0.939228
0.940015
0.871154
0.870884
0.885959
1.02507
1.01866
1
1.01628
1
1.01959
1.02342
0.875785
0.999939
0.99461
1.03072
0.879976
0.933542
1.033
0.885301
0.995701
0.957993
0.97555
0.884844
0.970902
0.954762
0.955727
0.91753
0.924635
0.957364
0.871448
0.888292
0.87593
0.853757
1.00471
0.980739
1.00008
0.915722
1.00409
0.975224
0.941223
0.984668
0.948324
0.847066
0.98298
0.926419
0.97181
0.988302
0.992083
0.939448
1.00459
0.910059
0.985669
0.997566
1.07187
1.05338
0.851769
1.03503
1.0379
1.02736
0.90924
1.05037
1.0322
1.0983
0.980194
1.02372
1.03062
0.991655
1.02081
0.95952
0.939464
1.01391
0.999982
0.958768
0.912582
1.00832
1.02169
0.964787
1
1.04673
0.931742
0.981864
0.819658
0.921635
0.814438
0.986435
0.973964
0.984522
0.985362
2.29353e-14
3.48021e-11
1.33961e-14
6.02648e-13
2.29356e-14
3.55455e-11
1.33957e-14
1.2778e-06
3.83611e-08
0.0229923
2.1032e-08
1.18793e-06
3.79247e-08
0.0234994
1.28352e-06
2.10472e-08
3.84144e-08
0.0229731
3.79391e-08
0.0234938
1.18065e-06
0.95905
1.0112
0.99269
1.00078
0.991116
1.00641
1.00923
-1.32398e-19
-2.07047e-17
-9.29636e-18
2.14121e-13
2.76738e-15
1.44199e-11
1.71604e-15
2.7742e-15
1.44588e-11
1.72067e-15
-2.98041e-19
-1.33803e-19
-2.14169e-17
-9.36657e-18
6.1513e-07
1.23047e-08
2.20488e-08
0.0220817
2.31031e-08
0.0200637
9.40024e-07
6.36007e-07
2.21287e-08
0.0221183
1.23449e-08
9.37343e-07
2.31465e-08
0.0199983
3.24298e-07
-9.56567e-19
0.0156035
2.32161e-09
4.09013e-09
0.0186146
-1.50601e-17
3.27943e-07
2.30529e-09
-9.07331e-19
0.0155725
4.05292e-09
0.0184939
-1.39936e-17
0.0291521
0.00268309
0.0299213
2.95336e-08
2.95336e-08
2.95336e-08
2.95336e-08
0.00266955
0.0293252
0.0297797
2.95466e-08
2.95466e-08
2.95466e-08
2.95466e-08
0.028485
0.00179791
0.0261923
1.71527e-08
1.71527e-08
1.71527e-08
1.71527e-08
0.001821
0.0283055
0.0263835
1.71406e-08
1.71406e-08
1.71406e-08
1.71406e-08
0.021648
0.00132765
0.0250831
3.32806e-09
-1.86427e-22
3.32806e-09
-4.3858e-17
0.846461
0.8432
0.925026
0.991556
0.973571
1.00172
0.993793
0.0013145
0.0216388
0.0252016
3.33601e-09
-2.56594e-21
3.33601e-09
-6.11985e-16
0.938211
0.998642
1
0.967345
0.999571
0.936952
0.937704
0.00204156
0.0275496
0.0281859
2.7719e-08
2.7719e-08
2.7719e-08
2.7719e-08
0.0277085
0.00201943
0.0281274
2.80676e-08
2.80676e-08
2.80676e-08
2.80676e-08
0.00144471
0.0268632
0.0247553
1.67439e-08
1.67439e-08
1.67439e-08
1.67439e-08
0.0266908
0.00143815
0.0246906
1.68284e-08
1.68284e-08
1.68284e-08
1.68284e-08
1.01329
1.02686
1.01563
0.841824
1.02562
1.01394
0.887478
0.929405
1.00291
1.0347
1.02116
0.976823
1.0089
1.04399
1.14746
1.01169
0.999951
1.03265
1
0.974943
1.12274
0.0199637
0.00108301
0.0235464
3.03232e-09
-4.02014e-17
3.03232e-09
-4.63594e-17
0.00108394
0.0200212
0.0234706
3.01789e-09
-5.10341e-17
3.01789e-09
0
1.01265
1.00719
1.03623
1.04203
1.04683
0.998918
1.03405
0.990405
1.01015
0.902754
1.01025
1.00703
1.00729
0.974387
0.991071
0.908674
0.985849
0.992999
0.909956
0.99068
0.925197
1.28681
0.914762
1.10741
0.587013
1.21334
0.512237
1.1651
0.953668
0.992486
0.99396
0.996289
0.87434
0.828242
0.993205
0.995792
0.95562
0.993648
0.945869
0.802125
0.882037
0.945933
0.994981
0.916236
0.980094
0.992616
0.971029
0.948179
0.99883
1.00632
1
1.007
1.02369
0.979654
0.997128
0.99726
1.00441
0.882293
1.00846
0.998042
0.91771
0.992367
0.94373
0.984956
0.999524
0.904447
0.930197
1.00492
0.998007
0.999954
0.930435
1.00005
0.998067
0.998205
0.986339
1.00104
0.991525
1.11066
1.00595
1.02877
1.02171
1.11926
1.04191
1.09478
0.958571
0.941855
0.945817
0.958131
0.965964
0.975609
0.956561
1
1.06741
1.00989
1.02967
1.07385
1.02482
1.02645
1.0633
1.07707
1.01088
1.01419
1.07211
0.986637
1.00131
1.08547
1.05039
0.979564
0.988913
0.87217
0.933028
0.905647
1.01479
1.07707
1.09402
0.985475
0.911992
1.08105
1.01793
0.975681
0.930117
0.994326
0.970969
1.00229
0.851801
0.997527
0.97815
0.911869
0.979899
1.25653
0.938869
0.987746
1.05083
0.991127
1
0.994083
0.994438
0.991384
0.872737
0.87969
1.01079
1.0011
0.988997
1.00778
0.879547
0.859442
1.00521
1.0126
0.998793
0.999169
0.851228
1.00784
1.00892
0.845588
0.992938
1
0.997227
1.00596
0.99985
1
0.9927
0.983057
0.985473
0.983221
0.834382
1.00125
0.998364
0.829889
0.81008
0.685004
0.796243
0.972368
0.964608
0.972482
0.957621
0.810632
0.811164
0.80913
0.981785
0.950548
0.959464
0.964722
0.674951
0.787815
0.78594
0.978941
1
0.994938
0.973634
0.986289
1.00172
1.00134
0.999533
0.918893
0.924565
1.0015
8.73167e-07
9.80116e-10
5.14953e-07
9.80117e-10
8.45775e-07
9.80116e-10
5.70771e-07
9.02368e-07
9.92583e-10
9.92582e-10
5.20373e-07
9.92582e-10
5.71986e-07
8.45929e-07
5.10126e-07
5.35628e-10
5.35626e-10
4.12553e-07
5.35627e-10
2.74719e-07
7.53056e-07
4.68929e-07
5.11227e-10
4.18672e-07
5.11228e-10
6.93628e-07
5.11228e-10
2.80265e-07
2.56995e-07
-1.7913e-20
-4.47776e-18
6.36295e-11
6.36289e-11
1.37322e-07
-2.08469e-16
2.51305e-07
6.35601e-11
-3.14849e-20
-4.8482e-18
6.356e-11
1.38349e-07
-3.14774e-16
0.982622
0.993028
1.07927
0.999784
1.00556
0.997929
1.02971
0.9887
1.06581
1.03288
0.996281
0.985856
1.03323
1.0289
1.04615
0.994873
0.981971
0.999993
1.03244
0.983246
0.943303
0.894531
0.936235
0.969041
0.996765
0.956833
0.873888
0.981674
0.961628
0.933884
0.96235
0.908527
0.779978
0.94209
0.838658
0.908707
0.959509
0.953628
0.990124
0.931523
0.949074
0.996182
0.893995
1.02721
1.02118
0.913513
0.96645
1.0376
1.02653
0.972492
0.856505
0.918592
0.91031
0.912966
0.929078
0.965772
1.00739
0.998084
0.995996
0.859213
0.975611
0.87726
0.987612
0.934562
0.855668
0.948864
0.854143
0.982372
0.983082
0.853914
0.983781
0.980354
0.83883
1
0.968685
0.836528
0.99903
0.991118
0.990969
0.981902
0.945799
0.858979
0.938947
0.928018
0.962946
0.990098
0.957369
0.899941
0.984625
0.984429
0.923701
1.01501
0.977233
0.988619
1.01424
1.0132
0.860829
0.865687
0.962964
0.979442
0.95822
0.855492
0.992618
0.928694
0.854143
1.02597
1.02009
1.01818
0.999975
1.01274
0.877124
0.996564
0.99878
1.0153
1.04259
0.955216
1.00011
1.0235
1.07961
1.05151
1.03048
1.04126
1.08221
1.03526
1.07123
1.06583
0.999078
0.970267
1
0.956097
0.943488
0.931351
0.924631
0.868529
0.971545
0.951511
0.849792
0.855875
0.987453
0.995042
0.966849
1
1.01406
0.924366
1
0.925456
0.999992
0.944114
1
1
0.844202
0.99994
0.842953
0.999968
1.02975
1.0268
1.05551
1.05801
1.02991
1.0343
1.06705
1.11189
1.05353
1.14075
1.01374
1.01847
1.03397
1.08769
0.98171
1
0.988721
0.991555
1.03112
1.00061
0.943274
0.949933
1.0066
1.00366
0.822619
0.834519
1
1
1.06357
1.02135
1.03008
0.701934
0.765063
0.923413
0.920282
0.936411
0.992761
1.00295
0.949733
1.00513
0.940395
0.813749
0.95751
0.953189
0.942808
0.793311
0.946688
0.764163
0.946268
2.48365e-07
9.94059e-07
2.75722e-07
8.6483e-10
8.6483e-10
8.98168e-10
9.57891e-10
9.85627e-07
2.48625e-07
2.76086e-07
8.65518e-10
8.65518e-10
9.00641e-10
9.60597e-10
2.00607e-07
4.57765e-07
1.33369e-07
4.2151e-10
4.2151e-10
4.2151e-10
5.26004e-10
4.67268e-07
1.99978e-07
1.33341e-07
4.21668e-10
4.21668e-10
4.21668e-10
5.26774e-10
-2.69386e-17
2.46785e-07
6.63628e-08
-5.27955e-18
4.98112e-11
4.98109e-11
-9.87373e-18
2.39221e-07
-2.84321e-17
6.63304e-08
-4.96607e-18
4.87333e-11
4.87331e-11
-9.06228e-18
1.73363e-07
7.8332e-07
1.93102e-07
6.54876e-10
6.54876e-10
7.23723e-10
8.04473e-10
7.66103e-07
1.70216e-07
1.89866e-07
6.51401e-10
6.51401e-10
7.36071e-10
8.15174e-10
3.87165e-07
1.34509e-07
8.91043e-08
3.28659e-10
3.28657e-10
3.28659e-10
4.68588e-10
1.38416e-07
3.95158e-07
9.18693e-08
3.3286e-10
3.32859e-10
3.32861e-10
4.67514e-10
-4.70028e-17
2.01574e-07
4.31529e-08
-3.50035e-19
3.7971e-11
3.79711e-11
-4.43494e-19
2.00228e-07
-5.1945e-17
4.31759e-08
-3.78931e-19
3.77861e-11
3.77862e-11
-4.97919e-19
0.971761
0.852659
0.849941
0.975127
0.851654
0.988017
0.987711
0.95321
1
0.989326
0.982171
0.943894
0.985325
0.94945
0.948694
0.991084
0.969904
1
0.999497
1.00173
1.00424
0.843737
0.968492
0.898272
0.853694
0.98149
0.80938
1.0447
1.09473
0.994439
0.910539
1.05807
1.12824
1.00359
0.756983
1.0718
1.05095
1.09322
1.01456
1.06154
1.02899
1.0191
1.04377
0.926244
1.19502
1.08454
1.09396
0.91841
1
0.999933
1.17047
0.963883
1.03725
1.00514
1.10931
1.12865
0.765587
1.02627
1.08673
1.0164
0.931674
0.999195
0.96131
1.01122
0.993108
0.997856
0.856505
0.944983
0.989516
0.881945
0.977239
0.949094
1
0.872385
1
0.875195
0.97662
0.979501
1.03649
1.00337
1.00374
0.962521
1.01662
0.996351
0.914721
0.967919
0.874164
0.964613
0.965148
0.936804
0.904828
0.987911
0.928325
0.932596
1
0.989088
1.02629
0.999457
0.894938
0.892376
0.994541
0.99026
0.941099
0.894849
0.996203
0.977128
0.944182
0.967576
0.939944
0.964124
0.924761
0.985638
0.895777
0.992619
0.958993
0.985549
0.935144
0.985821
0.91161
1.00172
0.990763
0.99252
0.991448
0.987672
1.02538
0.986139
1.0108
1.00082
1.01317
1.00847
1.01156
1.00062
1.01067
0.979849
0.965989
0.932768
0.971705
0.961488
0.919049
0.979958
0.999674
0.996604
0.999675
1.00033
1.00784
1.0067
1.00061
0.914599
1.01088
0.946004
0.70645
0.984578
0.748693
0.988488
1.0335
0.881614
1.13573
0.950496
0.873761
1.02046
0.927869
0.985236
0.96091
1
0.993593
0.927127
0.992635
0.91213
0.991997
0.992979
0.997675
0.999018
1.0083
1
1.00787
0.982414
1
0.999998
0.999357
1.00999
1.00955
0.997563
1.00719
1.00248
1.0212
1.02012
1.02452
1.03378
1.00233
1.0003
0.997598
0.998317
0.999267
1.0246
1.02348
1.00659
0.984458
1.01021
1.01998
0.930859
0.961679
1.00172
0.973928
1.00856
0.971793
1.05384
0.953689
1.00838
0.986824
1.03585
1.00495
0.902387
1.00955
1.01528
1.01671
1.00648
1.04511
0.809035
0.961031
0.984291
1.07934
1.00116
0.938391
1.14227
1.00299
0.9814
1.03686
1.01762
1.02672
0.993897
1.00354
1.01627
0.959916
0.987248
0.891856
0.991247
0.994709
0.841193
1.00358
0.959085
0.999687
0.952545
0.980754
0.963519
0.968125
0.853739
0.999959
1
0.946633
0.865917
0.99431
0.987827
1.04903
0.998127
0.681555
0.984171
1.05166
1.058
0.836238
1.09772
1.02285
0.737714
1.10033
1.03043
0.9921
0.88078
1.00331
1.02091
1.04622
0.937043
1
1.00904
0.885484
0.998853
0.955789
0.926115
0.696089
1
0.997164
0.680255
0.953134
0.996775
0.998387
0.96973
0.986754
0.985982
0.983338
0.840868
0.943179
0.952749
0.941461
0.931532
0.919485
0.960204
0.681471
1.14494
1.16231
1.18284
0.9958
1.11979
0.693619
1.06421
0.947237
0.694397
1.06013
0.772696
1.11173
0.803345
0.999901
1
1.00443
1.01427
1.01533
1.04432
1.04081
0.906121
1.01285
1.00798
0.970568
1.01246
1.02926
1.01922
1
1.01336
0.997208
0.996034
0.977431
1.01212
0.989167
0.955919
0.999749
0.959276
0.999958
1.00007
1
0.999868
0.955497
0.998855
1.04038
1.01179
1
1.04488
0.964235
0.872535
0.999042
1.00485
0.881725
0.748265
1.00936
1.01365
1.00124
0.929711
0.999551
0.972036
0.937909
0.916544
0.97346
4.62742e-07
1.11186e-07
3.73938e-10
3.73938e-10
4.20585e-07
1.24245e-07
3.73938e-10
4.64045e-07
3.74897e-10
1.11432e-07
3.74897e-10
1.2458e-07
3.74897e-10
4.21599e-07
1.00002
0.985518
1
1.00018
0.997142
0.998193
1.00016
0.849024
0.993598
0.890706
0.860808
0.986503
0.983016
0.98188
0.985166
0.833813
0.949456
0.953028
0.897031
0.895398
0.999773
1.00434
1.02329
0.978753
1.03702
1.12481
1.04129
0.85325
0.830149
1.0223
1.01209
1.00791
1.08996
1.21343
1.02396
2.25018e-07
8.72362e-08
1.85643e-10
2.32114e-10
3.38122e-07
5.68234e-08
1.85644e-10
0.978916
1.00016
0.997476
0.999003
1.00104
0.98483
1.00222
0.999991
0.995299
0.994446
0.948839
0.978827
0.999563
1.00038
0.996099
0.851477
0.993609
0.99909
0.995663
1.01639
1.0129
0.903933
0.994502
0.991884
0.998999
0.996127
1.01253
1.00547
0.94057
0.92787
0.9693
0.853109
0.984982
0.924832
0.948946
1
0.969657
0.981087
0.998956
0.999995
1
1.00004
1.00144
0.934334
1.01947
1.04677
1.00074
1.02216
1.04666
1.10195
0.982058
0.962456
0.966525
0.992234
0.984584
1.093
0.99967
0.991458
1
0.992642
0.990812
0.98834
1
0.999036
0.853974
0.999998
1.007
0.996782
0.99428
0.997165
0.891964
0.900135
0.892722
0.956331
1.05234
1
0.997223
2.25215e-07
2.325e-10
8.71709e-08
1.85885e-10
5.61582e-08
1.85885e-10
3.39162e-07
0.988776
0.924731
0.941906
0.975525
0.992896
0.984789
0.928706
1.0902
1.03
0.997393
1.02337
1.01791
1.06125
1.01237
0.984225
0.948343
0.973546
0.985754
1.00062
0.992557
0.992163
1.05438
1.00997
1.01863
0.991214
1.00799
1.01303
1.01558
1.00518
0.99957
1.00433
0.943003
1.00362
1.0009
0.93507
1.06792
1.02306
1.07223
1.02416
1.07149
1.01944
1.0727
0.898467
0.965198
0.871074
0.853914
0.989076
0.854809
0.970753
1.02067
1.00994
1.01476
1.01278
1.01697
1.01854
1.01668
1.00251
0.974496
0.99857
0.98803
1
0.979507
1.00057
0.950019
0.999102
1.00211
1.02022
1.02159
1.04645
1.04969
1.00847
1
0.984143
0.962075
1
0.996595
0.964911
1.11419e-07
2.09961e-11
-2.92319e-18
-1.82395e-19
2.67246e-08
2.0996e-11
-5.58255e-17
1.11636e-07
-2.81153e-18
-1.87217e-19
2.09744e-11
2.64275e-08
2.09743e-11
-4.91722e-17
1.03129
1.03391
1.03057
1.09592
1.01084
1.09902
0.809729
0.97333
0.762106
1.02411
0.955934
0.951655
1.01676
0.691225
1.03944
1.16156
1.00575
0.985
0.981928
1.15136
1.04872
0.893013
1.05453
1.00607
1.04836
1.04273
1.05827
1.05462
1.07375
0.994594
1.00723
1.00918
1.02618
1.04097
1.04706
0.994385
1
0.976339
0.907303
0.957451
0.916102
0.970257
0.967271
0.915368
0.940267
0.737936
1.00538
0.958709
1.09184
1.00322
1.01206
1.00451
1.03872
1.01704
1.02854
1.00374
1.03464
1.15279
1.70269
1.00269
0.909942
1.03856
1.01517
0.968058
0.994883
0.996734
0.921141
0.958777
0.999193
0.994079
0.830638
0.646894
1.07069
1.13584
0.76617
0.80048
0.757092
0.9784
0.861782
0.994913
1.10345
0.948301
0.917927
1.09709
1.00972
1.01884
0.998313
1.00512
0.997206
1.01759
0.9918
0.964922
1.05255
0.867465
0.973178
1.079
0.968024
0.946029
1.04218
1.00455
1.06797
0.991285
1.0664
1.0698
0.975675
1
0.960696
0.972256
1.03422
1.00388
1.01014
1.02177
0.864156
1.07366
1.03388
1.08027
0.962318
1.02258
1.16034
1.04337
0.845072
1.04168
1.11206
0.839752
0.883837
1.08468
1.00887
1.09316
1.08683
1.21023
1.06434
1.08754
1.05416
0.921891
1.01053
0.986362
0.975911
1.02124
1.01196
0.961708
1.04757
0.937889
0.659788
1.04298
1.07003
1.04609
1.14138
0.696006
1.04565
0.998209
1.06729
0.984585
1.10722
1.03954
1.09746
0.965158
0.81728
1.00734
1.07228
0.959296
0.978798
0.962669
0.9943
0.790876
0.942529
0.946006
0.792855
1.15686
1.30279
0.927923
0.939635
0.976763
0.793076
1.0094
1.04698
1.00806
1.00088
0.909845
1.03251
0.965892
1.00631
1.11475
0.96696
0.955983
0.818002
1.03381
1.03411
0.971559
0.860101
0.858243
1.00048
0.943631
0.84613
0.990676
0.933315
0.981961
1.07036
0.767297
1.18035
0.969192
1.00054
1.05937
0.916978
0.956194
0.957977
0.853914
0.854459
0.916043
0.950819
0.969192
0.999092
1.02079
1.02677
0.910874
0.955915
0.910959
0.951086
0.99213
1.02542
1.0056
0.99993
0.990969
1
1.00593
0.96424
0.940788
0.636112
1.01024
1.02041
0.978146
0.662184
0.997808
0.961417
0.938362
0.907211
0.984994
0.915276
0.966091
1
0.99424
0.995335
1.01906
0.995837
1.0029
1.0029
1.03213
1.14848
1.00781
0.884982
1.00719
0.919901
0.991046
0.987447
0.840772
1.06243
0.98625
0.979759
1.07445
0.837828
1.02528
0.995011
1.0213
0.911187
0.969916
0.911912
0.973751
1.02083
1.05754
1.06672
1.01938
1.0204
1.06653
1.04837
1.089
1.03615
1.02484
0.99935
0.990881
0.834717
0.827252
1.04109
1.04094
1.04177
0.601105
0.984794
0.941226
0.974599
0.854882
0.914806
0.925403
0.954546
0.94617
0.950679
0.900151
1.01969
0.991651
1.02661
0.998417
1.01154
1.03769
0.998842
1.03735
0.997101
0.687804
1.06518
1.02035
0.984609
1
0.955843
1.02109
0.977663
0.949488
0.960779
1.03008
0.94629
1.03277
1.04127
1.02354
1.03426
1.04444
1.02829
1.0474
1.08589
2.27586
0.210675
0.154072
1
1.33782
1.322
0.901269
0.923182
1.40321
0.61604
1
1.04871
2.77169
0.904718
0.949195
0.961433
0.853675
0.967327
0.952441
0.854582
1.00127
1.00824
1.01533
0.994077
1.00608
1.00162
1.00406
0.874174
0.950263
0.924559
1.01312
0.961158
1.014
0.990471
0.998678
1.00069
0.998166
0.997453
1.01801
0.994911
1.02405
0.99707
0.571032
0.946192
0.860708
1
1.04724
1.06468
1.11354
0.969112
0.991379
0.98813
0.972892
0.973246
0.977151
1.0295
1.00916
1.00207
0.986
0.989699
0.966063
0.967441
1.01102
1.01704
1.01041
1.01715
1.01584
1.00701
1.01815
1
0.932064
1
0.910355
0.990473
0.952529
0.904077
1.15931
1.14743
0.953252
1.03462
1.11209
1.04841
1.05083
1.16667
1.20652
1.0343
0.748168
1.2498
0.984253
1.22943
0.977751
0.994144
0.869451
1.01622
1.00687
0.826015
0.823723
0.916509
1.00845
1.01516
0.95516
0.856918
0.977783
0.919254
0.921284
1.03797
0.791533
0.941733
0.769961
1.23533
1.18148
0.985631
1.05316
1.07416
0.698494
0.653978
1.03198
1.02534
0.984819
1.1794
1.11046
0.653234
0.648022
1.03977
1.02692
0.886485
1.06033
0.937456
0.963841
0.99709
1.00108
0.987676
1.01522
1.00557
0.865562
1.17749
1.08217
1.18525
0.99578
1.0287
0.999868
0.86355
1.19867
0.794049
0.978751
1.18975
0.992999
0.897911
0.961223
1.02896
1.03466
0.967229
0.996404
0.968594
0.968178
0.96768
0.748003
0.97583
0.992428
0.705787
1.0673
1.01108
1.08433
1.08308
0.830336
0.906617
1.07419
1.06628
1.05616
1.04827
0.852151
0.850077
0.906445
0.894919
0.841555
1.00783
1.08282
1.00779
0.842391
1.01255
1.06061
1.13047
0.960205
1.14097
0.981145
1.03232
1.02696
0.993736
1.00616
0.940652
1.01298
0.856051
1.0195
1.0234
0.917486
0.843284
1.00683
1.00986
0.864158
1.00947
1.0117
1.01376
1.0312
1.036
1.0026
1.00899
1.00269
1.05231
1.00106
0.99318
1.01533
1.03454
0.971191
0.9999
0.951858
0.712592
1.05061
0.996417
1.04306
0.881326
0.844918
0.974382
0.933002
1.06436
1.07017
0.977344
1.03169
0.87726
1
1.00773
0.999998
0.978049
0.971622
0.899032
0.898134
0.972308
0.89809
0.912749
1.00763
1.00041
1.01869
0.997348
1.02363
0.882385
0.970472
0.96223
0.912207
0.890851
1.00267
1.00192
0.880774
0.96178
0.953113
0.919569
0.985323
0.984569
0.993539
0.903535
0.840774
1.01911
0.842773
1.08373
1.08117
1.0126
1
1.01454
1.14632
1.17155
0.971746
0.981071
1.04166
1.02458
1.01833
0.854779
0.844101
1.08055
1.07802
0.974296
0.958123
1.05826
0.978245
1.00314
0.846033
1.00208
1.01343
1
1.16006
1.00268
1.15254
0.975023
0.963501
1.03818
1.05473
1.08875
0.990105
1.02718
1.16116
1.24275
0.664499
0.664648
1.03323
1
1.00334
0.960525
1.00694
1.01267
1.00809
1.03434
1.08266
1.05728
1.06642
1.08062
1.07093
1.09017
1.05801
1.00489
1.01326
1.06803
1.12206
0.984541
1.01588
0.990733
0.968984
0.944229
0.96997
1.03278
0.980698
0.977366
1.00208
1.03002
0.763962
0.984042
1.02443
1.02367
0.926591
0.950444
1.00686
1.02089
1.07443
0.912352
1.01477
0.936191
1.06071
0.695796
1.18729
0.845127
0.994584
1.07589
0.679508
0.960438
1.01765
0.672977
0.739487
0.880753
0.656558
1.04523
1.25559
1.22175
1.03862
1.09881
1.30781
1.24792
1.11475
0.871345
1.02852
0.926386
0.933128
0.972089
1.07004
1.04828
1.00085
1.00371
0.953802
0.978909
1.0004
0.989448
0.985397
1.05262
1.05132
1.01827
1.02687
1.06888
1.07763
1.04909
0.893608
0.944176
1.22078
0.994757
0.909488
1.09792
0.789027
1.09146
1.23068
1.02076
1.02791
1.11503
0.683936
0.785623
0.858706
1.04395
1.01361
1.03026
1.03142
1.01996
1.03891
1.00147
1.04735
0.821284
1.07912
0.816156
1.01866
1.04405
1.04745
1.07899
0.995917
0.993451
1.07681
0.725545
0.736
1.02634
1.01365
1.00038
1.00951
0.859647
1.10594
1.00324
1.01563
0.846033
0.999263
1.04176
0.957941
1.05732
0.994034
1.32449
0.592533
1.23107
1.01463
1.25616
1.06571
0.700008
1.03962
1.04677
1.08201
1.06012
1.08953
1.07448
1.10655
0.861265
1.03502
1.09713
0.918998
0.984809
1.10257
1.21633
1.19697
1.04787
0.611911
0.974302
1.1487
1.02774
0.604036
1
1.11414
1.00973
0.793926
1.16315
1.15828
0.839103
0.893995
1.21767
1.26302
0.660094
0.664098
1.05414
1.01021
1.09563
1.0055
0.951082
0.982103
1.06551
0.755863
1.05737
0.944546
0.954541
1.39847
1.09574
0.962514
1.10468
1.09968
1.04269
0.801546
0.964132
1.06863
0.807374
1.08666
1.07031
0.978083
0.791838
0.845829
1.10449
1.08712
0.85945
0.743887
0.615558
0.992993
1.24892
1.51497
0.983335
0.834775
1.22813
1.24781
0.760231
0.67767
1.25154
1.1457
1.11664
0.67807
0.985248
1.04868
1.08146
0.987468
0.773356
0.630878
0.970473
0.988608
0.931188
1.035
0.961362
0.846724
1.0479
1.00996
1.05493
1.04796
1.12831
1.0592
1.0477
1.06169
1.03548
0.994108
1.06735
1.0176
1.01687
0.993978
1.04952
0.817346
0.940736
1.03307
0.941419
1
1.09435
1.08316
1
1.08012
0.983871
1
0.937098
1.07855
0.961862
0.993073
0.659683
1
0.875514
1
0.613214
1.03447
0.650898
1.20774
1.20236
1.08149
0.88267
1.0286
1.03565
1.05657
0.984911
1.15695
0.808017
0.870194
1.17128
0.706755
0.876828
1.00009
1
0.79689
1.07777
1.06461
1.13205
1.15329
0.972118
0.103836
0.105938
2.30982
0.996292
0.999425
1.45644
0.987976
0.676322
1.00512
1.01802
1.00443
0.688738
1.01485
0.857657
1.04065
1.12499
1.15611
0.99173
1.08364
0.708679
1.01314
1.0042
1.00301
0.961908
1
0.951625
0.963254
0.473852
0.914932
0.40849
0.983177
0.964985
1.01614
0.923558
0.961628
0.960084
0.876503
0.862017
0.920462
0.916419
0.87631
1
0.599496
0.623195
1.40118
1.00104
1.05824
0.989189
0.568331
0.833553
0.414445
1.04011
1.05748
0.961516
0.928845
0.791894
1
0.705751
1
1
0.964287
0.956414
0.766344
1
0.54771
0.973501
1
1.0491
0.927601
0.939265
0.947513
0.99992
0.967456
1
1.05586
1.0055
1.00337
0.994563
0.999197
0.74821
1.00926
1.06231
0.828637
1.00908
0.960079
1.28417
1
1
1.036
1.01513
1.02801
1.00657
1.04262
1.02297
1.06699
1.05183
1.02594
1.00039
1.06641
0.917396
0.994376
1.01231
0.991075
1.07202
1
0.799644
1.08562
0.985461
0.964867
0.938546
0.876043
1.06325
1.11691
0.894145
1.06845
1.17535
1.10554
1.01619
0.946441
1.00704
0.995544
0.992534
1.01119
1.02186
0.992556
1.1237
0.983089
0.963043
0.614513
0.982728
0.605855
1.04847
0.839612
1
0.924606
0.97697
0.832229
0.985156
0.828223
0.896204
0.992895
0.997966
1.02091
0.991514
0.970919
1.01727
1.02264
0.999958
0.795099
1
1.32442
1.02895
1.07049
1.06965
1.04604
1.01284
0.968222
0.999211
0.999536
1.00096
0.672352
1.14499
1.15647
1.09891
0.954901
1.10867
0.677493
1.10115
0.998083
1.08277
0.752765
0.886412
1.17947
1.2962
1.04494
1.02892
1.03108
1.02016
1.03619
1.0773
0.978755
1.01036
1.23745
1.02352
1.1563
0.853335
0.884957
1.30261
1.01915
0.957816
1.08594
1.52139
1.08057
1.00182
1.07259
0.914962
1.03131
1.01244
1.04877
0.910899
0.993919
0.981338
1.09433
1.08929
0.866146
1.12435
0.893676
1.0078
0.78846
0.994698
1.05124
0.922271
1.0524
0.953139
1.06134
1.08245
0.909604
1.04242
1.11511
0.920779
0.979402
0.95737
0.971905
1.02415
0.997892
0.742201
0.732375
1.03148
1.06224
1
1.09994
1.04162
1.01051
1.09407
0.891078
0.787781
1.04396
1
1.1467
1.12128
0.928035
1.02445
0.976925
0.958965
0.848368
1.11729
1.15652
1.03229
0.936831
1.0266
1.04786
0.981343
0.731651
1.05294
0.582386
1.10395
0.818012
1
0.976996
1.04883
1.25978
1.13541
0.865718
1.08229
1
0.998657
0.993874
1
0.999157
0.951062
0.931825
0.931825
0.852091
1.01489
1.00836
1.01925
1.04267
1.02663
1.02759
1.03921
1.00626
1.02088
1.02764
1.03104
0.836358
0.926572
1.02344
1.16688
0.990453
0.942681
1.05553
0.873252
1.19199
1.15022
1.01095
1.00705
1.09311
0.892471
0.9202
0.999699
1.17484
0.995042
1.0726
0.998138
0.865637
0.888229
0.856568
0.754867
1.16534
1.17266
1.03361
1.02859
0.751377
0.691684
1.28886
0.642267
1.02264
1.14235
1.19455
1.01168
0.632784
0.620707
1.10988
1.17685
0.670727
0.845474
1.0717
0.856682
1.12495
0.958367
0.976869
1.03365
1.00061
0.928341
1
1.07157
0.861285
0.936845
1.00524
1.01615
1.05744
1.05602
1.2091
1.01904
1.04888
0.760847
0.989528
1.17904
0.978208
0.827156
1.15205
1.11926
1.10116
1.44117
1.03732
1.09762
0.974667
1.02954
0.94646
0.999995
1.03485
1.07718
1.09398
1.00915
0.791839
0.803147
1.10287
0.999987
1.05321
1.07772
1.01905
1.02908
1.03396
1.00325
0.996197
1.0407
1.05413
1.17616
0.830894
0.877055
1.07873
0.915285
1.10487
1.22754
1.04341
1.02559
1.1379
1.02049
1.14168
1.05384
1.07817
1.06835
1.00542
0.985771
0.859356
0.888834
0.584581
1.47905
1.01326
0.998848
1.02624
1.06546
0.944789
0.994087
0.967742
1.00257
1.02124
1.02062
1.00714
1.0231
1.03337
1.03018
0.977541
0.973447
1.03441
1.03181
1.07072
1.03938
1.0164
0.956091
0.939344
0.961615
0.994766
1.0029
1.00587
1.01943
1.00377
1.02147
0.96987
1.03242
0.951651
0.999965
1.00941
1.01972
1.02521
1.00261
1.05781
0.997733
0.955271
0.971485
1.25023
0.988813
0.905079
1
1
0.87847
1.14669
1.96429
0.584325
0.549598
0.347382
1.06764
0.265061
1.35325
1.00928
1.04314
1.04429
1.04727
1.00933
1.02727
1.49688
0.974873
0.992422
0.967331
0.986824
0.909246
1
0.901123
1
1.0102
1
0.938393
1
1.09701
1.08025
0.927641
0.90084
0.927102
0.886431
0.951441
0.996535
0.996695
1.02326
1.03741
1.03649
1.05401
1.01833
1.10054
1.0929
1
0.844836
1.12655
1.32938
0.487438
0.447698
1.34549
1.03874
1
1.04031
1.07836
1.03149
1
1.04723
1.17522
1
1.1777
1.01849
0.860279
0.966138
0.793902
1.00358
0.991117
0.926936
1.02873
1.02245
1.05683
0.976876
1.22845
1.04342
0.880252
1.02952
1.16063
1.03387
1.19398
1.0253
1.18957
1.0242
1.07289
0.861207
0.986481
1.03189
1.01153
1.08355
1.13503
1.13374
1.13267
1.0081
1.06469
0.480867
1.03898
0.928679
1.29402
0.405228
1.08816
0.935298
0.655449
1.00847
0.939173
0.986955
0.66167
1.03702
0.798715
1
0.942771
1.02708
0.990129
1.04176
0.944801
1
0.655529
0.993773
1.03174
1.12426
1.05685
0.967946
0.660017
0.862215
1.06792
0.846915
1.29952
1.18965
0.987481
0.760315
0.70751
1.22076
0.984476
1.31797
1.23236
0.974694
1.08624
0.760031
0.931781
1.13411
0.964112
0.929351
0.999991
0.961325
0.90944
0.97647
0.961224
1.094
1.19012
0.994667
1.23189
1.00805
1.06412
1.0005
1.04271
1.05062
0.950255
0.943945
1.09329
0.551981
0.971996
1.0565
1.05884
1.15403
0.992746
1.02591
1.01711
1.05521
1.12334
1.08622
1.10419
1.07925
1.04087
1.0458
1.03729
1.03559
0.873181
0.981638
1.05865
1.03248
1.19093
1.16181
1.05122
1.07976
1.00355
1.03908
1.19079
0.913145
0.916298
1.04852
1.08845
0.750967
0.912293
1.08795
1.26213
1.3636
0.982384
0.948137
0.702312
0.8806
0.921017
0.756434
1
1.01495
1.03645
1.49632
1.09269
0.873135
1.01752
0.867331
0.869362
0.954098
1.2415
1.28604
0.942779
0.681785
0.77332
1
1.53535
1.69213
1.135
0.976889
1
0.745798
0.912441
0.780491
1
0.981481
1.00462
1.15153
1.12593
1.15791
1.08981
1.13342
1.04917
1.02692
0.990326
1.05174
0.795515
1.03104
1.06397
1.06065
0.767593
1.00556
0.999977
0.975284
1.06573
1.13963
1.00629
1.23937
1.01277
1.3302
1
0.952662
0.795856
0.996003
0.991324
0.982625
1.0743
0.889863
0.673735
0.952534
1.02405
1.07067
1.06331
0.986757
0.7844
0.832435
0.964251
1.03755
0.912208
1.13654
1.00537
1.1872
0.942197
1.0195
0.969328
1.10395
0.988119
1.03036
0.932732
0.935581
0.948187
1
1.02455
1.02203
1.04271
1.03636
1.03987
1.02061
1.02868
0.877534
1.94571
1
0.580224
0.839824
1.02819
0.889304
1.02781
0.842203
1.05652
0.723716
1.04276
1.02063
1.00233
0.760031
0.960128
0.96119
0.981102
0.915067
0.863366
0.847911
0.942515
0.929723
1.61314
0.798279
1.08253
0.824352
0.855951
1.04879
1.28935
1.47472
0.787476
0.609516
0.977367
0.957939
1
0.75948
1.14672
1.0614
1.02504
1.13539
1.09346
1.01126
1.14281
1.1404
1.06164
1.02346
1.10547
1
0.782514
0.748208
0.85963
0.760559
0.982911
0.845738
0.922399
1.0701
1.69231
1.12124
0.815246
1.03171
1.74721
0.496219
1.04771
1.02109
1.01706
1.20095
1.10992
1.05224
1.17105
1.09322
1.09825
1.10718
1.08051
1.03785
1.04319
1.06624
1.15355
0.95799
1.15786
0.969916
1.14023
1.05016
1.03915
1.0031
1.13251
1.05577
1.062
1.04689
1.07721
1.20366
1.08179
0.788502
1.11186
1.08501
1.10337
0.78111
1.14691
2.10373
1.05985
1.19432
0.525013
0.776544
0.412739
0.92736
1.03376
0.976058
1.02407
1.04517
0.832363
1.07616
0.984382
1.09656
1.02129
1.0544
1.24106
1.05037
1.08219
1.09044
1.05362
1.01977
1.03399
1
1
1
1
1.07155
1.40341
0.515566
0.931257
1.19479
0.60859
1.11695
0.913151
0.968698
0.65741
1.02615
1.00802
1.41236
1.15187
0.961642
1.03197
1
1.01582
0.746222
0.752167
0.999211
0.542915
1.11756
0.6787
0.982747
0.962124
1.13472
1.04953
0.961969
0.963636
0.814176
0.999948
1.10844
1.12286
1.06723
1
1.315
0.88711
1.35511
1.27259
1
0.999686
1.00455
1.0066
1.06861
1.00705
1.10547
1
0.973648
0.961246
0.999663
1
1.00998
1.04522
1.29773
1.19437
1.06209
0.938908
0.994424
0.976616
1.06021
1.09639
0.985569
1.00322
1.00321
1.03932
0.988891
1.01532
1.05038
0.97512
1
1.00274
0.831564
0.950964
0.997034
1
1
1.941
1.25584
0.506993
0.52409
0.738027
0.999302
0.302299
0.963106
0.93138
0.781241
1.0036
0.973652
0.92118
1.07619
1
0.929771
1.05223
0.818751
1.03558
0.803165
1.03932
0.999999
1.12254
1
0.968917
1.04753
0.929557
1.01694
1.22903
0.483908
0.636156
0.976117
0.974679
2.1574
1
0.973007
0.999986
0.990922
1
0.944557
1.03273
1.25028
1.36928
1.17752
1
1
1.09062
1.26128
1.00697
0.951802
1.00621
1.0137
0.968515
0.996229
1.07266
1.05093
1.083
1.33103
1.2518
1.09589
1.01556
1.08517
1.13176
0.513021
0.853582
0.984547
1.2813
1.25477
0.926814
1.05227
0.857566
1.01935
1.10373
1.09781
1.17739
1.32814
0.883816
1
1
1.66521
1.06862
1
1.17856
1.04705
1.01765
1.01795
1.03041
1.01891
1.00574
1.03336
1.00708
1.00675
1.00987
1.02886
1.00197
0.998597
1.02132
1.03476
1.06082
1.30651
0.637285
1.03299
1
1.17699
0.823514
0.903065
1.02496
1.11259
0.99992
1.24288
1
1.20993
1.32722
1.0482
1.26194
0.503126
0.723215
0.638286
1.54046
1.33367
1.05348
0.961003
1.25671
1.10174
0.758575
1.44824
0.696923
0.737535
0.760457
1.14958
0.849541
1
0.758826
0.751615
0.940005
0.994628
0.847952
0.831486
0.644133
1.02994
1.00999
0.909381
0.732048
1.01175
0.865073
0.999786
1.02961
0.906853
0.860404
0.869283
0.849354
0.746916
0.962574
1.30525
1.12009
1.01521
0.996628
1.03208
1.02173
1.21607
1.03693
0.999278
1.1853
0.999689
0.944605
0.836478
0.956642
0.917223
0.754193
0.973462
1.17482
1.65288
1.12295
1.44092
1.51521
1.09916
1.25503
1.26525
1.06985
0.909368
1.18704
1.07881
1.09749
1.14301
1.31019
1.09256
1.0314
1.15539
1.11989
0.56658
0.823648
0.998988
1.12344
0.959132
1.00002
1
1.27036
1.06867
1.37573
1.2155
1.16823
1
1.11724
1.11553
1.04965
1.0572
1.01125
1.01996
1.05315
1.11119
)
;
boundaryField
{
inlet
{
type inletOutlet;
inletValue uniform 1;
value uniform 1;
}
outlet
{
type inletOutlet;
inletValue uniform 0;
value nonuniform List<scalar>
30
(
2.40389e-142
8.54292e-144
9.3055e-144
9.02526e-141
1.34407e-139
2.69608e-141
1.39083e-140
7.55987e-144
2.0236e-144
4.25907e-144
1.66292e-138
1.19366e-139
1.82391e-137
1.47877e-136
5.57508e-135
1.22643e-134
1.06281e-136
2.9684e-137
6.72836e-140
6.74167e-139
2.23609e-142
3.76179e-145
9.96989e-142
2.5812e-142
1.41908e-138
4.21873e-140
2.69222e-140
3.56215e-144
5.45269e-144
1.51165e-144
)
;
}
lowerWall
{
type zeroGradient;
}
upperWall
{
type zeroGradient;
}
frontWall
{
type cyclic;
}
backWall
{
type cyclic;
}
}
// ************************************************************************* //
| [
"daihui.lu2016@gmail.com"
] | daihui.lu2016@gmail.com |
1da46b3e06884af623c4b7118fdbb4069dec6a52 | 15b0fc3b56e2ec2b22ff308f4f1e516f0f86665d | /Source/Core/Properties/Vec2Property.h | fc33c18c284c431e9ee78d039861d7dc8ec6685c | [] | no_license | thavlik/iridium | c636166077a94d4658851c6ff4639762d84175ff | 8051e7ed6aefd42552e5737aff3d20fd0b844eda | refs/heads/master | 2020-04-06T03:40:22.689918 | 2013-09-29T16:09:15 | 2013-09-29T16:09:15 | 11,291,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | h | #pragma once
#include "Property.h"
#include "../../Common/Vectors.h"
namespace Ir {
class Vec2Property : public Property {
public:
FloatProperty X, Y;
Vec2Property() {
OBJECT_PROPERTY( X );
OBJECT_PROPERTY( Y );
}
operator vec2f() const { return vec2f((float)X, (float)Y); }
};
} | [
"keres@live.com"
] | keres@live.com |
186bfc78d00adf35e9b5c034d61e64260c366065 | 5d28a72c2fad854f22f17f88a4106752d7b7b6c3 | /RPNCalculator/uipilevarview.cpp | c2f0373c8cbda90a6b2e71c7db7fb4d34ca108fe | [
"MIT"
] | permissive | pauljeannot/RPNCalculator | 0be63b1a1b06275f7e61b69dece1bd9a6886e443 | d13c50f0bf0e571c73e061f6369030cfa4210221 | refs/heads/master | 2021-03-27T11:43:13.974358 | 2016-06-08T12:44:06 | 2016-06-08T12:44:06 | 58,167,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,118 | cpp | #include "uipilevarview.h"
#include "ltprogramme.h"
#include "ltexpression.h"
#include "ltatomemanager.h"
void UIPileVarView::addItem(QTableWidgetItem* item) {
int newRow = this->rowCount();
this->insertRow(newRow);
item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
this->setItem(newRow, 0, item);
items.append(item);
this->refreshHeaderLabels(type);
}
void UIPileVarView::reloadView(const QString &type) {
LTAtomeManager& ctl = LTAtomeManager::getInstance();
QMap<QString, LTAtome*> map = ctl.getDictionnary();
int nbLines = getTailleVar(map, type);
while(this->rowCount() > 0)
this->removeRow(0);
items.clear();
int j = 0;
QMapIterator<QString, LTAtome*> i(map);
while(i.hasNext()) {
i.next();
std::cout << i.value()->getEnumString().toStdString() << std::endl;
if (i.value()->getEnumString() == type) {
this->addItem(new QTableWidgetItem(i.value()->getPointer()->getText()));
j++;
}
}
this->refreshHeaderLabels(type);
}
void UIPileVarView::refreshHeaderLabels(const QString& type) {
QStringList liste;
LTAtomeManager& ctl = LTAtomeManager::getInstance();
QMap<QString, LTAtome*> map = ctl.getDictionnary();
QMapIterator<QString, LTAtome*> i(map);
QString str;
while(i.hasNext()) {
i.next();
if (i.value()->getEnumString() == type) {
str = i.key();
liste << str;
}
}
this->setVerticalHeaderLabels(liste);
}
void UIPileVarView::clearAll(){
LTAtomeManager::getInstance().removeAllFromDictionnary();
while(this->rowCount() > 0)
this->removeRow(0);
items.clear();
XMLManager::getInstance().saveXMLFileAtomeManager();
}
int UIPileVarView::getTailleVar(QMap<QString, LTAtome*> M, const QString& type){
QMapIterator<QString, LTAtome*> i(M);
int taille = 0;
while(i.hasNext()) {
i.next();
if (i.value()->getEnumString() == type) {
taille++;
}
}
return taille;
}
| [
"floriancartier11@gmail.com"
] | floriancartier11@gmail.com |
b048a8dc4235f5a1fe8444edd6ef255840d1bb53 | 6260fd43890ca288271cdc5fb8db2cea9e2297d1 | /project2/project2_1.cc | f69723da5a92fdbd705b8153e0eaf71109c21acc | [] | no_license | tzhzcd/ns3-lec-project | 5cf0664bd54bf8c76f00f4a996a479d730379c42 | b44776b93ac64dac21888e08ee667773f749400e | refs/heads/master | 2021-01-17T18:45:35.433774 | 2016-07-04T11:31:19 | 2016-07-04T11:31:19 | 61,208,486 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,118 | cc | /*
ns-3培训 2016.6
参考程序:third.cc
更改:wifi的移动模型改为匀速;客户端安装在全部4个节点上
*/
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
// Default Network Topology
//默认网络拓扑
// Number of wifi or csma nodes can be increased up to 250
// |
// Rank 0 | Rank 1
// -------------------------|----------------------------
// Wifi 10.1.3.0
// AP
// * * * *
// | | | | 10.1.1.0
// n5 n6 n7 n0 ------------------ n1 n2 n3 n4
// point-to-point | | | |
// ================
// LAN 10.1.2.0
using namespace ns3;
//注册记录组件
NS_LOG_COMPONENT_DEFINE ("project2_1");
int
main (int argc, char *argv[])
{
bool verbose = true;//logging系统日志功能开启,输出系统信息
uint32_t nCsma = 3;
uint32_t nWifi = 3;
bool tracing = true;//记录设备设备信息功能开启,生产相应文件
CommandLine cmd;
cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
cmd.AddValue ("tracing", "Enable pcap tracing", tracing);
cmd.Parse (argc,argv);
if (nWifi > 250 || nCsma > 250)
{
std::cout << "Too many wifi or csma nodes, no more than 250 each." << std::endl;
return 1;
}
//详见logging
if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
}
NodeContainer p2pNodes;
p2pNodes.Create (2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));
NetDeviceContainer csmaDevices;
csmaDevices = csma.Install (csmaNodes);
NodeContainer wifiStaNodes;
wifiStaNodes.Create (nWifi);
NodeContainer wifiApNode = p2pNodes.Get (0);
YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
phy.SetChannel (channel.Create ());
WifiHelper wifi = WifiHelper::Default ();
wifi.SetRemoteStationManager ("ns3::AarfWifiManager");
NqosWifiMacHelper mac = NqosWifiMacHelper::Default ();
Ssid ssid = Ssid ("ns-3-ssid");
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
NetDeviceContainer staDevices;
staDevices = wifi.Install (phy, mac, wifiStaNodes);
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
NetDeviceContainer apDevices;
apDevices = wifi.Install (phy, mac, wifiApNode);
//配置移动模型,起始位置
MobilityHelper mobility;
/*
//此段为设置节点初始位置,以(0,0)为第一位置,横间距为5,纵间距为10,每行排3个节点
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (5.0),
"DeltaY", DoubleValue (10.0),
"GridWidth", UintegerValue (3),
"LayoutType", StringValue ("RowFirst"));
*/
//配置STA移动方式,ConstantVelocityMobilityModel,固定速度模型
mobility.SetMobilityModel ("ns3::ConstantVelocityMobilityModel");
mobility.Install (wifiStaNodes);
//设置必要参数,先设初始位置,后设初始时间。
for (uint n = 0; n < wifiStaNodes.GetN(); n++)
{
Ptr<ConstantVelocityMobilityModel> mob = wifiStaNodes.Get(n)->GetObject<ConstantVelocityMobilityModel>();
mob->SetPosition(Vector(0.0, 0.0, 0.0));
mob->SetVelocity(Vector(n/2.0+0.5, 0.0, 0.0));
}
//配置AP移动方式,ConstantPositionMobilityModel,固定位置模型
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);
//设置初始位置
Ptr<ConstantPositionMobilityModel> mob = wifiApNode.Get(0)->GetObject<ConstantPositionMobilityModel>();
mob->SetPosition(Vector(0.0, 0.0, 0.0));
InternetStackHelper stack;
stack.Install (csmaNodes);
stack.Install (wifiApNode);
stack.Install (wifiStaNodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);
address.SetBase ("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer csmaInterfaces;
csmaInterfaces = address.Assign (csmaDevices);
address.SetBase ("10.1.3.0", "255.255.255.0");
address.Assign (staDevices);
address.Assign (apDevices);
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
//安装客户端程序到节点,需要重复定义。
ApplicationContainer clientApps_1 =
echoClient.Install (wifiApNode);
clientApps_1.Start (Seconds (2.0));
clientApps_1.Stop (Seconds (10.0));
ApplicationContainer clientApps_2 =
echoClient.Install (wifiStaNodes.Get(0));
clientApps_2.Start (Seconds (2.0));
clientApps_2.Stop (Seconds (10.0));
ApplicationContainer clientApps_3 =
echoClient.Install (wifiStaNodes.Get(1));
clientApps_3.Start (Seconds (2.0));
clientApps_3.Stop (Seconds (10.0));
ApplicationContainer clientApps_4 =
echoClient.Install (wifiStaNodes.Get(2));
clientApps_4.Start (Seconds (3.0));
clientApps_4.Stop (Seconds (10.0));
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
//详见tracing设备信息功能
Simulator::Stop (Seconds (10.0));
if (tracing == true)
{
pointToPoint.EnablePcapAll ("project2_1");
phy.EnablePcap ("project2_1", apDevices.Get (0));
csma.EnablePcap ("project2_1", csmaDevices.Get (0), true);
}
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| [
"=2507471575@qq.com"
] | =2507471575@qq.com |
cb7321991a48ae6641688e4719f355e4f85ce336 | a6327821e2d2ef7cf4b37b7b6b9b891d99a4c0f9 | /CGALib/include/Headers/ShadowBox.h | 31cb0f62c7d8b22d1839addd400cdb277d1721ca | [] | no_license | rmartella/ComputacionGraficaAvanzada | 7f6d963b718ce3a6d0c2b8ba8093e07811fa2df7 | 5bd1724abadf1eee4fbb7f129635aee8bc26381c | refs/heads/master | 2023-08-29T00:05:20.279180 | 2023-08-26T08:16:53 | 2023-08-26T08:16:53 | 120,414,145 | 5 | 129 | null | 2023-08-26T08:16:54 | 2018-02-06T06:51:48 | C | UTF-8 | C++ | false | false | 1,163 | h | #include "Camera.h"
#ifndef SHADOWBOX_H_
#define SHADOWBOX_H_
#if defined _WIN32 || defined __CYGWIN__
#ifdef BUILDING_DLL
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllexport))
#else
#define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
#endif
#else
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllimport))
#else
#define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
#endif
#endif
#define DLL_LOCAL
#else
#if __GNUC__ >= 4
#define DLL_PUBLIC __attribute__ ((visibility ("default")))
#define DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define DLL_PUBLIC
#define DLL_LOCAL
#endif
#endif
class DLL_PUBLIC ShadowBox{
public:
ShadowBox(glm::vec3 direction, Camera * camera, float shadowDistance, float nearPlane, float fovy);
void update(int screenWidth, int screenHeight);
glm::vec3 getCenter();
float getWidth();
float getHeight();
float getLength();
private:
glm::vec3 front;
glm::vec3 up;
glm::vec3 right;
glm::vec3 mins;
glm::vec3 maxs;
Camera *camera;
float shadowDistance;
float nearPlane;
float fovy;
};
#endif /* SHADOWBOX_H_ */
| [
"reymar_44@hotmail.com"
] | reymar_44@hotmail.com |
fa91e87b3f1e9398075196d9c7b5631c0e1bf7f3 | fe5e4748939432af1d691f9d5837206fbf6c6c2f | /C++/C/c_toys.cpp | 85ab3b31e30f4fc6260feaee38895716e2e82c6d | [] | no_license | soadkhan/My-Code | e0ebe0898d68df983e8c41e56633780d6ac22c39 | 72fc258cdbf08d86f20a565afe371713e8e8bc39 | refs/heads/master | 2021-01-23T03:27:34.181019 | 2017-03-24T14:42:15 | 2017-03-24T14:42:15 | 86,077,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,886 | cpp |
#include<bits/stdc++.h>
using namespace std;// third parameter of sort ..... jei operator er jonno true sevabe kaj korbe .... sekhane caile condition lagano jabe ....
long long int se_si;
bitset<10>bs;//boundary is the size ....... use in prime
vector<long long int>primes; // use in prime
typedef unsigned long long int ull;
typedef long long int ll;
#define fs first
#define sc second
#define sp printf(" ")
#define nl printf("\n")
#define pb(a) push_back(a)
//setting an array or a vector
#define setzero(a) memset(a,0,sizeof(a))
#define setneg(a) memset(a,-1,sizeof(a))
#define setinf(a) memset(a,126,sizeof(a))
// different types of case printing
#define tc1(x) printf("Case %d: ",x)
#define tc2(x) printf("Case #%d: ",x)
#define tc3(x) printf("Case %d:\n",x)
#define tc4(x) printf("Case #%d:\n",x)
//input
#define ini(x) scanf("%d",&x)
#define ind(x) scanf("%lf",&x)
#define inll(x) scanf("%lld",&x)
#define incll(x) scanf("%I64d",&x)
#define inch(x) scanf("%c" , &x)
#define instr(x) scanf("%s" , &x)
//printing in cout
#define pr1(x) cout<<x<<"\n"
#define pr2(x,y) cout<<x<<" "<<y<<"\n"
#define pr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n"
#define pr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<"\n"
#define fast ios::sync_with_stdio(0)
//output
#define outi(x) printf("%d" , x)
#define outll(x) printf("%lld" x)
#define outch(x) printf("%c" , x)
#define outstr(x) printf("%s" , x)
// file input and output
#define read freopen("uva.txt","r",stdin)
#define write freopen("uva_out.txt","w",stdout)
//common looping
#define rep1(n ,i) for(ll i = 1 ; i<=n ; i++ )
#define rep0(n ,i) for(ll i = 0 ; i<n ; i++ )
// graph pros
int dx4[]= {1,-1,0,0};
int dy4[]= {0,0,1,-1};
int dx6[]= {0,0,1,-1,0,0};
int dy6[]= {1,-1,0,0,0,0};
int dz6[]= {0,0,0,0,1,-1};
long long int pw(long long int a,long long int b) {long long int sum=1;for(long long int i=0; i<b; i++) {sum*=a;}return sum;}
long long int gcd(long long int a,long long int b) {if(a%b==0) return b;else return gcd(b,a%b);}
void sieve(long long int up) {se_si=up+1;bs.set();bs[0]=0;bs[1]=0;for(long long int i=2; i<=se_si; i++)if(bs[i]) {for(long long int j=i*i; j<=se_si; j+=i)bs[j]=0;primes.push_back(i);}}
bool is_prime(long long int n) {if(n<=se_si)return bs[n];long long int l=primes.size();for(long long int i=0; i<l; i++)if(n%primes[i]==0)return false;return true;}
int main(void) {
ll n ; ll k ;
ll cost = 0 ;
inll(n) ; inll(k) ;
map<ll , ll>lists ;
for(ll i = 0 ; i< n ; i++){
ll a;
inll(a) ;
lists[a]++;
}
for(ll i = 1 ; i<=1000000010 ; i++){
}
return 0;
}
| [
"khancse5914@gmail.com"
] | khancse5914@gmail.com |
05e5e1969fbe81acfb1d7c8840dec950214d24f6 | ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd | /third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc | 97cd6be10e459289fe87053527faa00af728aa98 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | laien529/chromium | c9eb243957faabf1b477939e3b681df77f083a9a | 3f767cdd5c82e9c78b910b022ffacddcb04d775a | refs/heads/master | 2022-11-28T00:28:58.669067 | 2020-08-20T08:37:31 | 2020-08-20T08:37:31 | 288,961,699 | 1 | 0 | BSD-3-Clause | 2020-08-20T09:21:57 | 2020-08-20T09:21:56 | null | UTF-8 | C++ | false | false | 58,591 | cc | // Copyright 2018 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 "third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.h"
#include <memory>
#include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_button.h"
#include "third_party/blink/renderer/core/layout/layout_flexible_box.h"
#include "third_party/blink/renderer/core/layout/ng/flex/ng_flex_child_iterator.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
NGFlexLayoutAlgorithm::NGFlexLayoutAlgorithm(
const NGLayoutAlgorithmParams& params)
: NGLayoutAlgorithm(params),
is_column_(Style().ResolvedIsColumnFlexDirection()),
is_horizontal_flow_(FlexLayoutAlgorithm::IsHorizontalFlow(Style())),
is_cross_size_definite_(IsContainerCrossSizeDefinite()) {
container_builder_.SetIsNewFormattingContext(
params.space.IsNewFormattingContext());
border_box_size_ = container_builder_.InitialBorderBoxSize();
child_percentage_size_ = CalculateChildPercentageSize(
ConstraintSpace(), Node(), ChildAvailableSize());
algorithm_.emplace(&Style(), MainAxisContentExtent(LayoutUnit::Max()),
child_percentage_size_, &Node().GetDocument());
}
bool NGFlexLayoutAlgorithm::MainAxisIsInlineAxis(
const NGBlockNode& child) const {
return child.Style().IsHorizontalWritingMode() ==
FlexLayoutAlgorithm::IsHorizontalFlow(Style());
}
LayoutUnit NGFlexLayoutAlgorithm::MainAxisContentExtent(
LayoutUnit sum_hypothetical_main_size) const {
if (Style().ResolvedIsColumnFlexDirection()) {
// Even though we only pass border_padding in the third parameter, the
// return value includes scrollbar, so subtract scrollbar to get content
// size.
// We add |border_scrollbar_padding| to the fourth parameter because
// |content_size| needs to be the size of the border box. We've overloaded
// the term "content".
const LayoutUnit border_scrollbar_padding =
BorderScrollbarPadding().BlockSum();
return ComputeBlockSizeForFragment(
ConstraintSpace(), Style(), BorderPadding(),
sum_hypothetical_main_size.ClampNegativeToZero() +
border_scrollbar_padding,
border_box_size_.inline_size) -
border_scrollbar_padding;
}
return ChildAvailableSize().inline_size;
}
namespace {
enum AxisEdge { kStart, kCenter, kEnd };
// Maps the resolved justify-content value to a static-position edge.
AxisEdge MainAxisStaticPositionEdge(const ComputedStyle& style,
bool is_column) {
const StyleContentAlignmentData justify =
FlexLayoutAlgorithm::ResolvedJustifyContent(style);
const ContentPosition content_position = justify.GetPosition();
bool is_reverse_flex = is_column
? style.ResolvedIsColumnReverseFlexDirection()
: style.ResolvedIsRowReverseFlexDirection();
if (content_position == ContentPosition::kFlexEnd)
return is_reverse_flex ? AxisEdge::kStart : AxisEdge::kEnd;
if (content_position == ContentPosition::kCenter ||
justify.Distribution() == ContentDistributionType::kSpaceAround ||
justify.Distribution() == ContentDistributionType::kSpaceEvenly)
return AxisEdge::kCenter;
return is_reverse_flex ? AxisEdge::kEnd : AxisEdge::kStart;
}
// Maps the resolved alignment value to a static-position edge.
AxisEdge CrossAxisStaticPositionEdge(const ComputedStyle& style,
const ComputedStyle& child_style) {
ItemPosition alignment =
FlexLayoutAlgorithm::AlignmentForChild(style, child_style);
// AlignmentForChild already accounted for wrap-reverse for kFlexStart and
// kFlexEnd, but not kStretch. kStretch is supposed to act like kFlexStart.
if (style.FlexWrap() == EFlexWrap::kWrapReverse &&
alignment == ItemPosition::kStretch) {
return AxisEdge::kEnd;
}
if (alignment == ItemPosition::kFlexEnd)
return AxisEdge::kEnd;
if (alignment == ItemPosition::kCenter)
return AxisEdge::kCenter;
return AxisEdge::kStart;
}
} // namespace
void NGFlexLayoutAlgorithm::HandleOutOfFlowPositioned(NGBlockNode child) {
AxisEdge main_axis_edge = MainAxisStaticPositionEdge(Style(), is_column_);
AxisEdge cross_axis_edge =
CrossAxisStaticPositionEdge(Style(), child.Style());
AxisEdge inline_axis_edge = is_column_ ? cross_axis_edge : main_axis_edge;
AxisEdge block_axis_edge = is_column_ ? main_axis_edge : cross_axis_edge;
using InlineEdge = NGLogicalStaticPosition::InlineEdge;
using BlockEdge = NGLogicalStaticPosition::BlockEdge;
InlineEdge inline_edge;
BlockEdge block_edge;
LogicalOffset offset = BorderScrollbarPadding().StartOffset();
// Determine the static-position based off the axis-edge.
if (inline_axis_edge == AxisEdge::kStart) {
inline_edge = InlineEdge::kInlineStart;
} else if (inline_axis_edge == AxisEdge::kCenter) {
inline_edge = InlineEdge::kInlineCenter;
offset.inline_offset += ChildAvailableSize().inline_size / 2;
} else {
inline_edge = InlineEdge::kInlineEnd;
offset.inline_offset += ChildAvailableSize().inline_size;
}
// We may not know the final block-size of the fragment yet. This will be
// adjusted within the |NGContainerFragmentBuilder| once set.
if (block_axis_edge == AxisEdge::kStart) {
block_edge = BlockEdge::kBlockStart;
} else if (block_axis_edge == AxisEdge::kCenter) {
block_edge = BlockEdge::kBlockCenter;
offset.block_offset -= BorderScrollbarPadding().BlockSum() / 2;
} else {
block_edge = BlockEdge::kBlockEnd;
offset.block_offset -= BorderScrollbarPadding().BlockSum();
}
container_builder_.AddOutOfFlowChildCandidate(child, offset, inline_edge,
block_edge);
}
bool NGFlexLayoutAlgorithm::IsColumnContainerMainSizeDefinite() const {
DCHECK(is_column_);
// If this flex container is also a flex item, it might have a definite size
// imposed on it by its parent flex container.
// We can't rely on BlockLengthUnresolvable for this case because that
// considers Auto as unresolvable even when the block size is fixed and
// definite.
if (ConstraintSpace().IsFixedBlockSize() &&
!ConstraintSpace().IsFixedBlockSizeIndefinite())
return true;
Length main_size = Style().LogicalHeight();
return !BlockLengthUnresolvable(ConstraintSpace(), main_size,
LengthResolvePhase::kLayout);
}
bool NGFlexLayoutAlgorithm::IsContainerCrossSizeDefinite() const {
// A column flexbox's cross axis is an inline size, so is definite.
if (is_column_)
return true;
// If this flex container is also a flex item, it might have a definite size
// imposed on it by its parent flex container.
// TODO(dgrogan): Removing this check doesn't cause any tests to fail. Remove
// it if unneeded or add a test that needs it.
if (ConstraintSpace().IsFixedBlockSize() &&
!ConstraintSpace().IsFixedBlockSizeIndefinite())
return true;
return !BlockLengthUnresolvable(ConstraintSpace(), Style().LogicalHeight(),
LengthResolvePhase::kLayout);
}
bool NGFlexLayoutAlgorithm::DoesItemStretch(const NGBlockNode& child) const {
if (!DoesItemCrossSizeComputeToAuto(child))
return false;
const ComputedStyle& child_style = child.Style();
// https://drafts.csswg.org/css-flexbox/#valdef-align-items-stretch
// If the cross size property of the flex item computes to auto, and neither
// of the cross-axis margins are auto, the flex item is stretched.
if (is_horizontal_flow_ &&
(child_style.MarginTop().IsAuto() || child_style.MarginBottom().IsAuto()))
return false;
if (!is_horizontal_flow_ &&
(child_style.MarginLeft().IsAuto() || child_style.MarginRight().IsAuto()))
return false;
return FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kStretch;
}
bool NGFlexLayoutAlgorithm::IsItemFlexBasisDefinite(
const NGBlockNode& child) const {
const Length& flex_basis = child.Style().FlexBasis();
DCHECK(!flex_basis.IsAuto())
<< "This is never called with flex_basis.IsAuto, but it'd be trivial to "
"support.";
if (!is_column_)
return true;
return !BlockLengthUnresolvable(BuildSpaceForFlexBasis(child), flex_basis,
LengthResolvePhase::kLayout);
}
// This behavior is under discussion: the item's pre-flexing main size
// definiteness may no longer imply post-flexing definiteness.
// TODO(dgrogan): Have https://crbug.com/1003506 and
// https://github.com/w3c/csswg-drafts/issues/4305 been resolved yet?
bool NGFlexLayoutAlgorithm::IsItemMainSizeDefinite(
const NGBlockNode& child) const {
DCHECK(is_column_)
<< "This method doesn't work with row flexboxes because we assume "
"main size is block size when we call BlockLengthUnresolvable.";
// Inline sizes are always definite.
// TODO(dgrogan): The relevant tests, the last two cases in
// css/css-flexbox/percentage-heights-003.html passed even without this, so it
// may be untested or unnecessary.
if (MainAxisIsInlineAxis(child))
return true;
// We need a constraint space for the child to determine resolvability and the
// space for flex-basis is sufficient, even though it has some unnecessary
// stuff (ShrinkToFit and fixed cross sizes).
return !BlockLengthUnresolvable(BuildSpaceForFlexBasis(child),
child.Style().LogicalHeight(),
LengthResolvePhase::kLayout);
}
bool NGFlexLayoutAlgorithm::IsItemCrossAxisLengthDefinite(
const NGBlockNode& child,
const Length& length) const {
// Inline min/max value of 'auto' for the cross-axis isn't definite here.
// Block value of 'auto' is always indefinite.
if (length.IsAuto())
return false;
// But anything else in the inline direction is definite.
if (!MainAxisIsInlineAxis(child))
return true;
// If we get here, cross axis is block axis.
return !BlockLengthUnresolvable(BuildSpaceForFlexBasis(child), length,
LengthResolvePhase::kLayout);
}
bool NGFlexLayoutAlgorithm::DoesItemCrossSizeComputeToAuto(
const NGBlockNode& child) const {
const ComputedStyle& child_style = child.Style();
if (is_horizontal_flow_)
return child_style.Height().IsAuto();
return child_style.Width().IsAuto();
}
// This function is used to handle two requirements from the spec.
// (1) Calculating flex base size; case 3E at
// https://drafts.csswg.org/css-flexbox/#algo-main-item : If a cross size is
// needed to determine the main size (e.g. when the flex item’s main size is
// in its block axis) and the flex item’s cross size is auto and not
// definite, in this calculation use fit-content as the flex item’s cross size.
// The flex base size is the item’s resulting main size.
// (2) Cross size determination after main size has been calculated.
// https://drafts.csswg.org/css-flexbox/#algo-cross-item : Determine the
// hypothetical cross size of each item by performing layout with the used main
// size and the available space, treating auto as fit-content.
bool NGFlexLayoutAlgorithm::ShouldItemShrinkToFit(
const NGBlockNode& child) const {
if (MainAxisIsInlineAxis(child)) {
// In this case, the cross size is in the item's block axis. The item's
// block size is never needed to determine its inline size so don't use
// fit-content.
return false;
}
if (!child.Style().LogicalWidth().IsAuto()) {
DCHECK(!DoesItemCrossSizeComputeToAuto(child));
// The cross size (item's inline size) is already specified, so don't use
// fit-content.
return false;
}
DCHECK(DoesItemCrossSizeComputeToAuto(child));
// If execution reaches here, the item's inline size is its cross size and
// computes to auto. In that situation, we only don't use fit-content if the
// item qualifies for the first case in
// https://drafts.csswg.org/css-flexbox/#definite-sizes :
// 1. If a single-line flex container has a definite cross size, the outer
// cross size of any stretched flex items is the flex container’s inner cross
// size (clamped to the flex item’s min and max cross size) and is considered
// definite.
if (WillChildCrossSizeBeContainerCrossSize(child))
return false;
return true;
}
bool NGFlexLayoutAlgorithm::WillChildCrossSizeBeContainerCrossSize(
const NGBlockNode& child) const {
return !algorithm_->IsMultiline() && is_cross_size_definite_ &&
DoesItemStretch(child);
}
double NGFlexLayoutAlgorithm::GetMainOverCrossAspectRatio(
const NGBlockNode& child) const {
DCHECK(child.HasAspectRatio());
LogicalSize aspect_ratio = child.GetAspectRatio();
DCHECK_GT(aspect_ratio.inline_size, 0);
DCHECK_GT(aspect_ratio.block_size, 0);
double ratio =
aspect_ratio.inline_size.ToDouble() / aspect_ratio.block_size.ToDouble();
// Multiplying by ratio will take something in the item's block axis and
// convert it to the inline axis. We want to convert from cross size to main
// size. If block axis and cross axis are the same, then we already have what
// we need. Otherwise we need to use the reciprocal.
if (!MainAxisIsInlineAxis(child))
ratio = 1 / ratio;
return ratio;
}
LayoutUnit NGFlexLayoutAlgorithm::CalculateFixedCrossSize(
const MinMaxSizes& cross_axis_min_max,
const NGBoxStrut& margins) const {
if (!is_column_)
DCHECK_NE(ChildAvailableSize().block_size, kIndefiniteSize);
LayoutUnit available_size = is_column_ ? ChildAvailableSize().inline_size
: ChildAvailableSize().block_size;
LayoutUnit margin_sum = is_column_ ? margins.InlineSum() : margins.BlockSum();
return cross_axis_min_max.ClampSizeToMinAndMax(available_size - margin_sum);
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForIntrinsicBlockSize(
const NGBlockNode& flex_item,
const NGPhysicalBoxStrut& physical_margins = NGPhysicalBoxStrut(),
const MinMaxSizes& cross_axis_min_max = MinMaxSizes{
kIndefiniteSize, kIndefiniteSize}) const {
const ComputedStyle& child_style = flex_item.Style();
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
child_style.GetWritingMode(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder);
space_builder.SetCacheSlot(NGCacheSlot::kMeasure);
space_builder.SetIsPaintedAtomically(true);
NGBoxStrut margins = physical_margins.ConvertToLogical(
ConstraintSpace().GetWritingMode(), Style().Direction());
LogicalSize child_available_size = ChildAvailableSize();
if (ShouldItemShrinkToFit(flex_item)) {
space_builder.SetIsShrinkToFit(true);
} else if (cross_axis_min_max.min_size != kIndefiniteSize &&
WillChildCrossSizeBeContainerCrossSize(flex_item)) {
LayoutUnit cross_size =
CalculateFixedCrossSize(cross_axis_min_max, margins);
if (is_column_) {
space_builder.SetIsFixedInlineSize(true);
child_available_size.inline_size = cross_size;
} else {
space_builder.SetIsFixedBlockSize(true);
child_available_size.block_size = cross_size;
}
}
space_builder.SetNeedsBaseline(
ConstraintSpace().NeedsBaseline() ||
FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kBaseline);
// For determining the intrinsic block-size we make %-block-sizes resolve
// against an indefinite size.
LogicalSize child_percentage_size = child_percentage_size_;
if (is_column_)
child_percentage_size.block_size = kIndefiniteSize;
space_builder.SetAvailableSize(child_available_size);
space_builder.SetPercentageResolutionSize(child_percentage_size);
// TODO(dgrogan): The SetReplacedPercentageResolutionSize calls in this file
// may be untested. Write a test or determine why they're unnecessary.
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size);
space_builder.SetTextDirection(child_style.Direction());
return space_builder.ToConstraintSpace();
}
NGConstraintSpace NGFlexLayoutAlgorithm::BuildSpaceForFlexBasis(
const NGBlockNode& flex_item) const {
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
flex_item.Style().GetWritingMode(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder);
// This space is only used for resolving lengths, not for layout. We only
// need the available and percentage sizes.
space_builder.SetAvailableSize(ChildAvailableSize());
space_builder.SetPercentageResolutionSize(child_percentage_size_);
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size_);
return space_builder.ToConstraintSpace();
}
void NGFlexLayoutAlgorithm::ConstructAndAppendFlexItems() {
NGFlexChildIterator iterator(Node());
for (NGBlockNode child = iterator.NextChild(); child;
child = iterator.NextChild()) {
if (child.IsOutOfFlowPositioned()) {
HandleOutOfFlowPositioned(child);
continue;
}
const ComputedStyle& child_style = child.Style();
NGConstraintSpace flex_basis_space = BuildSpaceForFlexBasis(child);
NGPhysicalBoxStrut physical_child_margins =
ComputePhysicalMargins(flex_basis_space, child_style);
NGBoxStrut border_padding_in_child_writing_mode =
ComputeBorders(flex_basis_space, child) +
ComputePadding(flex_basis_space, child_style);
NGPhysicalBoxStrut physical_border_padding(
border_padding_in_child_writing_mode.ConvertToPhysical(
child_style.GetWritingMode(), child_style.Direction()));
LayoutUnit main_axis_border_padding =
is_horizontal_flow_ ? physical_border_padding.HorizontalSum()
: physical_border_padding.VerticalSum();
LayoutUnit cross_axis_border_padding =
is_horizontal_flow_ ? physical_border_padding.VerticalSum()
: physical_border_padding.HorizontalSum();
base::Optional<MinMaxSizesResult> min_max_sizes;
auto MinMaxSizesFunc = [&](MinMaxSizesType type) -> MinMaxSizesResult {
if (!min_max_sizes) {
// We want the child's intrinsic inline sizes in its writing mode, so
// pass child's writing mode as the first parameter, which is nominally
// |container_writing_mode|.
NGConstraintSpace child_space = BuildSpaceForIntrinsicBlockSize(child);
MinMaxSizesInput input(ChildAvailableSize().block_size, type);
min_max_sizes = child.ComputeMinMaxSizes(child_style.GetWritingMode(),
input, &child_space);
}
return *min_max_sizes;
};
MinMaxSizes min_max_sizes_in_main_axis_direction{main_axis_border_padding,
LayoutUnit::Max()};
MinMaxSizes min_max_sizes_in_cross_axis_direction{LayoutUnit(),
LayoutUnit::Max()};
const Length& max_property_in_main_axis = is_horizontal_flow_
? child.Style().MaxWidth()
: child.Style().MaxHeight();
const Length& max_property_in_cross_axis = is_horizontal_flow_
? child.Style().MaxHeight()
: child.Style().MaxWidth();
const Length& min_property_in_cross_axis = is_horizontal_flow_
? child.Style().MinHeight()
: child.Style().MinWidth();
if (MainAxisIsInlineAxis(child)) {
min_max_sizes_in_main_axis_direction.max_size = ResolveMaxInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, max_property_in_main_axis,
LengthResolvePhase::kLayout);
min_max_sizes_in_cross_axis_direction.max_size = ResolveMaxBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
max_property_in_cross_axis, LengthResolvePhase::kLayout);
min_max_sizes_in_cross_axis_direction.min_size = ResolveMinBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
min_property_in_cross_axis, LengthResolvePhase::kLayout);
} else {
min_max_sizes_in_main_axis_direction.max_size = ResolveMaxBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
max_property_in_main_axis, LengthResolvePhase::kLayout);
min_max_sizes_in_cross_axis_direction.max_size = ResolveMaxInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, max_property_in_cross_axis,
LengthResolvePhase::kLayout);
min_max_sizes_in_cross_axis_direction.min_size = ResolveMinInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, min_property_in_cross_axis,
LengthResolvePhase::kLayout);
}
base::Optional<LayoutUnit> intrinsic_block_size;
auto IntrinsicBlockSizeFunc = [&]() -> LayoutUnit {
if (!intrinsic_block_size) {
NGConstraintSpace child_space = BuildSpaceForIntrinsicBlockSize(
child, physical_child_margins,
min_max_sizes_in_cross_axis_direction);
scoped_refptr<const NGLayoutResult> layout_result =
child.Layout(child_space, /* break_token */ nullptr);
intrinsic_block_size = layout_result->IntrinsicBlockSize();
}
return *intrinsic_block_size;
};
// The logic that calculates flex_base_border_box assumes that the used
// value of the flex-basis property is either definite or 'content'.
LayoutUnit flex_base_border_box;
const Length& specified_length_in_main_axis =
is_horizontal_flow_ ? child_style.Width() : child_style.Height();
const Length& flex_basis = child_style.FlexBasis();
Length length_to_resolve = Length::Auto();
if (flex_basis.IsAuto()) {
if (!is_column_ || IsItemMainSizeDefinite(child))
length_to_resolve = specified_length_in_main_axis;
} else if (IsItemFlexBasisDefinite(child)) {
length_to_resolve = flex_basis;
}
if (length_to_resolve.IsAuto()) {
// This block means that the used flex-basis is 'content'. In here we
// implement parts B,C,D,E of 9.2.3
// https://drafts.csswg.org/css-flexbox/#algo-main-item
const Length& cross_axis_length =
is_horizontal_flow_ ? child.Style().Height() : child.Style().Width();
// This check should use HasAspectRatio() instead of Style().
// AspectRatio(), but to avoid introducing a behavior change we only
// do this for the aspect-ratio property for now until FlexNG ships.
bool use_cross_axis_for_aspect_ratio =
child.Style().AspectRatio() &&
WillChildCrossSizeBeContainerCrossSize(child);
if (use_cross_axis_for_aspect_ratio ||
(child.HasAspectRatio() &&
(IsItemCrossAxisLengthDefinite(child, cross_axis_length)))) {
// This is Part B of 9.2.3
// https://drafts.csswg.org/css-flexbox/#algo-main-item It requires that
// the item has a definite cross size.
LayoutUnit cross_size;
if (use_cross_axis_for_aspect_ratio) {
NGBoxStrut margins = physical_child_margins.ConvertToLogical(
ConstraintSpace().GetWritingMode(), Style().Direction());
cross_size = CalculateFixedCrossSize(
min_max_sizes_in_cross_axis_direction, margins);
} else if (MainAxisIsInlineAxis(child)) {
cross_size = ResolveMainBlockLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode, cross_axis_length,
kIndefiniteSize, LengthResolvePhase::kLayout);
} else {
cross_size =
ResolveMainInlineLength(flex_basis_space, child_style,
border_padding_in_child_writing_mode,
MinMaxSizesFunc, cross_axis_length);
}
cross_size = min_max_sizes_in_cross_axis_direction.ClampSizeToMinAndMax(
cross_size);
flex_base_border_box =
LayoutUnit((cross_size - cross_axis_border_padding) *
GetMainOverCrossAspectRatio(child) +
main_axis_border_padding);
} else if (MainAxisIsInlineAxis(child)) {
// We're now in parts C, D, and E for what are usually (horizontal-tb
// containers AND children) row flex containers. I _think_ the C and D
// cases are correctly handled by this code, which was originally
// written for case E.
if (child.HasAspectRatio()) {
// Legacy uses child.PreferredLogicalWidths() for this case, which
// is not exactly correct.
// TODO(dgrogan): Replace with a variant of ComputeReplacedSize that
// ignores min-width, width, max-width.
MinMaxSizesInput input(child_percentage_size_.block_size,
MinMaxSizesType::kContent);
flex_base_border_box =
ComputeMinAndMaxContentContribution(Style(), child, input)
.sizes.max_size;
} else {
flex_base_border_box =
MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.max_size;
}
} else {
// Parts C, D, and E for what are usually column flex containers.
//
// This is the post-layout height for aspect-ratio items, which matches
// legacy but isn't always correct.
// TODO(dgrogan): Replace with a variant of ComputeReplacedSize that
// ignores min-height, height, max-height.
flex_base_border_box = IntrinsicBlockSizeFunc();
}
} else {
// Part A of 9.2.3 https://drafts.csswg.org/css-flexbox/#algo-main-item
if (MainAxisIsInlineAxis(child)) {
flex_base_border_box = ResolveMainInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, length_to_resolve);
} else {
// Flex container's main axis is in child's block direction. Child's
// flex basis is in child's block direction.
flex_base_border_box = ResolveMainBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
length_to_resolve, IntrinsicBlockSizeFunc,
LengthResolvePhase::kLayout);
}
}
// Spec calls this "flex base size"
// https://www.w3.org/TR/css-flexbox-1/#algo-main-item
// Blink's FlexibleBoxAlgorithm expects it to be content + scrollbar widths,
// but no padding or border.
DCHECK_GE(flex_base_border_box, main_axis_border_padding);
LayoutUnit flex_base_content_size =
flex_base_border_box - main_axis_border_padding;
const Length& min = is_horizontal_flow_ ? child.Style().MinWidth()
: child.Style().MinHeight();
if (algorithm_->ShouldApplyMinSizeAutoForChild(*child.GetLayoutBox())) {
// TODO(dgrogan): This should probably apply to column flexboxes also,
// but that's not what legacy does.
if (child.IsTable() && !is_column_) {
MinMaxSizes table_preferred_widths =
ComputeMinAndMaxContentContribution(
Style(), child,
MinMaxSizesInput(child_percentage_size_.block_size,
MinMaxSizesType::kIntrinsic))
.sizes;
min_max_sizes_in_main_axis_direction.min_size =
table_preferred_widths.min_size;
} else {
LayoutUnit content_size_suggestion;
if (MainAxisIsInlineAxis(child)) {
content_size_suggestion =
MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.min_size;
} else {
LayoutUnit intrinsic_block_size;
if (child.IsReplaced()) {
base::Optional<LayoutUnit> computed_inline_size;
base::Optional<LayoutUnit> computed_block_size;
child.IntrinsicSize(&computed_inline_size, &computed_block_size);
// The 150 is for replaced elements that have no size, which SVG
// can have (maybe others?).
intrinsic_block_size =
computed_block_size.value_or(LayoutUnit(150)) +
border_padding_in_child_writing_mode.BlockSum();
} else {
intrinsic_block_size = IntrinsicBlockSizeFunc();
}
content_size_suggestion = intrinsic_block_size;
}
DCHECK_GE(content_size_suggestion, main_axis_border_padding);
if (child.HasAspectRatio()) {
content_size_suggestion =
AdjustChildSizeForAspectRatioCrossAxisMinAndMax(
child, content_size_suggestion,
min_max_sizes_in_cross_axis_direction.min_size,
min_max_sizes_in_cross_axis_direction.max_size,
main_axis_border_padding, cross_axis_border_padding);
}
LayoutUnit specified_size_suggestion = LayoutUnit::Max();
// If the item’s computed main size property is definite, then the
// specified size suggestion is that size.
if (MainAxisIsInlineAxis(child)) {
if (!specified_length_in_main_axis.IsAuto()) {
// TODO(dgrogan): Optimization opportunity: we may have already
// resolved specified_length_in_main_axis in the flex basis
// calculation. Reuse that if possible.
specified_size_suggestion = ResolveMainInlineLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode, MinMaxSizesFunc,
specified_length_in_main_axis);
}
} else if (!BlockLengthUnresolvable(flex_basis_space,
specified_length_in_main_axis,
LengthResolvePhase::kLayout)) {
specified_size_suggestion = ResolveMainBlockLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode,
specified_length_in_main_axis, IntrinsicBlockSizeFunc,
LengthResolvePhase::kLayout);
DCHECK_NE(specified_size_suggestion, kIndefiniteSize);
}
LayoutUnit transferred_size_suggestion = LayoutUnit::Max();
if (specified_size_suggestion == LayoutUnit::Max() &&
child.HasAspectRatio()) {
const Length& cross_axis_length =
is_horizontal_flow_ ? child_style.Height() : child_style.Width();
if (IsItemCrossAxisLengthDefinite(child, cross_axis_length)) {
LayoutUnit cross_axis_size;
if (MainAxisIsInlineAxis(child)) {
cross_axis_size = ResolveMainBlockLength(
flex_basis_space, child_style,
border_padding_in_child_writing_mode, cross_axis_length,
kIndefiniteSize, LengthResolvePhase::kLayout);
DCHECK_NE(cross_axis_size, kIndefiniteSize);
} else {
cross_axis_size =
ResolveMainInlineLength(flex_basis_space, child_style,
border_padding_in_child_writing_mode,
MinMaxSizesFunc, cross_axis_length);
}
double ratio = GetMainOverCrossAspectRatio(child);
transferred_size_suggestion = LayoutUnit(
main_axis_border_padding +
ratio *
(min_max_sizes_in_cross_axis_direction.ClampSizeToMinAndMax(
cross_axis_size) -
cross_axis_border_padding));
}
}
DCHECK(specified_size_suggestion == LayoutUnit::Max() ||
transferred_size_suggestion == LayoutUnit::Max());
min_max_sizes_in_main_axis_direction.min_size =
std::min({specified_size_suggestion, content_size_suggestion,
transferred_size_suggestion,
min_max_sizes_in_main_axis_direction.max_size});
}
} else if (MainAxisIsInlineAxis(child)) {
min_max_sizes_in_main_axis_direction.min_size = ResolveMinInlineLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
MinMaxSizesFunc, min, LengthResolvePhase::kLayout);
} else {
min_max_sizes_in_main_axis_direction.min_size = ResolveMinBlockLength(
flex_basis_space, child_style, border_padding_in_child_writing_mode,
min, LengthResolvePhase::kLayout);
}
min_max_sizes_in_main_axis_direction -= main_axis_border_padding;
DCHECK_GE(min_max_sizes_in_main_axis_direction.min_size, 0);
DCHECK_GE(min_max_sizes_in_main_axis_direction.max_size, 0);
NGBoxStrut scrollbars = ComputeScrollbarsForNonAnonymous(child);
algorithm_
->emplace_back(nullptr, child.Style(), flex_base_content_size,
min_max_sizes_in_main_axis_direction,
min_max_sizes_in_cross_axis_direction,
main_axis_border_padding, cross_axis_border_padding,
physical_child_margins, scrollbars)
.ng_input_node = child;
}
}
LayoutUnit
NGFlexLayoutAlgorithm::AdjustChildSizeForAspectRatioCrossAxisMinAndMax(
const NGBlockNode& child,
LayoutUnit content_size_suggestion,
LayoutUnit cross_min,
LayoutUnit cross_max,
LayoutUnit main_axis_border_padding,
LayoutUnit cross_axis_border_padding) {
DCHECK(child.HasAspectRatio());
double ratio = GetMainOverCrossAspectRatio(child);
// Clamp content_suggestion by any definite min and max cross size properties
// converted through the aspect ratio.
const Length& cross_max_length = is_horizontal_flow_
? child.Style().MaxHeight()
: child.Style().MaxWidth();
DCHECK_GE(cross_max, cross_axis_border_padding);
// TODO(dgrogan): No tests fail if we unconditionally apply max_main_length.
// Either add a test that needs it or remove it.
if (IsItemCrossAxisLengthDefinite(child, cross_max_length)) {
LayoutUnit max_main_length =
main_axis_border_padding +
LayoutUnit((cross_max - cross_axis_border_padding) * ratio);
content_size_suggestion =
std::min(max_main_length, content_size_suggestion);
}
const Length& cross_min_length = is_horizontal_flow_
? child.Style().MinHeight()
: child.Style().MinWidth();
DCHECK_GE(cross_min, cross_axis_border_padding);
// TODO(dgrogan): Same as above with min_main_length here -- it may be
// unneeded or untested.
if (IsItemCrossAxisLengthDefinite(child, cross_min_length)) {
LayoutUnit min_main_length =
main_axis_border_padding +
LayoutUnit((cross_min - cross_axis_border_padding) * ratio);
content_size_suggestion =
std::max(min_main_length, content_size_suggestion);
}
return content_size_suggestion;
}
scoped_refptr<const NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
if (auto result = LayoutInternal())
return result;
// We may have aborted layout due to a child changing scrollbars, relayout
// with the new scrollbar information.
return RelayoutIgnoringChildScrollbarChanges();
}
scoped_refptr<const NGLayoutResult>
NGFlexLayoutAlgorithm::RelayoutIgnoringChildScrollbarChanges() {
DCHECK(!ignore_child_scrollbar_changes_);
// Freezing the scrollbars for the sub-tree shouldn't be strictly necessary,
// but we do this just in case we trigger an unstable layout.
PaintLayerScrollableArea::FreezeScrollbarsScope freeze_scrollbars;
NGLayoutAlgorithmParams params(
Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(),
BreakToken(), /* early_break */ nullptr);
NGFlexLayoutAlgorithm algorithm(params);
algorithm.ignore_child_scrollbar_changes_ = true;
return algorithm.Layout();
}
scoped_refptr<const NGLayoutResult> NGFlexLayoutAlgorithm::LayoutInternal() {
PaintLayerScrollableArea::DelayScrollOffsetClampScope delay_clamp_scope;
ConstructAndAppendFlexItems();
LayoutUnit main_axis_start_offset;
LayoutUnit main_axis_end_offset;
LayoutUnit cross_axis_offset = BorderScrollbarPadding().block_start;
if (is_column_) {
const bool is_column_reverse =
Style().ResolvedIsColumnReverseFlexDirection();
main_axis_start_offset =
is_column_reverse ? LayoutUnit() : BorderScrollbarPadding().block_start;
main_axis_end_offset =
is_column_reverse ? LayoutUnit() : BorderScrollbarPadding().block_end;
cross_axis_offset = BorderScrollbarPadding().inline_start;
} else if (Style().ResolvedIsRowReverseFlexDirection()) {
main_axis_start_offset = BorderScrollbarPadding().inline_end;
main_axis_end_offset = BorderScrollbarPadding().inline_start;
} else {
main_axis_start_offset = BorderScrollbarPadding().inline_start;
main_axis_end_offset = BorderScrollbarPadding().inline_end;
}
FlexLine* line;
while (
(line = algorithm_->ComputeNextFlexLine(border_box_size_.inline_size))) {
line->SetContainerMainInnerSize(
MainAxisContentExtent(line->sum_hypothetical_main_size));
line->FreezeInflexibleItems();
while (!line->ResolveFlexibleLengths()) {
continue;
}
for (wtf_size_t i = 0; i < line->line_items.size(); ++i) {
FlexItem& flex_item = line->line_items[i];
const ComputedStyle& child_style = flex_item.ng_input_node.Style();
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
child_style.GetWritingMode(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item.ng_input_node,
&space_builder);
space_builder.SetTextDirection(child_style.Direction());
space_builder.SetIsPaintedAtomically(true);
LogicalSize available_size;
NGBoxStrut margins = flex_item.physical_margins.ConvertToLogical(
ConstraintSpace().GetWritingMode(), Style().Direction());
LayoutUnit fixed_aspect_ratio_cross_size = kIndefiniteSize;
if (RuntimeEnabledFeatures::FlexAspectRatioEnabled() &&
flex_item.ng_input_node.HasAspectRatio() &&
flex_item.ng_input_node.IsReplaced()) {
// This code derives the cross axis size from the flexed main size and
// the aspect ratio. We can delete this code when
// NGReplacedLayoutAlgorithm exists, because it will do this for us.
NGConstraintSpace flex_basis_space =
BuildSpaceForFlexBasis(flex_item.ng_input_node);
const Length& cross_axis_length =
is_horizontal_flow_ ? child_style.Height() : child_style.Width();
// Only derive the cross axis size from the aspect ratio if the computed
// cross axis length might be indefinite. The item's cross axis length
// might still be definite if it is stretched, but that is checked in
// the |WillChildCrossSizeBeContainerCrossSize| calls below.
if (cross_axis_length.IsAuto() ||
(MainAxisIsInlineAxis(flex_item.ng_input_node) &&
BlockLengthUnresolvable(flex_basis_space, cross_axis_length,
LengthResolvePhase::kLayout))) {
fixed_aspect_ratio_cross_size =
flex_item.min_max_cross_sizes->ClampSizeToMinAndMax(
flex_item.cross_axis_border_padding +
LayoutUnit(
flex_item.flexed_content_size /
GetMainOverCrossAspectRatio(flex_item.ng_input_node)));
}
}
if (is_column_) {
available_size.inline_size = ChildAvailableSize().inline_size;
available_size.block_size =
flex_item.flexed_content_size + flex_item.main_axis_border_padding;
space_builder.SetIsFixedBlockSize(true);
if (WillChildCrossSizeBeContainerCrossSize(flex_item.ng_input_node)) {
space_builder.SetIsFixedInlineSize(true);
available_size.inline_size = CalculateFixedCrossSize(
flex_item.min_max_cross_sizes.value(), margins);
} else if (fixed_aspect_ratio_cross_size != kIndefiniteSize) {
space_builder.SetIsFixedInlineSize(true);
available_size.inline_size = fixed_aspect_ratio_cross_size;
}
// https://drafts.csswg.org/css-flexbox/#definite-sizes
// If the flex container has a definite main size, a flex item's
// post-flexing main size is treated as definite, even though it can
// rely on the indefinite sizes of any flex items in the same line.
if (!IsColumnContainerMainSizeDefinite() &&
!IsItemMainSizeDefinite(flex_item.ng_input_node)) {
space_builder.SetIsFixedBlockSizeIndefinite(true);
}
} else {
available_size.inline_size =
flex_item.flexed_content_size + flex_item.main_axis_border_padding;
available_size.block_size = ChildAvailableSize().block_size;
space_builder.SetIsFixedInlineSize(true);
if (WillChildCrossSizeBeContainerCrossSize(flex_item.ng_input_node)) {
space_builder.SetIsFixedBlockSize(true);
available_size.block_size = CalculateFixedCrossSize(
flex_item.min_max_cross_sizes.value(), margins);
} else if (fixed_aspect_ratio_cross_size != kIndefiniteSize) {
space_builder.SetIsFixedBlockSize(true);
available_size.block_size = fixed_aspect_ratio_cross_size;
} else if (DoesItemStretch(flex_item.ng_input_node)) {
// If we are in a row flexbox, and we don't have a fixed block-size
// (yet), use the "measure" cache slot. This will be the first
// layout, and we will use the "layout" cache slot if this gets
// stretched later.
//
// Setting the "measure" cache slot on the space writes the result
// into both the "measure", and "layout" cache slots. If a subsequent
// "layout" occurs, it'll just get written into the "layout" slot.
space_builder.SetCacheSlot(NGCacheSlot::kMeasure);
}
}
space_builder.SetNeedsBaseline(
ConstraintSpace().NeedsBaseline() ||
FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kBaseline);
space_builder.SetAvailableSize(available_size);
space_builder.SetPercentageResolutionSize(child_percentage_size_);
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size_);
// https://drafts.csswg.org/css-flexbox/#algo-cross-item
// Determine the hypothetical cross size of each item by performing layout
// with the used main size and the available space, treating auto as
// fit-content.
if (ShouldItemShrinkToFit(flex_item.ng_input_node))
space_builder.SetIsShrinkToFit(true);
// For a button child, we need the baseline type same as the container's
// baseline type for UseCounter. For example, if the container's display
// property is 'inline-block', we need the last-line baseline of the
// child. See the bottom of GiveLinesAndItemsFinalPositionAndSize().
if (Node().IsButton()) {
space_builder.SetBaselineAlgorithmType(
ConstraintSpace().BaselineAlgorithmType());
}
NGConstraintSpace child_space = space_builder.ToConstraintSpace();
flex_item.layout_result =
flex_item.ng_input_node.Layout(child_space, nullptr /*break token*/);
// TODO(layout-dev): Handle abortions caused by block fragmentation.
DCHECK_EQ(flex_item.layout_result->Status(), NGLayoutResult::kSuccess);
flex_item.cross_axis_size =
is_horizontal_flow_
? flex_item.layout_result->PhysicalFragment().Size().height
: flex_item.layout_result->PhysicalFragment().Size().width;
}
// cross_axis_offset is updated in each iteration of the loop, for passing
// in to the next iteration.
line->ComputeLineItemsPosition(main_axis_start_offset, main_axis_end_offset,
cross_axis_offset);
}
LayoutUnit intrinsic_block_size = BorderScrollbarPadding().BlockSum();
if (algorithm_->FlexLines().IsEmpty() && Node().HasLineIfEmpty()) {
intrinsic_block_size += Node().GetLayoutBox()->LogicalHeightForEmptyLine();
} else {
intrinsic_block_size += algorithm_->IntrinsicContentBlockSize();
}
intrinsic_block_size =
ClampIntrinsicBlockSize(ConstraintSpace(), Node(),
BorderScrollbarPadding(), intrinsic_block_size);
LayoutUnit block_size = ComputeBlockSizeForFragment(
ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size,
border_box_size_.inline_size);
container_builder_.SetIntrinsicBlockSize(intrinsic_block_size);
container_builder_.SetFragmentsTotalBlockSize(block_size);
bool success = GiveLinesAndItemsFinalPositionAndSize();
if (!success)
return nullptr;
NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run();
return container_builder_.ToBoxFragment();
}
void NGFlexLayoutAlgorithm::ApplyStretchAlignmentToChild(FlexItem& flex_item) {
const ComputedStyle& child_style = flex_item.ng_input_node.Style();
NGConstraintSpaceBuilder space_builder(ConstraintSpace(),
child_style.GetWritingMode(),
/* is_new_fc */ true);
SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item.ng_input_node,
&space_builder);
space_builder.SetIsPaintedAtomically(true);
LogicalSize available_size(
flex_item.flexed_content_size + flex_item.main_axis_border_padding,
flex_item.cross_axis_size);
if (is_column_) {
available_size.Transpose();
if (!IsColumnContainerMainSizeDefinite() &&
!IsItemMainSizeDefinite(flex_item.ng_input_node)) {
space_builder.SetIsFixedBlockSizeIndefinite(true);
}
}
space_builder.SetNeedsBaseline(
ConstraintSpace().NeedsBaseline() ||
FlexLayoutAlgorithm::AlignmentForChild(Style(), child_style) ==
ItemPosition::kBaseline);
space_builder.SetTextDirection(child_style.Direction());
space_builder.SetAvailableSize(available_size);
space_builder.SetPercentageResolutionSize(child_percentage_size_);
space_builder.SetReplacedPercentageResolutionSize(child_percentage_size_);
space_builder.SetIsFixedInlineSize(true);
space_builder.SetIsFixedBlockSize(true);
NGConstraintSpace child_space = space_builder.ToConstraintSpace();
flex_item.layout_result =
flex_item.ng_input_node.Layout(child_space, /* break_token */ nullptr);
}
bool NGFlexLayoutAlgorithm::GiveLinesAndItemsFinalPositionAndSize() {
Vector<FlexLine>& line_contexts = algorithm_->FlexLines();
const LayoutUnit cross_axis_start_edge =
line_contexts.IsEmpty() ? LayoutUnit()
: line_contexts[0].cross_axis_offset;
LayoutUnit final_content_main_size =
container_builder_.InlineSize() - BorderScrollbarPadding().InlineSum();
LayoutUnit final_content_cross_size = container_builder_.FragmentBlockSize() -
BorderScrollbarPadding().BlockSum();
if (is_column_)
std::swap(final_content_main_size, final_content_cross_size);
if (!algorithm_->IsMultiline() && !line_contexts.IsEmpty())
line_contexts[0].cross_axis_extent = final_content_cross_size;
algorithm_->AlignFlexLines(final_content_cross_size);
algorithm_->AlignChildren();
if (Style().FlexWrap() == EFlexWrap::kWrapReverse) {
// flex-wrap: wrap-reverse reverses the order of the lines in the container;
// FlipForWrapReverse recalculates each item's cross axis position. We have
// to do that after AlignChildren sets an initial cross axis position.
algorithm_->FlipForWrapReverse(cross_axis_start_edge,
final_content_cross_size);
}
if (Style().ResolvedIsColumnReverseFlexDirection()) {
algorithm_->LayoutColumnReverse(final_content_main_size,
BorderScrollbarPadding().block_start);
}
base::Optional<LayoutUnit> fallback_baseline;
bool success = true;
LayoutUnit overflow_block_size;
for (FlexLine& line_context : line_contexts) {
for (wtf_size_t child_number = 0;
child_number < line_context.line_items.size(); ++child_number) {
FlexItem& flex_item = line_context.line_items[child_number];
if (DoesItemStretch(flex_item.ng_input_node))
ApplyStretchAlignmentToChild(flex_item);
const auto& physical_fragment = To<NGPhysicalBoxFragment>(
flex_item.layout_result->PhysicalFragment());
// flex_item.desired_location stores the main axis offset in X and the
// cross axis offset in Y. But AddChild wants offset from parent
// rectangle, so we have to transpose for columns. AddChild takes care of
// any writing mode differences though.
LayoutPoint location = is_column_
? flex_item.desired_location.TransposedPoint()
: flex_item.desired_location;
NGBoxFragment fragment(ConstraintSpace().GetWritingMode(),
ConstraintSpace().Direction(), physical_fragment);
// Only propagate baselines from children on the first flex-line.
if (&line_context == line_contexts.begin()) {
PropagateBaselineFromChild(flex_item, fragment, location.Y(),
&fallback_baseline);
}
container_builder_.AddChild(physical_fragment,
{location.X(), location.Y()});
flex_item.ng_input_node.StoreMargins(flex_item.physical_margins);
LayoutUnit margin_block_end =
flex_item.physical_margins
.ConvertToLogical(ConstraintSpace().GetWritingMode(),
ConstraintSpace().Direction())
.block_end;
overflow_block_size =
std::max(overflow_block_size,
location.Y() + fragment.BlockSize() + margin_block_end);
// Detect if the flex-item had its scrollbar state change. If so we need
// to relayout as the input to the flex algorithm is incorrect.
if (!ignore_child_scrollbar_changes_) {
if (flex_item.scrollbars !=
ComputeScrollbarsForNonAnonymous(flex_item.ng_input_node))
success = false;
} else {
DCHECK_EQ(flex_item.scrollbars,
ComputeScrollbarsForNonAnonymous(flex_item.ng_input_node));
}
}
}
container_builder_.SetOverflowBlockSize(overflow_block_size +
BorderScrollbarPadding().block_end);
// Set the baseline to the fallback, if we didn't find any children with
// baseline alignment.
if (!container_builder_.Baseline() && fallback_baseline)
container_builder_.SetBaseline(*fallback_baseline);
if (Node().IsButton())
AdjustButtonBaseline(final_content_cross_size);
// Signal if we need to relayout with new child scrollbar information.
return success;
}
void NGFlexLayoutAlgorithm::AdjustButtonBaseline(
LayoutUnit final_content_cross_size) {
// See LayoutButton::BaselinePosition()
if (!Node().HasLineIfEmpty() && !Node().ShouldApplyLayoutContainment() &&
!container_builder_.Baseline()) {
// To ensure that we have a consistent baseline when we have no children,
// even when we have the anonymous LayoutBlock child, we calculate the
// baseline for the empty case manually here.
container_builder_.SetBaseline(BorderScrollbarPadding().block_start +
final_content_cross_size);
return;
}
// Apply flexbox's baseline as is. That is to say, the baseline of the
// first line.
// However, we count the differences between it and the last-line baseline
// of the anonymous block. crbug.com/690036.
// We also have a difference in empty buttons. See crbug.com/304848.
const LayoutObject* parent = Node().GetLayoutBox()->Parent();
if (!LayoutButton::ShouldCountWrongBaseline(
Style(), parent ? parent->Style() : nullptr))
return;
// The button should have at most one child.
const NGContainerFragmentBuilder::ChildrenVector& children =
container_builder_.Children();
if (children.size() < 1) {
const LayoutBlock* layout_block = To<LayoutBlock>(Node().GetLayoutBox());
base::Optional<LayoutUnit> baseline = layout_block->BaselineForEmptyLine(
layout_block->IsHorizontalWritingMode() ? kHorizontalLine
: kVerticalLine);
if (container_builder_.Baseline() != baseline) {
UseCounter::Count(Node().GetDocument(),
WebFeature::kWrongBaselineOfEmptyLineButton);
}
return;
}
DCHECK_EQ(children.size(), 1u);
const NGContainerFragmentBuilder::ChildWithOffset& child = children[0];
DCHECK(!child.fragment->IsLineBox());
const NGConstraintSpace& space = ConstraintSpace();
NGBoxFragment fragment(space.GetWritingMode(), space.Direction(),
To<NGPhysicalBoxFragment>(*child.fragment));
base::Optional<LayoutUnit> child_baseline =
space.BaselineAlgorithmType() == NGBaselineAlgorithmType::kFirstLine
? fragment.FirstBaseline()
: fragment.Baseline();
if (child_baseline)
child_baseline = *child_baseline + child.offset.block_offset;
if (container_builder_.Baseline() != child_baseline) {
UseCounter::Count(Node().GetDocument(),
WebFeature::kWrongBaselineOfMultiLineButton);
}
}
void NGFlexLayoutAlgorithm::PropagateBaselineFromChild(
const FlexItem& flex_item,
const NGBoxFragment& fragment,
LayoutUnit block_offset,
base::Optional<LayoutUnit>* fallback_baseline) {
// Check if we've already found an appropriate baseline.
if (container_builder_.Baseline())
return;
LayoutUnit baseline_offset =
block_offset + (Node().IsButton() ? fragment.FirstBaselineOrSynthesize()
: fragment.BaselineOrSynthesize());
// We prefer a baseline from a child with baseline alignment, and no
// auto-margins in the cross axis (even if we have to synthesize the
// baseline).
if (FlexLayoutAlgorithm::AlignmentForChild(Style(), flex_item.style) ==
ItemPosition::kBaseline &&
!flex_item.HasAutoMarginsInCrossAxis()) {
container_builder_.SetBaseline(baseline_offset);
return;
}
// Set the fallback baseline if it doesn't have a value yet.
*fallback_baseline = fallback_baseline->value_or(baseline_offset);
}
MinMaxSizesResult NGFlexLayoutAlgorithm::ComputeMinMaxSizes(
const MinMaxSizesInput& child_input) const {
if (auto result = CalculateMinMaxSizesIgnoringChildren(
Node(), BorderScrollbarPadding()))
return *result;
MinMaxSizes sizes;
bool depends_on_percentage_block_size = false;
int number_of_items = 0;
NGFlexChildIterator iterator(Node());
for (NGBlockNode child = iterator.NextChild(); child;
child = iterator.NextChild()) {
if (child.IsOutOfFlowPositioned())
continue;
number_of_items++;
MinMaxSizesResult child_result =
ComputeMinAndMaxContentContribution(Style(), child, child_input);
NGBoxStrut child_margins = ComputeMinMaxMargins(Style(), child);
child_result.sizes += child_margins.InlineSum();
depends_on_percentage_block_size |=
child_result.depends_on_percentage_block_size;
if (is_column_) {
sizes.min_size = std::max(sizes.min_size, child_result.sizes.min_size);
sizes.max_size = std::max(sizes.max_size, child_result.sizes.max_size);
} else {
sizes.max_size += child_result.sizes.max_size;
if (algorithm_->IsMultiline()) {
sizes.min_size = std::max(sizes.min_size, child_result.sizes.min_size);
} else {
sizes.min_size += child_result.sizes.min_size;
}
}
}
if (!is_column_) {
LayoutUnit gap_inline_size =
(number_of_items - 1) * algorithm_->gap_between_items_;
sizes.max_size += gap_inline_size;
if (!algorithm_->IsMultiline()) {
sizes.min_size += gap_inline_size;
}
}
sizes.max_size = std::max(sizes.max_size, sizes.min_size);
// Due to negative margins, it is possible that we calculated a negative
// intrinsic width. Make sure that we never return a negative width.
sizes.Encompass(LayoutUnit());
sizes += BorderScrollbarPadding().InlineSum();
return {sizes, depends_on_percentage_block_size};
}
} // namespace blink
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
dfd7f7b428d73b7eefc0a193d690c4fc3026d70f | f1a4e1bd1c1919765cf1a0eb86dffbb7f1505de2 | /src/PriorType.cpp | 3a833d9ed0c5f4c8bd3d5280042a5950ba3d69db | [] | no_license | csu-xiao-an/simulator | a661a51844f7782cd315e7b084ef59422a9db684 | 4fa9ec38e24c29227aae465f24a9e07549255dcb | refs/heads/master | 2022-02-18T13:10:57.708919 | 2019-09-15T06:48:21 | 2019-09-15T06:48:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 140 | cpp | /*
* Data simulator for mobile phone network events
*
* PriorType.cpp
*
* Created on: Apr 24, 2019
* Author: Bogdan Oancea
*/
| [
"bogdan.oancea@gmail.com"
] | bogdan.oancea@gmail.com |
7f3d2d4ac18bea5a7dace0ef84448f583c1147e0 | 2557f9feb131cc66bf54ed5115bf082e4e71baaa | /Humzer/src/Humzer/Renderer/Framebuffer.cpp | d9373413dad73b5f1044813d9df957b53f816088 | [] | no_license | PMASTUDIO/Humzer | 849146c27c3ae6c569d91e693b77ec342409fd71 | 451dd0d1935f3a2e01a319488784ddce0843d252 | refs/heads/main | 2023-03-09T01:49:24.757957 | 2021-02-21T18:34:40 | 2021-02-21T18:34:40 | 321,194,810 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include "humpch.h"
#include "Framebuffer.h"
#include "Renderer.h"
#include "RendererAPI.h"
#include "../Platform/OpenGL/OpenGLFramebuffer.h"
namespace Humzer {
Humzer::Ref<Humzer::Framebuffer> Framebuffer::Create(const FramebufferSpecs& spec)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::OpenGL:
return CreateRef<OpenGLFramebuffer>(spec);
break;
default:
case RendererAPI::API::None:
HUM_CORE_FATAL("No Renderer API Selected!");
return nullptr;
}
}
}
| [
"pmastudionet@gmail.com"
] | pmastudionet@gmail.com |
e20d95c0df637a0705df9817c045c62c6f6947b1 | 0f2635f18d7b47323332ab733f34c9308888e851 | /DEBUG/debug.cpp | dfbcc622851fd88b6b635867e3d1086933cf4fca | [] | no_license | stevebraveman/Code | 2e48b3638272126653c5a2baabac3438db781157 | 4205dd6c4c2f87a8d8554a21efac39616672004e | refs/heads/master | 2020-06-30T21:55:41.313296 | 2019-11-13T22:57:51 | 2019-11-13T22:57:51 | 178,631,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define ls(x) ((x) << 1)
#define rs(x) ((x) << 1 | 1)
#define MAXN 200010
int lazy[MAXN << 2], n, m, a[MAXN];
double sia[MAXN << 2], coa[MAXN << 2];
void pd(int p) {
sia[p] = sia[ls(p)] + sia[rs(p)];
coa[p] = coa[ls(p)] + coa[rs(p)];
}
void build(int l, int r, int p) {
if (l == r) {
sia[p] = sin(1.0 * a[l]);
coa[p] = cos(1.0 * a[l]);
return;
}
int m = (l + r) >> 1;
build(l, m, ls(p));
build(m + 1, r, rs(p));
pd(p);
}
void f(int p, int k) {
lazy[p] += k;
double x = sin(1.0 * k), y = cos(1.0 * k);
double c = sia[p], d = coa[p];
coa[p] = y * d - x * c;
sia[p] = x * d + y * c;
}
void pushd(int l, int r, int p) {
if (lazy[p]) {
f(ls(p), lazy[p]);
f(rs(p), lazy[p]);
lazy[p] = 0;
}
}
double ask(int x, int y, int l, int r, int p) {
double s = 0;
if (x <= l && y >= r) {
return sia[p];
}
int m = (l + r) >> 1;
pushd(l, r, p);
if (x <= m) s += ask(x, y, l, m, ls(p));
if (y > m) s += ask(x, y, m + 1, r, rs(p));
return s;
}
void chg(int x, int y, int l, int r, int k, int p) {
if (x <= l && y >= r) {
f(p, k);
return;
}
int m = (l + r) >> 1;
pushd(l, r, p);
if (x <= m) chg(x, y, l, m, k, ls(p));
if (y > m) chg(x, y, m + 1, r, k, rs(p));
pd(p);
}
int op, l, r, k;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
build(1, n, 1);
scanf("%d", &m);
while (m--) {
scanf("%d%d%d", &op, &l, &r);
if (op == 1) {
scanf("%d", &k);
chg(l, r, 1, n, k, 1);
}
else {
printf("%.1lf\n", ask(l, r, 1, n, 1));
}
}
}
/*
5
1 3 1 5 5
5
1 5 5 5
2 3 3
2 1 5
2 2 2
2 4 4
---------
5
1 3 1 5 5
5
1 5 5 5
2 3 3
2 1 5
2 2 5
2 4 5
*/ | [
"zhoujiangfan52D2@163.com"
] | zhoujiangfan52D2@163.com |
5eff0c7330fd849924165fdad77a877e6f900eb9 | ba59f0a4b84953033547719629648dc9b4a1ea5d | /mainwindow.cpp | 401921911c37a96e0fc9235ccae4ded0e1f82074 | [] | no_license | Toufikboudani/ConverNumToText | f8705d87daeef307a00ddb39193dcd16dd4816da | cec68827cf7bda07586ecbde423a5e8f28a3d2df | refs/heads/master | 2021-04-06T20:32:03.482369 | 2018-03-14T09:41:24 | 2018-03-14T09:41:24 | 125,189,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,803 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "DialogAboutt.h"
#include "mywstyle.h"
#include "currencys.h"
#include "write_read_file.h"
#include "myqstandarditemmodel.h"
#include <QDebug>
#include <QSettings>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QDoubleValidator *myDblVal = new QDoubleValidator(0, 99999999999999, 2,ui->lineEditNumber->parent());
ui->lineEditNumber->setValidator(myDblVal);
ui->lineEditNumber->setMaxLength(15);
ui->lineEditNumber->setAlignment(Qt::AlignRight);
ui->lineEditNumber->clear();
ui->pushButton->setStyleSheet(MyWstyle::StylebuttonOK());
ui->Santim->setStyleSheet(MyWstyle::StyleQcheckboxSwitch());
QString color="#45a1fe";
ui->comboBox->setStyleSheet(MyWstyle::StyleStondare("QComboBox",color,this->font()));
ui->comboBox_2->setStyleSheet(MyWstyle::StyleStondare("QComboBox",color,this->font()));
ui->textEdit->setStyleSheet(MyWstyle::StyleStondare("QTextEdit",color,this->font()));
ui->lineEditNumber->setStyleSheet(MyWstyle::StyleStondare("QLineEdit",color,this->font()));
ui->groupBox->setStyleSheet(MyWstyle::StyleStondare("QGroupBox",color,this->font()));
Model=new MyQStandardItemModel(0,Currencys::HaderMax);
ui->comboBox_2->setModel(Model);
ui->comboBox_2->setModelColumn(Currencys::Country);
ReadConty();
on_Santim_clicked();
QSettings SettingsCur("MyMainWindow","myapp");
SettingsCur.beginGroup("MainWindow");
ui->comboBox_2->setCurrentText(SettingsCur.value("current_Country").toString());
ui->comboBox->setCurrentText(SettingsCur.value("current_language").toString());
SettingsCur.endGroup();
}
void MainWindow::ReadConty()
{
Model->removeRows(0,Model->rowCount());
QString Read_F;
Write_Read_File::Read_File("Currency.Cur",Read_F);
qDebug()<<"Write_Read_File "<<Read_F;
if (Read_F.isEmpty()) {
return;
}
QStringList StrRow= Read_F.split("\n", QString::SkipEmptyParts);
for (int Row = 0; Row < StrRow.size(); ++Row) {
QStandardItem* itm = new QStandardItem();
Model->appendRow(itm);
QStringList datacolumRow_F=StrRow.at(Row).split("*=A@A=*", QString::KeepEmptyParts);
if (datacolumRow_F.size()<Currencys::HaderMax) {
return;
}
for (int col = 0; col < Currencys::HaderMax; ++col) {
Model->setData( Model->index(Row,col),datacolumRow_F.at(col));
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_lineEditNumber_returnPressed()
{
}
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
QString Dinar=Model->data(Model->index(ui->comboBox_2->currentIndex(),index+(Currencys::Currency_HomeAR))).toString();
QString Centimes=Model->data(Model->index(ui->comboBox_2->currentIndex(),index+(Currencys::Currency_partsAR))).toString();
ui->textEdit->setText(ConverNumToText::getTextConver(index,ui->lineEditNumber->text().toDouble(),ui->groupBox->isEnabled(),Dinar,Centimes));
}
void MainWindow::on_actionAbout_triggered()
{
DialogAboutt abo(this);
abo.setWindowTitle(ui->actionAbout->text());
abo.exec();
}
void MainWindow::on_pushButton_clicked()
{
if (Model->rowCount()>0) {
qDebug()<<ui->comboBox->currentIndex();
qDebug()<<"Model->rowCount()== "<<Model->rowCount();
QString Dinar=Model->data(Model->index(ui->comboBox_2->currentIndex(),ui->comboBox->currentIndex()+(Currencys::Currency_HomeAR))).toString();
QString Centimes=Model->data(Model->index(ui->comboBox_2->currentIndex(),ui->comboBox->currentIndex()+(Currencys::Currency_partsAR))).toString();
ui->textEdit->setText(ConverNumToText::getTextConver(ui->comboBox->currentIndex(),ui->lineEditNumber->text().toDouble(),ui->groupBox->isEnabled(),Dinar,Centimes));
}
}
void MainWindow::on_Santim_clicked()
{
if (ui->Santim->isChecked()) {
ui->groupBox->setEnabled(ui->Santim->isChecked());
} else {
ui->groupBox->setEnabled(ui->Santim->isChecked());
}
on_pushButton_clicked();
}
void MainWindow::on_CurrencySave_clicked()
{
}
void MainWindow::on_ADDCountry_clicked()
{
Currencys d(this);
d.exec();
ReadConty();
}
void MainWindow::closeEvent(QCloseEvent *)
{
QSettings SettingsCur("MyMainWindow","myapp");
SettingsCur.beginGroup("MainWindow");
SettingsCur.setValue("current_Country",ui->comboBox_2->currentText());
SettingsCur.setValue("current_language",ui->comboBox->currentText());
SettingsCur.endGroup();
}
void MainWindow::on_actionConvert_triggered()
{
on_ADDCountry_clicked();
}
void MainWindow::on_actionExit_triggered()
{
close();
}
| [
"toufikboudani@gmail.com"
] | toufikboudani@gmail.com |
83ea978ab8d824d3d7cb76dc26193121864e3ec1 | a964826c7d71c0b417157c3f56fced2936a17082 | /Source/Clockwork/Navigation/Navigable.cpp | 5dbbd662f1384e090ad6ae8b3891bc7eb5947878 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-openssl",
"BSD-3-Clause",
"NTP",
"BSL-1.0",
"LicenseRef-scancode-khronos",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Zlib"
] | permissive | gitter-badger/Clockwork | c95bcfc2066a11e2fcad0329a79cb69f0e7da4b5 | ec489a090697fc8b0dc692c3466df352ee722a6b | refs/heads/master | 2020-12-28T07:46:24.514590 | 2016-04-11T00:51:14 | 2016-04-11T00:51:14 | 55,931,507 | 0 | 0 | null | 2016-04-11T01:09:48 | 2016-04-11T01:09:48 | null | UTF-8 | C++ | false | false | 1,775 | cpp | //
// Copyright (c) 2008-2015 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/Context.h"
#include "../Navigation/Navigable.h"
#include "../DebugNew.h"
namespace Clockwork
{
extern const char* NAVIGATION_CATEGORY;
Navigable::Navigable(Context* context) :
Component(context),
recursive_(true)
{
}
Navigable::~Navigable()
{
}
void Navigable::RegisterObject(Context* context)
{
context->RegisterFactory<Navigable>(NAVIGATION_CATEGORY);
ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
ATTRIBUTE("Recursive", bool, recursive_, true, AM_DEFAULT);
}
void Navigable::SetRecursive(bool enable)
{
recursive_ = enable;
}
}
| [
"dragonCASTjosh@gmail.com"
] | dragonCASTjosh@gmail.com |
7c72fad0d04dd16c297db229310234d4bd3d43cd | 902a17bff646d17930ab0055ac454e8d976c6215 | /mcrouter/mcrouter_sr_deps-impl.h | a9304135ae523a8f9de66da7e256340e81549de3 | [
"MIT"
] | permissive | shazahmad/mcrouter | 7a58896eaa19cbdfaea9c28694b455e6ee436af7 | 3bac1c95e4ef5ecea9fed67fb11fb0805c7ec717 | refs/heads/master | 2023-03-28T17:34:03.546697 | 2021-04-01T04:41:04 | 2021-04-01T04:41:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace facebook {
namespace memcache {
struct SRHost {
public:
SRHost(){};
const std::string& getIp() const {
return "127.0.0.1";
}
uint16_t getPort() const {
return 0;
}
const std::optional<uint16_t> getTwTaskId() const {
return std::nullopt;
}
};
} // namespace memcache
} // namespace facebook
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
71354793243ac258af03763ae4f6547042b97cca | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/test/cpp/e4e005815c75f7e3c1431f2b8a7a47b97e6e30bfSvnRepoUpdater.h | e4e005815c75f7e3c1431f2b8a7a47b97e6e30bf | [
"MIT"
] | permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | C++ | false | false | 1,746 | h | /* Copyright 2013 Lieven Govaerts
*
* 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 __ufj_svnrepo_daemon__SvnRepoUpdater__
#define __ufj_svnrepo_daemon__SvnRepoUpdater__
#include <string>
#include <boost/make_shared.hpp>
#include "svn_client.h"
#include "svn_pools.h"
#include "SvnRepo.h"
#include "SvnRepoDAO.h"
#include "SvnRepoItemDAO.h"
using boost::shared_ptr;
class SvnRepoUpdater {
public:
// has to be public for make_shared, should not be used directly.
SvnRepoUpdater(std::string url);
// SvnRepoUpdater(shared_ptr<SvnRepo> svnrepo);
void update_repo();
private:
apr_pool_t *pool;
svn_client_ctx_t *ctx;
long start_rev;
shared_ptr<SvnRepoItemDAO> repoItemDAO;
shared_ptr<SvnRepoDAO> repoDAO;
shared_ptr<SvnRepo> repo;
/* Static member function for the C api */
static svn_error_t * log_entry_receiver_wrapper(void *baton,
svn_log_entry_t *log_entry,
apr_pool_t *pool);
svn_error_t *log_entry_receiver(svn_log_entry_t *log_entry,
apr_pool_t *pool);
};
#endif /* defined(__ufj_svnrepo_daemon__SvnRepoUpdater__) */
| [
"aliostad+github@gmail.com"
] | aliostad+github@gmail.com |
74b1299b9ea10388a7d7e800152355ab70f9347e | fdaa2c607e4bcbd23a3445a68c3d0a8265f92f2f | /Fall 2018/CS 225/mp1/cs225/HSLAPixel.cpp | 24a0b8aaa8c390ab538ebabec5a2de9b14244388 | [] | no_license | unnatr2/UIUC | a34cab9a0c867aa6e872800e365abaa25c08c9ae | 9ee14d0635116c03e7868cd6b3266aa9ea428570 | refs/heads/master | 2021-03-03T21:38:40.858998 | 2020-03-09T23:32:42 | 2020-03-09T23:32:42 | 245,987,822 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | /**
* @file HSLAPixel.cpp
* Implementation of the HSLAPixel class for use in with the PNG library.
*
* @author CS 225: Data Structures
* @version 2018r1-lab1
*/
#include "HSLAPixel.h"
#include <cmath>
#include <iostream>
using namespace std;
namespace cs225 {
HSLAPixel::HSLAPixel(){
h=0;
s=1;
l=1;
a=1;
}
HSLAPixel::HSLAPixel(double hue, double sat, double lum){
h=hue;
s=sat;
l=lum;
a=1;
}
HSLAPixel::HSLAPixel(double hue, double sat, double lum, double alpha){
h=hue;
s=sat;
l=lum;
a=alpha;
}
}
| [
"unnatr2@illinois.edu"
] | unnatr2@illinois.edu |
726de0eddce80613b48ff8cfb9343931b5aaafd0 | d5556ca59eb9e2db8c15f11e40809e4c009db828 | /src/P2p/P2pNodeConfig.h | afaabc4447893205cc9bd4a4ece499124715f96b | [] | no_license | cntemple/Citadel | d453e5b3fc7365bce24cbfad1f42e845fbfdff6a | 0bd4dc9df780c583ae9c2db35ce69d302d50896e | refs/heads/derate | 2022-07-21T19:19:04.447984 | 2022-07-08T11:30:36 | 2022-07-08T11:30:36 | 130,511,235 | 5 | 8 | null | 2019-06-26T12:58:22 | 2018-04-21T20:53:20 | C++ | UTF-8 | C++ | false | false | 1,745 | h | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2014-2016 SDN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <chrono>
#include "NetNodeConfig.h"
namespace CryptoNote {
class P2pNodeConfig : public NetNodeConfig {
public:
P2pNodeConfig();
// getters
std::chrono::nanoseconds getTimedSyncInterval() const;
std::chrono::nanoseconds getHandshakeTimeout() const;
std::chrono::nanoseconds getConnectInterval() const;
std::chrono::nanoseconds getConnectTimeout() const;
size_t getExpectedOutgoingConnectionsCount() const;
size_t getWhiteListConnectionsPercent() const;
boost::uuids::uuid getNetworkId() const;
size_t getPeerListConnectRange() const;
size_t getPeerListGetTryCount() const;
// setters
void setTimedSyncInterval(std::chrono::nanoseconds interval);
void setHandshakeTimeout(std::chrono::nanoseconds timeout);
void setConnectInterval(std::chrono::nanoseconds interval);
void setConnectTimeout(std::chrono::nanoseconds timeout);
void setExpectedOutgoingConnectionsCount(size_t count);
void setWhiteListConnectionsPercent(size_t percent);
void setNetworkId(const boost::uuids::uuid& id);
void setPeerListConnectRange(size_t range);
void setPeerListGetTryCount(size_t count);
private:
std::chrono::nanoseconds timedSyncInterval;
std::chrono::nanoseconds handshakeTimeout;
std::chrono::nanoseconds connectInterval;
std::chrono::nanoseconds connectTimeout;
boost::uuids::uuid networkId;
size_t expectedOutgoingConnectionsCount;
size_t whiteListConnectionsPercent;
size_t peerListConnectRange;
size_t peerListGetTryCount;
};
}
| [
"Nasser Sagoe"
] | Nasser Sagoe |
add4d3cc4b12c8d974f307112288ba7ac17e77d0 | bef56ea19df6f3e540c101b8517a2114675b804a | /APIGame_base/ObjectManager.h | 75560b6a3bedc59c8fa370cdc18a9deba2a96af0 | [] | no_license | kwt1326/2DProject | 2b0b829dd7331ca4ad3aa87e5c529fe157e23fb3 | 940f0721ac5e4e216ef9b763ac888260aad34fb0 | refs/heads/master | 2022-01-27T23:41:33.703150 | 2022-01-17T00:31:28 | 2022-01-17T00:31:28 | 149,836,434 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | h | #ifndef _OBJECTMANAGER_H_
#define _OBJECTMANAGER_H_
#include "GameObject.h"
#include <vector>
#include "Vector2.h"
#define OBJECT_MGR ObjectManager::GetInstance()
class ObjectManager
{
public:
static ObjectManager* m_Instance;
public:
static ObjectManager* GetInstance()
{
if (m_Instance == NULL) m_Instance = new ObjectManager;
return m_Instance;
}
public:
ObjectManager();
ObjectManager(const ObjectManager& val);
~ObjectManager();
public:
void Update(float dt);
void Render(HDC hdc);
void Release();
void AddObject(GameObject* obj);
void AddObject(GameObject* obj, Vector2 pos);
void Destroy(GameObject* obj);
void DestroyFront();
void DestroyPop();
std::vector<GameObject*>& GetObjectList() { return m_Object; }
GameObject* FindObject(GameObject* obj);
GameObject* FindObject(const char* name);
GameObject* FindObjectTag(const char* tag);
private:
std::vector<GameObject*> m_Object;
};
#endif // !_OBJECTMANAGER_H_
| [
"u1326@hotmail.com"
] | u1326@hotmail.com |
2edd060d59a2d00b6696e02f129594f891917988 | 7c1dc9907f6b009a87abb5a8a50e771a56b86bf4 | /DataStructure/codeforces/267_3.cpp | 7eb3a3986a114d2be6846ae5d73e9c72b6a7c786 | [] | no_license | TarunSaini063/Coding | 4b6a022a23488bbf5a4a1a746d865388095707ab | cd0abd63b469ab7f3be52eca0b5305a49c3f25b6 | refs/heads/master | 2021-08-22T17:41:58.152521 | 2021-05-22T08:58:28 | 2021-05-22T08:58:28 | 252,940,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,213 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ld double
#define ll long long
#define pb emplace_back
#define mk make_pair
#define mod 1000000007
#define ff first
#define ss second
#define sz(x) (int)x.size()
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define all(x) x.begin(),x.end()
ll power(ll a, ll b) {ll res = 1; a = a % mod; while (b) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b /= 2;} return res;}
ll invmod(ll a) {return power(a, mod - 2);}
ll n, m, k, arr[5555];
ll mp[5555][5555];
ll fun(int id, int req) {
// l++;
if (req <= 0) return 0;
if (id + req * m - 1 > n) return 0;
if (mp[id][req] != 0) return mp[id][req];
ll ans = 0;
ans = max(arr[id + m - 1] - arr[id - 1] + fun(id + m, req - 1), fun(id + 1, req));
mp[id][req] = ans;
return ans;
}
int main(void)
{
FIO
int t = 1;
// cin >> t;
while (t--)
{
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) cin >> arr[i];
for (int i = 1; i <= n; i++)arr[i] += arr[i - 1];
// fun(1, k);
for (int i = 1; i <= k; i++) {
for (int j = i * m; j <= n; j++) {
mp[i][j] = max(mp[i - 1][j - m] + arr[j] - arr[j - m], mp[i][j - 1]);
}
}
cout << mp[k][n] << "\n";
}
return 0;
} | [
"tsaini063@outlook.com"
] | tsaini063@outlook.com |
e7be5c51ad19a87eb12008ef9351126cd4edd676 | 0636e69f7cc3a94c49d6d481c0120d168d832ebf | /Solutions/TopCoder/SRM_DIV2/SRM608_DIV2/OneDimensionalRobotEasy.cpp | 35aca7661982ac2b76b11d0c274230ed882789e0 | [] | no_license | TurtleShip/ProgrammingContests | 33e0e261341e8f78c3d8d3bd66bbad0f511acc61 | 2ebd93f9b3d50c10a10c8731d17193e69382ca9b | refs/heads/master | 2021-01-13T02:07:37.539205 | 2016-11-30T18:50:46 | 2016-11-30T18:50:46 | 18,936,833 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,109 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef long long ll;
class OneDimensionalRobotEasy {
public:
int finalPosition(string commands, int A, int B);
};
int OneDimensionalRobotEasy::finalPosition(string cmd, int A, int B) {
int pos = 0;
for(int i=0; i < cmd.size(); i++) {
if(cmd[i] == 'R' && pos != B) pos++;
else if(cmd[i] == 'L' && pos != -A) pos--;
}
return pos;
}
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, string p0, int p1, int p2, bool hasAnswer, int p3) {
cout << "Test " << testNum << ": [" << "\"" << p0 << "\"" << "," << p1 << "," << p2;
cout << "]" << endl;
OneDimensionalRobotEasy *obj;
int answer;
obj = new OneDimensionalRobotEasy();
clock_t startTime = clock();
answer = obj->finalPosition(p0, p1, p2);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p3 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p3;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
string p0;
int p1;
int p2;
int p3;
{
// ----- test 0 -----
p0 = "RRLRRLLR";
p1 = 10;
p2 = 10;
p3 = 2;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = "RRRRR";
p1 = 3;
p2 = 4;
p3 = 4;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = "LLLLLLLLLLR";
p1 = 2;
p2 = 6;
p3 = -1;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = "RRRRRRRLRRLRRRRRRRRRRRRLRLRRRRRRRRLRRRRRLRRRRRRRRR";
p1 = 5;
p2 = 20;
p3 = 20;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 4 -----
p0 = "RLRLLLLLLLRLLLRLLLLLLLLRLLLLLRLLLRRLLLLLRLLLLLRLLL";
p1 = 34;
p2 = 15;
p3 = -30;
all_right = KawigiEdit_RunTest(4, p0, p1, p2, true, p3) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"sk765@cornell.edu"
] | sk765@cornell.edu |
1740a03f831533e0299e4ce174d7e990b646d02f | 21d7c1def6efcaf9ba5b74f521f75d2aaeae8192 | /scorched3d/scorched3d.ver01/scorched-dep-win32/include/wx/wx/protocol/file.h | 767dc700345b70dccd1b3f02cb0e993f90f593bc | [] | no_license | QuangNhat/GitHub | 99f3714fc38f3cf007ccc947b1647f41fe8aa29b | bc9a35c5bfe53a648b717c46b6bf5ddbca9b2ea3 | refs/heads/master | 2021-01-10T16:06:11.305568 | 2015-12-17T16:45:59 | 2015-12-17T16:45:59 | 48,186,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | h | /////////////////////////////////////////////////////////////////////////////
// Name: file.h
// Purpose: File protocol
// Author: Guilhem Lavaux
// Modified by:
// Created: 1997
// RCS-ID: $Id: file.h,v 1.1 2006/12/02 15:58:53 scara Exp $
// Copyright: (c) 1997, 1998 Guilhem Lavaux
// Licence: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#ifndef __WX_PROTO_FILE_H__
#define __WX_PROTO_FILE_H__
#if defined(__GNUG__) && !defined(__APPLE__)
#pragma interface "sckfile.h"
#endif
#include "wx/defs.h"
#if wxUSE_PROTOCOL_FILE
#include "wx/protocol/protocol.h"
#include "wx/url.h"
class WXDLLEXPORT wxFileProto: public wxProtocol {
DECLARE_DYNAMIC_CLASS(wxFileProto)
DECLARE_PROTOCOL(wxFileProto)
protected:
wxProtocolError m_error;
public:
wxFileProto();
~wxFileProto();
wxProtocolError GetError() { return m_error; }
bool Abort() { return TRUE; }
wxInputStream *GetInputStream(const wxString& path);
};
#endif // wxUSE_PROTOCOL_FILE
#endif // __WX_PROTO_FILE_H__
| [
"doquangnhat1@gmail.com"
] | doquangnhat1@gmail.com |
0fd75fc12cd1f8806ab45830fe6b67d0d435bee0 | e2df9dfe5051f7bc427778ab68b43cee3911a7bf | /automated-tests/src/dali-toolkit-internal/utc-Dali-Text-Segmentation.cpp | 5366164cb9af1c16cf528c34ff1d8d8483fee6c8 | [
"Apache-2.0"
] | permissive | pwisbey/dali-toolkit | 3a0d3358f0a07505786b0c97f83c48e9481e9791 | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | refs/heads/master | 2021-01-12T15:50:06.874102 | 2016-10-25T12:48:13 | 2016-10-25T12:48:13 | 71,880,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,788 | cpp | /*
* Copyright (c) 2015 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/internal/text/character-set-conversion.h>
#include <dali-toolkit/internal/text/segmentation.h>
#include <dali-toolkit-test-suite-utils.h>
#include <dali-toolkit/dali-toolkit.h>
using namespace Dali;
using namespace Toolkit;
using namespace Text;
// Tests the following functions with different scripts.
// void SetLineBreakInfo( const Vector<Character>& text,
// Vector<LineBreakInfo>& lineBreakInfo );
// void SetWordBreakInfo( const Vector<Character>& text,
// CharacterIndex startIndex,
// Length numberOfCharacters,
// Vector<WordBreakInfo>& wordBreakInfo );
//////////////////////////////////////////////////////////
namespace
{
struct BreakInfoData
{
std::string description; ///< Description of the test.
std::string text; ///< input text.
uint32_t index; ///< The index from where to start to query the break info.
uint32_t numberOfCharacters; ///< The requested number of characters.
std::string breakInfo; ///< The expected break info.
};
bool LineBreakInfoTest( const BreakInfoData& data )
{
// 1) Convert to utf32
Vector<Character> utf32;
utf32.Resize( data.text.size() );
const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( data.text.c_str() ),
data.text.size(),
&utf32[0u] );
utf32.Resize( numberOfCharacters );
// 2) Set the line break info for the whole text.
Vector<LineBreakInfo> lineBreakInfo;
lineBreakInfo.Resize( numberOfCharacters );
SetLineBreakInfo( utf32,
0u,
numberOfCharacters,
lineBreakInfo );
// 3) Update the word text info if it's requested for part of the text.
if( ( 0u != data.index ) &&
( numberOfCharacters != data.numberOfCharacters ) )
{
// Clear part of the line break info.
lineBreakInfo.Erase( lineBreakInfo.Begin() + data.index,
lineBreakInfo.Begin() + data.index + data.numberOfCharacters );
// Update the word line info.
SetLineBreakInfo( utf32,
data.index,
data.numberOfCharacters,
lineBreakInfo );
}
// 4) compare the results
std::ostringstream breakInfo;
for( unsigned int index = 0u; index < numberOfCharacters; ++index )
{
breakInfo << static_cast<unsigned int>( lineBreakInfo[index] );
}
if( data.breakInfo != breakInfo.str() )
{
std::cout << " text : [" << data.text << "]" << std::endl;
std::cout << " index : " << data.index << std::endl;
std::cout << " numberOfCharacters : " << data.numberOfCharacters << std::endl;
std::cout << " expected : [" << data.breakInfo << "]" << std::endl;
std::cout << " got : [" << breakInfo.str() << "]" << std::endl;
return false;
}
return true;
}
bool WordBreakInfoTest( const BreakInfoData& data )
{
// 1) Convert to utf32
Vector<Character> utf32;
utf32.Resize( data.text.size() );
const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( data.text.c_str() ),
data.text.size(),
&utf32[0u] );
utf32.Resize( numberOfCharacters );
// 2) Set the word break info for the whole text.
Vector<WordBreakInfo> wordBreakInfo;
wordBreakInfo.Resize( numberOfCharacters );
SetWordBreakInfo( utf32,
0u,
numberOfCharacters,
wordBreakInfo );
// 3) Update the word text info if it's requested for part of the text.
if( ( 0u != data.index ) &&
( numberOfCharacters != data.numberOfCharacters ) )
{
// Clear part of the word break info.
wordBreakInfo.Erase( wordBreakInfo.Begin() + data.index,
wordBreakInfo.Begin() + data.index + data.numberOfCharacters );
// Update the word break info.
SetWordBreakInfo( utf32,
data.index,
data.numberOfCharacters,
wordBreakInfo );
}
// 4) compare the results
std::ostringstream breakInfo;
for( unsigned int index = 0u; index < numberOfCharacters; ++index )
{
breakInfo << static_cast<unsigned int>( wordBreakInfo[index] );
}
if( data.breakInfo != breakInfo.str() )
{
std::cout << " text : [" << data.text << "]" << std::endl;
std::cout << " index : " << data.index << std::endl;
std::cout << " numberOfCharacters : " << data.numberOfCharacters << std::endl;
std::cout << " expected : [" << data.breakInfo << "]" << std::endl;
std::cout << " got : [" << breakInfo.str() << "]" << std::endl;
return false;
}
return true;
}
} // namespace
//////////////////////////////////////////////////////////
int UtcDaliTextSegnemtationSetLineBreakInfo(void)
{
tet_infoline(" UtcDaliTextSegnemtationSetLineBreakInfo");
struct BreakInfoData data[] =
{
{
"Zero characters",
"",
0u,
0u,
"",
},
{
"Latin script",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
0u,
317u,
"22222122222122222122212222212222212222222222122122221222221222222222122122220"
"2221221222212222222122222222221222222122222222122222222122212220"
"221222122222122222221222222222122212222221222222212220"
"22122222212222222122222222222122221222122222122222222222122222222222212220"
"222222122222221221222212212221222222122222222220",
},
{
"Latin script. Update initial paragraphs.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
0u,
141u,
"22222122222122222122212222212222212222222222122122221222221222222222122122220"
"2221221222212222222122222222221222222122222222122222222122212220"
"221222122222122222221222222222122212222221222222212220"
"22122222212222222122222222222122221222122222122222222222122222222222212220"
"222222122222221221222212212221222222122222222220",
},
{
"Latin script. Update mid paragraphs.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
141u,
128u,
"22222122222122222122212222212222212222222222122122221222221222222222122122220"
"2221221222212222222122222222221222222122222222122222222122212220"
"221222122222122222221222222222122212222221222222212220"
"22122222212222222122222222222122221222122222122222222222122222222222212220"
"222222122222221221222212212221222222122222222220",
},
{
"Latin script. Update final paragraphs.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
195u,
122u,
"22222122222122222122212222212222212222222222122122221222221222222222122122220"
"2221221222212222222122222222221222222122222222122222222122212220"
"221222122222122222221222222222122212222221222222212220"
"22122222212222222122222222222122221222122222122222222222122222222222212220"
"222222122222221221222212212221222222122222222220",
},
{
"Japanese script",
"韓国側は北朝鮮当局を通じて米ドルで賃金を支払う。\n"
"国際社会から様々な経済制裁を受ける北朝鮮にとっては出稼ぎ労働などと並んで重要な外貨稼ぎの手段となっている。\n"
"韓国統一省によると15年だけで1320億ウォン(約130億円)が同工業団地を通じ北朝鮮に支払われたという。",
0u,
132u,
"1111111111111111111111220"
"111111211111111111111111111111111111111111111111111220"
"11111111121111122211111212211211111111111111111111120",
},
{
"Chinese script",
"在被捕的64人中,警方落案起訴了35名男子和3名女子,他們年齡介乎15到70歲。\n"
"38人中有1人獲准保釋。\n"
"16名年齡介乎14到33歲的被捕人士獲准保釋候查,另有10人仍被拘留作進一步調查。",
0u,
95u,
"11112112111111112111111112111111121121220"
"2111111111220"
"21111112112111111111111211121111111111120",
}
};
const unsigned int numberOfTests = 7u;
for( unsigned int index = 0u; index < numberOfTests; ++index )
{
ToolkitTestApplication application;
if( !LineBreakInfoTest( data[index] ) )
{
tet_result(TET_FAIL);
}
}
tet_result(TET_PASS);
END_TEST;
}
int UtcDaliTextSegnemtationSetWordBreakInfo(void)
{
tet_infoline(" UtcDaliTextSegnemtationSetWordBreakInfo");
struct BreakInfoData data[] =
{
{
"Zero characters.",
"",
0u,
0u,
"",
},
{
"Latin script, full text.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
0u,
317u,
"11110011110011110011001110001111001111111110010011000111100111111110010011000"
"1100100111001111110011111111000111110011111110011111110011001000"
"100110011110011111100111111100011001111100111111001000"
"10011111001111110011111111110011000110011110011111111110011111111111001000"
"111110011111100100110001001100111110011111111100",
},
{
"Latin script, update first paragraph.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
0u,
77u,
"11110011110011110011001110001111001111111110010011000111100111111110010011000"
"1100100111001111110011111111000111110011111110011111110011001000"
"100110011110011111100111111100011001111100111111001000"
"10011111001111110011111111110011000110011110011111111110011111111111001000"
"111110011111100100110001001100111110011111111100",
},
{
"Latin script, update middle paragraphs.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
77u,
118u,
"11110011110011110011001110001111001111111110010011000111100111111110010011000"
"1100100111001111110011111111000111110011111110011111110011001000"
"100110011110011111100111111100011001111100111111001000"
"10011111001111110011111111110011000110011110011111111110011111111111001000"
"111110011111100100110001001100111110011111111100",
},
{
"Latin script, update last paragraph.",
"Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
"Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
"Ne nec nulla regione albucius, mea doctus delenit ad!\n"
"Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
"Quidam corpora at duo. An eos possim scripserit?",
269u,
48u,
"11110011110011110011001110001111001111111110010011000111100111111110010011000"
"1100100111001111110011111111000111110011111110011111110011001000"
"100110011110011111100111111100011001111100111111001000"
"10011111001111110011111111110011000110011110011111111110011111111111001000"
"111110011111100100110001001100111110011111111100",
},
{
"Japanese script, full text.",
"韓国側は北朝鮮当局を通じて米ドルで賃金を支払う。\n"
"国際社会から様々な経済制裁を受ける北朝鮮にとっては出稼ぎ労働などと並んで重要な外貨稼ぎの手段となっている。\n"
"韓国統一省によると15年だけで1320億ウォン(約130億円)が同工業団地を通じ北朝鮮に支払われたという。",
0u,
132u,
"0000000000000010000000000"
"000000000000000000000000000000000000000000000000000000"
"00000000010000011100110001100000000000000000000000000",
},
{
"Japanese script, update first paragraph.",
"韓国側は北朝鮮当局を通じて米ドルで賃金を支払う。\n"
"国際社会から様々な経済制裁を受ける北朝鮮にとっては出稼ぎ労働などと並んで重要な外貨稼ぎの手段となっている。\n"
"韓国統一省によると15年だけで1320億ウォン(約130億円)が同工業団地を通じ北朝鮮に支払われたという。",
0u,
25u,
"0000000000000010000000000"
"000000000000000000000000000000000000000000000000000000"
"00000000010000011100110001100000000000000000000000000",
},
{
"Japanese script, update middle paragraph.",
"韓国側は北朝鮮当局を通じて米ドルで賃金を支払う。\n"
"国際社会から様々な経済制裁を受ける北朝鮮にとっては出稼ぎ労働などと並んで重要な外貨稼ぎの手段となっている。\n"
"韓国統一省によると15年だけで1320億ウォン(約130億円)が同工業団地を通じ北朝鮮に支払われたという。",
25u,
54u,
"0000000000000010000000000"
"000000000000000000000000000000000000000000000000000000"
"00000000010000011100110001100000000000000000000000000",
},
{
"Japanese script, update last paragraph.",
"韓国側は北朝鮮当局を通じて米ドルで賃金を支払う。\n"
"国際社会から様々な経済制裁を受ける北朝鮮にとっては出稼ぎ労働などと並んで重要な外貨稼ぎの手段となっている。\n"
"韓国統一省によると15年だけで1320億ウォン(約130億円)が同工業団地を通じ北朝鮮に支払われたという。",
79u,
53u,
"0000000000000010000000000"
"000000000000000000000000000000000000000000000000000000"
"00000000010000011100110001100000000000000000000000000",
},
{
"Chinese script, full text.",
"在被捕的64人中,警方落案起訴了35名男子和3名女子,他們年齡介乎15到70歲。\n"
"38人中有1人獲准保釋。\n"
"16名年齡介乎14到33歲的被捕人士獲准保釋候查,另有10人仍被拘留作進一步調查。",
0u,
95u,
"00001000000000001000000000000000010010000"
"1000000000000"
"10000001001000000000000000010000000000000",
},
{
"Chinese script, update first paragraph.",
"在被捕的64人中,警方落案起訴了35名男子和3名女子,他們年齡介乎15到70歲。\n"
"38人中有1人獲准保釋。\n"
"16名年齡介乎14到33歲的被捕人士獲准保釋候查,另有10人仍被拘留作進一步調查。",
0u,
41u,
"00001000000000001000000000000000010010000"
"1000000000000"
"10000001001000000000000000010000000000000",
},
{
"Chinese script, update middle paragraph.",
"在被捕的64人中,警方落案起訴了35名男子和3名女子,他們年齡介乎15到70歲。\n"
"38人中有1人獲准保釋。\n"
"16名年齡介乎14到33歲的被捕人士獲准保釋候查,另有10人仍被拘留作進一步調查。",
41u,
13u,
"00001000000000001000000000000000010010000"
"1000000000000"
"10000001001000000000000000010000000000000",
},
{
"Chinese script, update last paragraph.",
"在被捕的64人中,警方落案起訴了35名男子和3名女子,他們年齡介乎15到70歲。\n"
"38人中有1人獲准保釋。\n"
"16名年齡介乎14到33歲的被捕人士獲准保釋候查,另有10人仍被拘留作進一步調查。",
54u,
41u,
"00001000000000001000000000000000010010000"
"1000000000000"
"10000001001000000000000000010000000000000",
}
};
const unsigned int numberOfTests = 13u;
for( unsigned int index = 0u; index < numberOfTests; ++index )
{
ToolkitTestApplication application;
if( !WordBreakInfoTest( data[index] ) )
{
tet_result(TET_FAIL);
}
}
tet_result(TET_PASS);
END_TEST;
}
| [
"v.cebollada@samsung.com"
] | v.cebollada@samsung.com |
342ff93708a2f090e016c292ba4d9f94dc10e956 | cdb55dbdd700a3f456bc67775374dd2a5f99f049 | /test/src/physics/collision/island/IslandContainerTest.cpp | 3420a8dad53ad2c547c64e12dc83a039ee43a62b | [
"MIT"
] | permissive | wangscript007/urchinEngine | 1bfd6fb9ae6ed30154d29b082856101b9a8ef202 | 88f5f70d319299e2df6c006cdeabd6bfb622437b | refs/heads/master | 2022-12-30T18:06:53.231268 | 2020-10-07T19:03:56 | 2020-10-07T19:03:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,289 | cpp | #include <cppunit/TestSuite.h>
#include <cppunit/TestCaller.h>
#include "AssertHelper.h"
#include "physics/collision/island/IslandContainerTest.h"
using namespace urchin;
/**
* Create 4 bodies. Body n will be in contact with body n+1.
* All bodies of container should belong to same island.
*/
void IslandContainerTest::cascadeMergeIslands()
{
TestBody* bodies[] = {new TestBody(), new TestBody(), new TestBody(), new TestBody()};
std::vector<IslandElement *> bodiesVector(bodies, bodies + (sizeof(bodies) / sizeof(TestBody*)));
IslandContainer islandContainer;
islandContainer.reset(bodiesVector);
islandContainer.mergeIsland(bodies[0], bodies[1]); //body 0 is in contact with body 1
islandContainer.mergeIsland(bodies[1], bodies[2]); //body 1 is in contact with body 2
islandContainer.mergeIsland(bodies[2], bodies[3]); //body 2 is in contact with body 3
const std::vector<IslandElementLink> &islandElementsLink = islandContainer.retrieveSortedIslandElements();
AssertHelper::assertUnsignedInt(islandElementsLink.size(), 4);
unsigned int islandId = islandElementsLink[0].islandIdRef;
for(std::size_t i=1; i<islandElementsLink.size(); ++i)
{
AssertHelper::assertUnsignedInt(islandElementsLink[i].islandIdRef, islandId);
}
delete bodies[0]; delete bodies[1]; delete bodies[2]; delete bodies[3];
}
/**
* Create 3 bodies. Each body will be in contact with all others bodies
* All bodies of container should belong to same island.
*/
void IslandContainerTest::mergeAllIslands()
{
TestBody* bodies[] = {new TestBody(), new TestBody(), new TestBody()};
std::vector<IslandElement *> bodiesVector(bodies, bodies + (sizeof(bodies) / sizeof(TestBody*)));
IslandContainer islandContainer;
islandContainer.reset(bodiesVector);
islandContainer.mergeIsland(bodies[0], bodies[1]); //body 0 is in contact with body 1
islandContainer.mergeIsland(bodies[0], bodies[2]); //body 0 is in contact with body 2
islandContainer.mergeIsland(bodies[1], bodies[2]); //body 1 is in contact with body 2
const std::vector<IslandElementLink> &islandElementsLink = islandContainer.retrieveSortedIslandElements();
AssertHelper::assertUnsignedInt(islandElementsLink.size(), 3);
unsigned int islandId = islandElementsLink[0].islandIdRef;
for(std::size_t i=1; i<islandElementsLink.size(); ++i)
{
AssertHelper::assertUnsignedInt(islandElementsLink[i].islandIdRef, islandId);
}
delete bodies[0]; delete bodies[1]; delete bodies[2];
}
/**
* Create 4 bodies. Body 0 is in contact with body 3. Body 2 is in contact with body 1.
* We should have two distinct islands.
*/
void IslandContainerTest::createTwoSeparateIslands()
{
TestBody* bodies[] = {new TestBody(), new TestBody(), new TestBody(), new TestBody()};
std::vector<IslandElement *> bodiesVector(bodies, bodies + (sizeof(bodies) / sizeof(TestBody*)));
IslandContainer islandContainer;
islandContainer.reset(bodiesVector);
islandContainer.mergeIsland(bodies[0], bodies[3]); //body 0 is in contact with body 3
islandContainer.mergeIsland(bodies[2], bodies[1]); //body 2 is in contact with body 1
const std::vector<IslandElementLink> &islandElementsLink = islandContainer.retrieveSortedIslandElements();
AssertHelper::assertUnsignedInt(islandElementsLink.size(), 4);
AssertHelper::assertUnsignedInt(islandElementsLink[0].islandIdRef, islandElementsLink[1].islandIdRef);
AssertHelper::assertUnsignedInt(islandElementsLink[2].islandIdRef, islandElementsLink[3].islandIdRef);
AssertHelper::assertTrue(islandElementsLink[0].islandIdRef != islandElementsLink[2].islandIdRef);
delete bodies[0]; delete bodies[1]; delete bodies[2]; delete bodies[3];
}
CppUnit::Test *IslandContainerTest::suite()
{
auto *suite = new CppUnit::TestSuite("IslandContainerTest");
suite->addTest(new CppUnit::TestCaller<IslandContainerTest>("cascadeMergeIslands", &IslandContainerTest::cascadeMergeIslands));
suite->addTest(new CppUnit::TestCaller<IslandContainerTest>("mergeAllIslands", &IslandContainerTest::mergeAllIslands));
suite->addTest(new CppUnit::TestCaller<IslandContainerTest>("createTwoSeparateIslands", &IslandContainerTest::createTwoSeparateIslands));
return suite;
}
| [
"petitg1987@gmail.com"
] | petitg1987@gmail.com |
585e32281d3f977624380831e378624b1cb61cf8 | d5c436ee059bede2b8af4de15b2a12c9964cbc14 | /bankingSystem.cpp | dc502eefa22b9b40adf17924e623c0dc625388c0 | [] | no_license | sparshgoyal2014/cppCodes | 805e10536c853d9bd2235f058f7f2ad1e27c99d3 | bf9f4021e771de46b332dba0e76aede2e4febf47 | refs/heads/master | 2023-04-01T09:16:01.831508 | 2021-04-07T16:45:28 | 2021-04-07T16:45:28 | 257,046,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,054 | cpp | #include<iostream>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<map>
using namespace std;
#define MIN_BALANCE 500
class InsufficientFunds{};
class account{
private:
long accountNumber;
string firstName;
string lastName;
float balance;
static long nextAccountNumber;
public:
account(){};
account(string fname , string lname , float balance);
long getAccNo(){
return accountNumber;
}
string getFirstName(){
return firstName;
}
string getLastname(){
return lastName;
}
float getBalance(){
return balance;
}
void deposit(float amount);
void withdraw(float amount);
static void setLastAccountNumber(long accountNumber);
static long getLastAccountNumber();
friend ofstream & operator<<(ofstream &ofs , account &acc);
friend ifstream & operator>>(ifstream &ifs , account &acc);
friend ostream & operator<<(ostream &os , account &acc);
};
long account :: nextAccountNumber = 0;
class bank{
private:
map<long , account> accounts;
public:
bank();
account openAccount(string fname , string lname , float balance);
account balanceEnquiry(long accountNumber );
account deposit(long accountNumber , float amount);
account withdraw(long accountNumber , float amount);
void closeAccount(long accountNumber);
void showAllAccounts();
~bank();
};
int main(){
bank b;
account acc;
int choice;
string fname, lname;
long accountNumber;
float balance;
float amount;
cout << "***BANKING SYSTEM***" << endl;
do{
cout << "\nSelect one option below ";
cout << "\n\t1. open an Account ";
cout << "\n\t2. Balance Enquiry " ;
cout << "\n\t3. Deposit ";
cout << "\n\t4. Withdrawal ";
cout << "\n\t5. Close an Account ";
cout << "\n\t6. Show all Accounts " ;
cout << "\n\t7. quit ";
cin>>choice;
switch(choice){
case 1:
cout << "Enter First Name: ";
cin>>fname;
cout << "Enter Last Name: ";
cin>>lname;
cout << "Enter Intil Balance: ";
cin>>balance;
acc = b.openAccount(fname , lname , balance);
cout << endl << "*congratulations Accouont is Created*" << endl;
cout << acc;
break;
case 2:
cout << "Enter Account Number: ";
cin>> accountNumber;
acc = b.balanceEnquiry(accountNumber);
cout << endl << "Your Account Details " << endl;
cout << acc;
break;
case 3:
cout << "Enter Account Number :" ;
cin>> accountNumber;
cout <<"Enter Balance: ";
cin >> amount;
acc = b.deposit(accountNumber , amount);
cout << endl << "Amount is Deposited " << endl;
cout <<acc;
break;
case 4:
cout << "Enter ccount Number :" ;
cin>> accountNumber;
cout << "Enter Balance:" ;
cin >> amount;
acc = b.withdraw(accountNumber , amount);
cout << endl << "Amount withdrawn" << endl;
cout << acc;
break;
case 5:
cout << "Enter Account Number :" ;
cin>> accountNumber;
b.closeAccount(accountNumber);
cout << endl << "Account is closed "<< endl;
cout << acc;
break;
case 6:
b.showAllAccounts();
break;
case 7:
break;
default:
cout << "\nEnter correct choice";
exit(0);
}
}while(choice!=7);
return 0;
}
account::account(string fname , string lname , float balance){
nextAccountNumber++;
accountNumber = nextAccountNumber;
firstName = fname;
lastName = lname;
this->balance = balance;
}
void account:: deposit(float amount){
balance += amount;
}
void account:: withdraw(float amount){
if(balance - amount <MIN_BALANCE)
throw InsufficientFunds();
balance -= amount;
}
void account:: setLastAccountNumber(long accountNumber){
nextAccountNumber = accountNumber;
}
long account::getLastAccountNumber(){
return nextAccountNumber;
}
ofstream & operator<<(ofstream &ofs , account &acc){
ofs << acc.accountNumber << endl;
ofs << acc.firstName << endl;
ofs << acc.lastName << endl;
ofs << acc.balance << endl;
return ofs;
}
ifstream & operator>>(ifstream &ifs , account &acc){
ifs>>acc.accountNumber;
ifs>>acc.firstName ;
ifs>>acc.lastName;
ifs>>acc.balance;
return ifs;
}
ostream & operator<<(ostream &os , account &acc){
os<<"First Name:" << acc.getFirstName() << endl;
os<<"Last Name:" << acc.getLastname() << endl;
os<<"Account Number:" << acc.getAccNo() << endl;
os<<"Balance:" << acc.getBalance() << endl;
return os;
}
bank::bank(){
account acc;
ifstream infile;
infile.open("bank.data");
if(!infile){
cout << "Error in opening! File not Found!!" << endl;
return ;
}
while(!infile.eof()){
infile>>acc;
accounts.insert(pair<long,account>(acc.getAccNo(),acc));
}
account::setLastAccountNumber(acc.getAccNo());
infile.close();
}
account bank::openAccount(string fname , string lname , float balance){
ofstream outfile;
account acc(fname , lname , balance);
accounts.insert(pair<long, account>(acc.getAccNo(),acc));
outfile.open("Bank.data" , ios::trunc);
map<long , account>::iterator itr;
for(itr = accounts.begin();itr!=accounts.end();itr++){
outfile<<itr->second;
}
outfile.close();
return acc;
}
account bank::balanceEnquiry(long accountNumber){
map<long , account>::iterator itr = accounts.find(accountNumber);
return itr->second;
}
account bank::deposit(long accountNumber , float amount){
map<long , account>:: iterator itr = accounts.find(accountNumber);
itr->second.deposit(amount);
return itr->second;
}
account bank::withdraw(long accountNumber , float amount){
map<long , account>:: iterator itr = accounts.find(accountNumber);
itr->second.withdraw(amount);
return itr->second;
}
void bank::closeAccount(long accountNumber){
map<long , account>:: iterator itr = accounts.find(accountNumber);
cout << "Account Deleted " << itr->second;
accounts.erase(accountNumber);
}
void bank::showAllAccounts(){
map<long , account>::iterator itr;
for(itr = accounts.begin();itr!=accounts.end();itr++){
cout << "Account " << itr->first << endl << itr->second << endl;
}
}
bank::~bank(){
ofstream outfile;
outfile.open("Bank.data" , ios::trunc);
map<long , account>:: iterator itr;
for(itr = accounts.begin();itr!=accounts.end();itr++){
outfile<<itr->second;
}
outfile.close();
}
| [
"sparshgoyal2014@gmail.com"
] | sparshgoyal2014@gmail.com |
a42fcfddb7f00b8105d0bf3f6f1451ea2a067d40 | e173fc6d152b4313036df82d6b61cad2646a536b | /OsmmdCore/InsertCommandArg.cpp | 9b72272ab5dd85bd958aeb08e4aa765b1bff5ecb | [] | no_license | sinzens/Osmmd | 0b829927f929817aeef6e100f70c6f2f374f672b | c7f51bec40f1e4a1a02ff73d016fc9253acd89fc | refs/heads/master | 2023-07-15T00:03:19.945782 | 2021-09-09T15:57:12 | 2021-09-09T15:57:12 | 400,107,044 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | cpp | /*
* Created by Zeng Yinuo, 2021.09.06
* Edited by Zeng Yinuo, 2021.09.07
*/
#include "InsertCommandArg.h"
Osmmd::InsertCommandArg::InsertCommandArg(const std::string& table, std::shared_ptr<RowValue> value)
: Table(table)
, Value(value)
{
}
Osmmd::InsertCommandArg& Osmmd::InsertCommandArg::operator=(const InsertCommandArg& other)
{
this->Table = other.Table;
this->Value = other.Value;
return *this;
}
| [
"1187261181@qq.com"
] | 1187261181@qq.com |
a22d3ce913549bd3e6e465211bc4df380782701b | d8fc8a50fbedfc80c2ba8bbc57697763751d7144 | /src/Racecar.hpp | fef3b93aa48797765c0f819c024db83a5e3fb4fb | [] | no_license | sid-dey/racebot | 1163bea502107af0f8b88fdd64bc8c5663576c20 | 5a2b7d8d20c953bec0e073882619b18c49fbf230 | refs/heads/main | 2023-03-21T19:41:59.158879 | 2021-03-11T00:44:01 | 2021-03-11T00:44:01 | 346,533,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | hpp | #ifndef RACECAR_HPP
#define RACECAR_HPP
#include <vector>
class Racecar {
private:
std::vector<double> _time;
std::vector<double> _state;
std::vector<std::vector<double>> _state_array;
std::vector<std::vector<double>> _input_array;
const double _coeff[9] = {
0.000016614664891, -0.000000195546174, 0.000003619042463,
0.000000438199867, -0.081112039381716, -1.473644114877512,
0.125688871505601, 0.076458603684900, -0.013991208725085};
const double _wheelbase = 0.5;
const double _height = 0.25;
std::vector<double> _rover_x_bounds;
std::vector<double> _rover_y_bounds;
const double _max_steering = 0.4; // radians
const double _min_steering = -0.4; // radians
const double _max_v = 3; // m/s
const double _min_v = -3; // m/s
public:
Racecar(std::vector<double> x0);
std::vector<double> dynamics(Racecar R, double t, std::vector<double> z, std::vector<double> Tnom, std::vector<std::vector<double>> Unom, bool brake);
};
#endif //RACECAR_HPP
| [
"siddey@umich.edu"
] | siddey@umich.edu |
2ce9a97ef7584e5bb38b007b8b949d289cee281f | c550ffcf8778f21a4c4cda666a1c65581b654b38 | /Devices/VNCInput.h | 8655c7cfde47a49cbe964e339ee0f888f0edf311 | [] | no_license | OpenEngineDK/extensions-VNCServer | 625a5347aae5f631839ce324de9542bca5bd584d | a61a4215b3c035ee12850d52b8ac1462da903a87 | refs/heads/master | 2016-09-14T05:53:07.693664 | 2016-05-05T00:21:20 | 2016-05-05T00:21:20 | 58,073,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | h | //
// -------------------------------------------------------------------
// Copyright (C) 2007 OpenEngine.dk (See AUTHORS)
//
// This program is free software; It is covered by the GNU General
// Public License version 2 or any later version.
// See the GNU General Public License for more details (see LICENSE).
//--------------------------------------------------------------------
#ifndef _OE_VNC_INPUT_H_
#define _OE_VNC_INPUT_H_
#include <Devices/IKeyboard.h>
#include <Devices/IMouse.h>
#include <Core/Event.h>
namespace OpenEngine {
namespace Display {
class VNCEnvironment;
}
namespace Devices {
using namespace Core;
/**
* Short description.
*
* @class VNCInput VNCInput.h ons/VNCServer/Display/VNCInput.h
*/
class VNCInput
: public Devices::IKeyboard
, public Devices::IMouse {
private:
Core::Event<KeyboardEventArg> keyEvent;
Core::Event<MouseMovedEventArg> mouseMovedEvent;
Core::Event<MouseButtonEventArg> mouseButtonEvent;
MouseState state;
public:
VNCInput(Display::VNCEnvironment*);
IEvent<KeyboardEventArg>& KeyEvent() ;
IEvent<MouseButtonEventArg>& MouseButtonEvent() ;
IEvent<MouseMovedEventArg>& MouseMovedEvent() ;
void HideCursor() ;
void ShowCursor() ;
void SetCursor(int x, int y) ;
MouseState GetState() ;
};
} // NS Devices
} // NS OpenEngine
#endif
| [
"ptx@openengine.dk"
] | ptx@openengine.dk |
23608b0f69bdd7fbf489b85bd18e209fd769d86f | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/TRiAS/TRiAS03/ClassProps/SELOPRPT.CXX | 39105288c3b84afa2e64c7acc098c9ae279e0644 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,682 | cxx | // Ein TreeViewCtrl, mit welchem Objekteigenschaften ausgewählt werden können -
// File: SELOPRPT.CXX
#include "featurep.hxx"
#include "propname.hxx"
#include "seloprpt.hxx"
static char s_cbPropInfo[_MAX_PATH];
// Konstruktor/Destruktor/Initialisierung -------------------------------------
CSelObjPropTree :: CSelObjPropTree (pDialogWindow pW, ResID uiRes,
ResourceFile &rRF, IObjectProps *pIProps)
: CTreeViewCtrl (pW, uiRes), m_Props(pIProps)
{
}
CSelObjPropTree :: ~CSelObjPropTree (void)
{
}
bool CSelObjPropTree :: InitControl (void)
{
if (!Control::FInit()) return false; // Initialisieren
m_Items.erase();
// Objekteigenschaften in Gruppen sortiert im Baum einhängen
HRESULT hr = m_Props -> OnNewReferenceObject (0L); // alle ObjProps installieren
if (FAILED(hr)) return hr;
WEnumObjProps IEnum;
hr = m_Props -> EnumObjectProps (IEnum.ppi());
if (FAILED(hr)) return hr;
// Objekteigenschaften durchgehen
WObjectProperty IProp;
for (IEnum -> Reset();
S_OK == IEnum -> Next (1, (IUnknown **)IProp.ppi(), NULL); /**/)
{
// vollständigen Namen geben lassen
IProp -> GetPropInfo (s_cbPropInfo, sizeof(s_cbPropInfo), NULL);
// ParentItem der Property aus dem Baum besorgen
CPropertyName PropName (s_cbPropInfo);
HTREEITEM hParent = CalcParentItem (PropName.GetGroup());
os_string rstr = PropName.GetSubGroup();
if (0 != rstr.size()) {
HTREEITEM hSubGroup = CalcSubGroupItem (hParent, rstr.c_str());
if (NULL != hSubGroup)
InsertItem (PropName.GetName().c_str(), hSubGroup);
else
InsertItem (PropName.GetName().c_str(), hParent);
} else
InsertItem (PropName.GetName().c_str(), hParent);
}
return true;
}
// Finden des ParentItems im Control, ansonsten TVI_ROOT liefern --------------
HTREEITEM CSelObjPropTree :: CalcParentItem (os_string &strGroup)
{
HTREEITEM hItem;
CItemMap::const_iterator it = m_Items.find (strGroup);
if (it == m_Items.end()) {
// erstes mal
hItem = InsertItem (strGroup.c_str(), TVI_ROOT);
m_Items.insert (make_pair(strGroup, hItem));
} else
hItem = (*it).second;
return hItem;
}
// Finden bzw. hinzufügen eines GruppenItems zu einem Parent ------------------
HTREEITEM CSelObjPropTree::CalcSubGroupItem (HTREEITEM hParent, LPCSTR pcSubGroup)
{
HTREEITEM hChild = GetChildItem (hParent);
while (NULL != hChild) {
string str = GetItemText (hChild);
if (str == pcSubGroup)
return hChild; // SubGroup gibt es schon
hChild = GetNextItem (hChild, TVGN_NEXT);
}
// nichts gefunden, also neue SubGroup einfügen
return InsertItem (pcSubGroup, hParent);
}
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
4245680e0407e3e7a7964531d3223cb20677adcf | 8b7dc8357b177c0a48f03db4bc822dd4af868096 | /tomasulo.cpp | b10c1012a54a97fce793a49890184fe2c2740c72 | [] | no_license | fangtiancheng/PPCA | ef0ad0387f34b306928d4b1a21f01396c2376f2a | 138f6bef13336a5cf7684236fce081cadf476939 | refs/heads/master | 2022-11-24T13:13:48.941067 | 2020-07-19T12:32:48 | 2020-07-19T12:32:48 | 279,234,162 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,943 | cpp | #include <iostream>
#include <cstring>
#include <cstdio>
//面向硬件编程
enum INSTRUCTION{
LUI, //U
AUIPC, //U
JAL, //J
JALR, //I
BEQ, //B
BNE, //B
BLT, //B
BGE, //B
BLTU, //B
BGEU, //B
LB, //I
LH, //I
LW, //I
LBU, //I
LHU, //I
SB, //S
SH, //S
SW, //S
ADDI, //I
SLTI,
SLTIU,
XORI,
ORI,
ANDI,
SLLI,
SRLI,
SRAI,
ADD, //R
SUB,
SLL,
SLT,
SLTU,
XOR,
SRL,
SRA,
OR,
AND
};
const char* name[] = {"LUI","AUIPC","JAL","JALR","BEQ","BNE","BLT","BGE","BLTU","BGEU","LB","LH","LW","LBU","LHU","SB","SH","SW","ADDI","SLTI","SLTIU","XORI","ORI","ANDI","SLLI","SRLI","SRAI","ADD","SUB","SLL","SLT","SLTU","XOR","SRL","SRA","OR","AND"};
const char* REGI_name[] = {"zero","ra","sp","qp","tp","t0","t1","t2","s0","s1","a0","a1","a2","a3","a4","a5","a6","a7","s2","s3","s4","s5","s6","s7","s8","s9","s10","s11","t3","t4","t5","t6"};
enum INSTRUCTION_TYPE{_U,_J,_B,_I,_S,_R};
struct error{
unsigned int line,num;
error(unsigned int l,unsigned int n):line(l),num(n){}
void printerror(){
std::cerr<<"ERROR in line "<<line<<"!\tnum = "<<num<<std::endl;
}
};
struct move{};
struct end{
int num;
end(int n=0):num(n){}
};
inline bool is_num(char c){
if(c>='0'&&c<='9') return true;
if(c>='A'&&c<='F') return true;
if(c=='@') throw move();
if(c==EOF) throw end();
return false;
}
class IF_IDs{
public:
bool NOP=true;
uint32_t PC=0;//执行这条指令的PC
uint32_t raw_instruction=0;
};
class ID_EXs{//9个元素
public:
bool NOP=true;//EX是否为空指令
uint32_t PC=0,NPC=0;//执行这条指令的PC,预测PC
INSTRUCTION instruction=LUI;
INSTRUCTION_TYPE type=_J;
uint32_t imm=0,rs1=0,rs2=0,rd=0;
};
class EX_MEMs{//8个元素
public:
bool NOP=true;//MEM是否为空指令
uint32_t PC=0;//PC,预测PC
INSTRUCTION instruction=LUI;
INSTRUCTION_TYPE type=_J;
uint32_t MEM_index=0;
uint32_t to_MEM=0;
uint32_t to_WB=0;
uint32_t WB_index=0;
};
class MEM_WBs{
public:
bool NOP=true;//WB是否为空指令
INSTRUCTION instruction;
INSTRUCTION_TYPE type=_J;
// uint32_t PC=0;
uint16_t WB_index=0;
uint32_t to_WB=0;
};
class Reservation_Stations{//保留站
public:
bool busy=false;
INSTRUCTION instruction;
};
class BroadCast{
public:
bool NOP=true;
INSTRUCTION instruction;
uint32_t rd=0;//1~31
uint32_t value=0;
};
INSTRUCTION decoder(uint32_t num){//取raw指令,返回指令
INSTRUCTION instruction;
if((num&3u) != 0x3) throw error(__LINE__,num);
unsigned int sub_num1 = (num>>12)%8;
if( ((num>>2)&1) == 0x1) {// 111
if( ((num>>3)&1) == 0x1){// 1111
instruction = JAL;
} else {// 0111
if( ((num>>4)&1) == 0x1){// 10111
if( ((num>>5)&1) == 0x1){// 010111
instruction = LUI;
}else {// 110111
instruction = AUIPC;
}
} else{// 00111
instruction = JALR;
}
}
}else{// 011
if( ((num>>3)&1u) == 0x1) throw error(__LINE__,num);// 1011
if( ((num>>4)&1u) == 0x1){// 10011
if( ((num>>6)&1u) == 0x1) throw error(__LINE__,num);
unsigned int sub_num2 = (num>>30);
if( ((num>>5)&1u) == 0x1){// 0110011
switch (sub_num1){
case 0x0:
if(sub_num2==0x1) instruction = SUB;
else instruction = ADD;
break;
case 0x1: instruction = SLL; break;
case 0x2: instruction = SLT; break;
case 0x3: instruction = SLTU; break;
case 0x4: instruction = XOR; break;
case 0x5:
if(sub_num2==0x1) instruction = SRA;
else instruction = SRL;
break;
case 0x6: instruction = OR; break;
case 0x7: instruction = AND; break;
default: throw error(__LINE__,num); break;
}
}else{// 0010011
switch (sub_num1){
case 0x0: instruction = ADDI; break;
case 0x1: instruction = SLLI; break;
case 0x2: instruction = SLTI; break;
case 0x3: instruction = SLTIU;break;
case 0x4: instruction = XORI; break;
case 0x5:
if(sub_num2==0x1) instruction = SRAI;
else instruction = SRLI;
break;
case 0x6: instruction = ORI; break;
case 0x7: instruction = ANDI; break;
default: throw error(__LINE__,num); break;
}
}
}else{// 00011
if( ((num>>5)&1) == 0x1){// 100011
if( ((num>>6)&1) == 0x1){// 1100011
switch (sub_num1){// 1100011
case 0x0: instruction = BEQ; break;
case 0x1: instruction = BNE; break;
case 0x4: instruction = BLT; break;
case 0x5: instruction = BGE; break;
case 0x6: instruction = BLTU; break;
case 0x7: instruction = BGEU; break;
default: throw error(__LINE__,num); break;
}
}else{// 0100011
switch (sub_num1){
case 0x0: instruction = SB; break;
case 0x1: instruction = SH; break;
case 0x2: instruction = SW; break;
default: throw error(__LINE__,num); break;
}
}
}else{// 000011
if( ((num>>6)&1u) == 0x1) throw error(__LINE__,num);
switch (sub_num1){// 0000011
case 0x0: instruction = LB; break;
case 0x1: instruction = LH; break;
case 0x2: instruction = LW; break;
case 0x4: instruction = LBU; break;
case 0x5: instruction = LHU; break;
default: throw error(__LINE__,num); break;
}
}//end 000011
}//end 00011
}//end 011
return instruction;
}
INSTRUCTION_TYPE instruction_type(INSTRUCTION instr){
if(instr>=ADD) return _R;
if(instr<=AUIPC) return _U;
if(instr==JAL) return _J;
if(instr>=BEQ&&instr<=BGEU) return _B;
if(instr>=SB&&instr<=SW) return _S;
return _I;
}
class CPU{
private:
uint32_t MEMORY[1<<16]={0};
uint32_t REGI[32]={0};//寄存器
uint32_t PC=0;//系统PC
uint64_t tick=0;//时钟
IF_IDs IF_ID;
ID_EXs ID_EX;
EX_MEMs EX_MEM;
MEM_WBs MEM_WB;
void lui(){//EX阶段运行
EX_MEM.to_WB = ID_EX.imm;
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.PC = ID_EX.PC+4;
}
void auipc(){
EX_MEM.to_WB = ID_EX.imm+ID_EX.rd;
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.PC = ID_EX.PC+4;
}
void jal(){
EX_MEM.to_WB = ID_EX.PC+4;
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
void beq(){
if(ID_EX.rs1==ID_EX.rs2){
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void bne(){
if(ID_EX.rs1!=ID_EX.rs2) {
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void blt(){
if((int)ID_EX.rs1< (int)ID_EX.rs2) {
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void bge(){
if((int)ID_EX.rs1>=(int)ID_EX.rs2) {
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void bltu(){
if(ID_EX.rs1< ID_EX.rs2) {
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void bgeu(){
if(ID_EX.rs1>=ID_EX.rs2) {
EX_MEM.PC = ID_EX.PC+ID_EX.imm;
}
else EX_MEM.PC = ID_EX.PC+4;
}
void jalr(){
EX_MEM.to_WB = ID_EX.PC+4;
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.PC = (ID_EX.imm+ID_EX.rs1)&(-2u);
}
void lb(){//在MEM阶段解决
char ch;
memcpy(&ch,(char*)MEMORY+EX_MEM.MEM_index,sizeof(char));
MEM_WB.to_WB = (uint32_t)ch;
MEM_WB.WB_index = EX_MEM.WB_index;
}
void lh(){//在MEM阶段解决
short ch;
memcpy(&ch,(char*)MEMORY+EX_MEM.MEM_index,sizeof(short));
EX_MEM.to_WB = (uint32_t)ch;
}
void lw(){//在MEM阶段解决
uint32_t ch;
memcpy(&ch,(char*)MEMORY+EX_MEM.MEM_index,sizeof(unsigned int));
EX_MEM.to_WB = (uint32_t)ch;
}
void lbu(){//在MEM阶段解决
unsigned char ch;
memcpy(&ch,(char*)MEMORY+EX_MEM.MEM_index,sizeof(unsigned char));
EX_MEM.to_WB = (uint32_t)ch;
}
void lhu(){//在MEM阶段解决
unsigned short ch;
memcpy(&ch,(char*)MEMORY+EX_MEM.MEM_index,sizeof(unsigned short));
EX_MEM.to_WB = (uint32_t)ch;
}
void addi(){//EX阶段解决
if(ID_EX.rd==10&&ID_EX.imm==0xFF)//结束标记
throw end(REGI[ID_EX.rd]&0xFFUL);
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1+ID_EX.imm;
EX_MEM.PC = ID_EX.PC+4;
}
void slti(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ((int)ID_EX.rs1<(int)ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
}
void sltiu(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (ID_EX.rs1<ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
}
void xori(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (ID_EX.rs1^ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
}
void ori(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (ID_EX.rs1|ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
}
void andi(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (ID_EX.rs1&ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
}
void slli(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1<<(ID_EX.imm&31UL);
EX_MEM.PC = ID_EX.PC+4;
}
void srli(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1>>(ID_EX.imm&31UL);
EX_MEM.PC = ID_EX.PC+4;
}
void srai(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (int) ID_EX.rs1>>(ID_EX.imm&31UL);
EX_MEM.PC = ID_EX.PC+4;
}
void sb(){//在MEM阶段解决
char ch=(char) EX_MEM.to_MEM;
memcpy((char*)MEMORY+EX_MEM.MEM_index,&ch,sizeof(char));
}
void sh(){
short ch=(unsigned short) EX_MEM.to_MEM;
memcpy((char*)MEMORY+EX_MEM.MEM_index,&ch,sizeof(unsigned short));
}
void sw(){
uint32_t ch=EX_MEM.to_MEM;
memcpy((char*)MEMORY+EX_MEM.MEM_index,&ch,sizeof(unsigned int));
}
void add(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1+ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void sub(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1-ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void sll(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1<<(ID_EX.rs2&31);
EX_MEM.PC = ID_EX.PC+4;
}//逻辑左移
void slt(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (int)ID_EX.rs1<(int)ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void sltu(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1<ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void _xor(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1^ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void srl(){//逻辑右移(空位补0)
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1>>(ID_EX.rs2&31UL);
EX_MEM.PC = ID_EX.PC+4;
}
void sra(){//算数右移(空位用最高位填充)
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = (int)(ID_EX.rs1)>>(ID_EX.rs2&31UL);
EX_MEM.PC = ID_EX.PC+4;
}
void _or(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1|ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
void _and(){
EX_MEM.WB_index = ID_EX.rd;
EX_MEM.to_WB = ID_EX.rs1&ID_EX.rs2;
EX_MEM.PC = ID_EX.PC+4;
}
uint32_t predictor(const ID_EXs& ID_EX){//预测NPC
return ID_EX.PC+4UL;
}
void read(uint32_t& num){
char ch=getchar();uint32_t x=0;
while(!is_num(ch)){ch=getchar();}
while(is_num(ch)){
ch = (ch<'A')?(ch-'0'):(ch-'A'+10);
x=(x<<4)+ch;ch=getchar();
}
num = x;
}
uint32_t read(){//把32位码转换成int
char ch[8];
ch[1] = getchar();
while(!is_num(ch[1])){ch[1]=getchar();}
ch[0] = getchar();getchar();
ch[3] = getchar();ch[2] = getchar();getchar();
ch[5] = getchar();ch[4] = getchar();getchar();
ch[7] = getchar();ch[6] = getchar();
unsigned int ans=0;
for(int i=0;i<8;i++){
if(ch[i]<'A') ch[i] = ch[i]-'0';
else ch[i] = ch[i]-'A'+10;
ans |= ((unsigned int)(ch[i]) << (i<<2) );
}
return ans;
}
void IF(){
IF_ID.raw_instruction=MEMORY[PC/4];
// printf("IF %s PC = 0x%x\n",name[decoder(IF_ID.raw_instruction)],PC);
IF_ID.PC=this->PC;//一开始的PC
PC+=4;
IF_ID.NOP=false;
}
void check_broadcast(uint32_t& rs){
// WB();
// MEM();
// WB();
// rs = REGI[rs];
// return;
//====================================不冒险,直接停=========================================
const uint32_t prev_rd1 = (EX_MEM.type!=_S && EX_MEM.type!=_B && !EX_MEM.NOP)?EX_MEM.WB_index:320;//还没MEM 修改WB的寄存器
const uint32_t prev_rd2 = (MEM_WB.type!=_S && MEM_WB.type!=_B && !MEM_WB.NOP)?MEM_WB.WB_index:320;//还没WB 修改WB的寄存器
uint32_t& prev_value1 = EX_MEM.to_WB;
uint32_t& prev_value2 = MEM_WB.to_WB;
if(rs==prev_rd1){
if(EX_MEM.instruction==LB||EX_MEM.instruction==LH||
EX_MEM.instruction==LBU||EX_MEM.instruction==LHU||EX_MEM.instruction==LW){
WB();MEM();
rs = (prev_rd1==0)?0:prev_value2;
}
else rs = (prev_rd1==0)?0:prev_value1;
}
else if(rs==prev_rd2){
rs = (prev_rd2==0)?0:prev_value2;
}
else rs=REGI[rs];
}
void ID(){
if(IF_ID.NOP) return;
else IF_ID.NOP=true;
const uint32_t& num=IF_ID.raw_instruction;//寄存器取指令
ID_EX.instruction=decoder(IF_ID.raw_instruction);//1
ID_EX.type=instruction_type(ID_EX.instruction);//2
ID_EX.PC=IF_ID.PC;//3
ID_EX.imm=0;//4
ID_EX.rd=ID_EX.rs1=ID_EX.rs2=0;//5 6 7
switch(ID_EX.type){//Fetch Register
case _U:
ID_EX.rd = (num>>7)&31u;
ID_EX.imm = (num & 0xFFFFF000UL);//不用移位
break;
case _J:
ID_EX.rd = (num>>7)&31u;
if ((num >> 31u) == 1u)
ID_EX.imm |= 0xFFF00000UL;
ID_EX.imm |= num & 0x000ff000UL;
ID_EX.imm |= ((num >> 20u) & 1u) << 11u;
ID_EX.imm |= ((num >> 21u) & 1023u) << 1u;
break;
case _B:
ID_EX.rs1 = (num>>15)&31u;
ID_EX.rs2 = (num>>20)&31u;
check_broadcast(ID_EX.rs1);
check_broadcast(ID_EX.rs2);
if ((num >> 31u) == 1u)
ID_EX.imm |= 0xfffff000;
ID_EX.imm |= ((num >> 7u) & 1u) << 11u;
ID_EX.imm |= ((num >> 25u) & 63u) << 5u;
ID_EX.imm |= ((num >> 8u) & 15u) << 1u;
break;
case _I:
ID_EX.rs1 = (num>>15)&31u;
ID_EX.rd = (num>>7)&31u;
check_broadcast(ID_EX.rs1);
if ((num >> 31u) == 1u)
ID_EX.imm |= 0xfffff800;
ID_EX.imm |= (num >> 20u) & 2047u;
break;
case _S:
ID_EX.rs1 = (num>>15)&31u;
ID_EX.rs2 = (num>>20)&31u;
check_broadcast(ID_EX.rs1);
check_broadcast(ID_EX.rs2);
if ((num >> 31u) == 0x1u)
ID_EX.imm |= 0xfffff800;
ID_EX.imm |= ((num >> 25u) & 63u) << 5u;
ID_EX.imm |= ((num >> 8u) & 15u) << 1u;
ID_EX.imm |= (num >> 7u) & 1u;
break;
case _R:
ID_EX.rs1 = (num>>15)&31u;
ID_EX.rs2 = (num>>20)&31u;
check_broadcast(ID_EX.rs1);
check_broadcast(ID_EX.rs2);
ID_EX.rd = (num>>7)&31u;
break;
}//判断type
// printf("ID %s PC = 0x%x rs1 = %d rs2 = %d\n",name[ID_EX.instruction],ID_EX.PC,ID_EX.rs1,ID_EX.rs2);
ID_EX.NPC = predictor(ID_EX);//分支预测8
ID_EX.NOP = false;//9
}
void EX(){
if(ID_EX.NOP) return;//是否为空指令
else ID_EX.NOP=true;//执行完就把指令清空
// printf("EX %s ",name[ID_EX.instruction]);
switch(ID_EX.instruction){
case LUI: lui(); break;
case AUIPC: auipc(); break;
case JAL: jal(); break;
case BEQ: beq(); break;
case BNE: bne(); break;
case BLT: blt(); break;
case BGE: bge(); break;
case BLTU: bltu(); break;
case BGEU: bgeu(); break;
case JALR: jalr(); break;
case LB: case LH: case LW: case LBU: case LHU:
EX_MEM.MEM_index = ID_EX.rs1+ID_EX.imm;//1 to_WB4
// printf("MEM_index(0x%x) = rs1(%d) + imm(%d)",EX_MEM.MEM_index,ID_EX.rs1,ID_EX.imm);
EX_MEM.WB_index = ID_EX.rd;//2
EX_MEM.PC = ID_EX.PC+4;//3
break;
case ADDI: addi(); break;//
case SLTI: slti(); break;
case SLTIU: sltiu(); break;
case XORI: xori(); break;
case ORI: ori(); break;
case ANDI: andi(); break;
case SLLI: slli(); break;
case SRLI: srli(); break;
case SRAI: srai(); break;
case SB: case SH: case SW:
EX_MEM.to_MEM = ID_EX.rs2;//5
EX_MEM.MEM_index = ID_EX.rs1+(int)ID_EX.imm;
// printf("MEM_index(0x%x) = rs1(%d) + imm(%d)",EX_MEM.MEM_index,ID_EX.rs1,ID_EX.imm);
EX_MEM.PC = ID_EX.PC+4;
break;
case ADD: add(); break;
case SUB: sub(); break;
case SLL: sll(); break;
case SLT: slt(); break;
case SLTU: sltu(); break;
case XOR: _xor(); break;
case SRL: srl(); break;
case SRA: sra(); break;
case OR: _or(); break;
case AND: _and(); break;
}
// printf("PC = 0x%x ",ID_EX.PC);
// if(ID_EX.type!=_S&&ID_EX.type!=_B)
// printf("%d(%s) imm = %d ",EX_MEM.to_WB,REGI_name[EX_MEM.WB_index],ID_EX.imm);
if(ID_EX.NPC!=EX_MEM.PC){
// puts("jump!!");
IF_ID.NOP=true;//停止ID
PC=EX_MEM.PC;
}//如果预测值不一样,那么暂停流水线
// else puts("");
EX_MEM.instruction=ID_EX.instruction;//6
EX_MEM.type=ID_EX.type;//7
EX_MEM.NOP=false;//8
}
void MEM(){
if(EX_MEM.NOP) return;
else EX_MEM.NOP=true;
// printf("MEM %s ",name[EX_MEM.instruction]);
if(EX_MEM.type == _I||EX_MEM.type == _S){//如果是I or S就执行
switch(EX_MEM.instruction){
case LB: lb();break;
case LH: lh();break;
case LW: lw();break;
case LBU: lbu();break;
case LHU: lhu();break;
case SB: sb();break;
case SH: sh();break;
case SW: sw();break;
}
// printf("MEM_index = 0x%x To_MEM = 0x%x To_WB = 0x%x\n",EX_MEM.MEM_index,EX_MEM.to_MEM,EX_MEM.to_WB);
}
// else puts("");
MEM_WB.type=EX_MEM.type;
MEM_WB.to_WB=EX_MEM.to_WB;
MEM_WB.WB_index=EX_MEM.WB_index;
MEM_WB.instruction=EX_MEM.instruction;
MEM_WB.NOP=false;
}
void WB(){
if(MEM_WB.NOP) return;
else MEM_WB.NOP=true;
if(MEM_WB.type==_S||MEM_WB.type==_B){
// printf("WB %s\n",name[MEM_WB.instruction]);
return;
}
REGI[MEM_WB.WB_index]=MEM_WB.to_WB;
REGI[0]=0;
// printf("WB %s %d(%s)\n",name[MEM_WB.instruction],MEM_WB.to_WB,REGI_name[MEM_WB.WB_index]);
}
void copy_into_MEM(){
uint32_t index=0UL;
flag1:
try{
while (true){
MEMORY[index/4]=read();
index+=4;
}
}
catch(move e){
read(index);
// printf("move to 0x%x\n",index);
goto flag1;
}
catch(end e){
// puts("successfully read!");
index=0;
}
catch(error e){
e.printerror();
goto flag1;
}
}
public:
void run(){
// puts("begin");
this->copy_into_MEM();
PC=0;
flag2:
try{
while(1){
WB();
MEM();
EX();
try{ID();}catch(...){}
IF();
// puts("========================");
}
}
catch(error e){
e.printerror();
printf("PC = 0x%x\n",PC);
}
catch(end e){
printf("%d\n",e.num);
}
}
};
int main(){
// freopen(".\\testcases\\hanoi.data","r",stdin);
CPU my_CPU;
my_CPU.run();
return 0;
} | [
"1773701277@qq.com"
] | 1773701277@qq.com |
06daca14c97f05c717a1d028f4b774bca88e7ceb | 2abc2378ba47e2561f08fc27beb95c039531632b | /TLibToolTest/terminal_app.h | f20747e39bec40d172e601ac80c453c1f5378ebf | [] | no_license | spartawwy/Dev_lib | a877eb5f991625c0b221f2f2f995ad24b45ca17f | c2b790d8f4ab15d5f709274b5ef1f4189adf603b | refs/heads/master | 2021-10-08T06:44:02.920691 | 2018-12-09T16:22:02 | 2018-12-09T16:22:02 | 111,189,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | h | #ifndef TERMINAL_APP_H_
#define TERMINAL_APP_H_
#include <TLib/tool/tsystem_server_client_appbase.h>
#include "TLib/core/tsystem_connection.h"
using namespace TSystem;
class TerminalApp : public TSystem::ServerClientAppBase
{
public:
TerminalApp();
virtual ~TerminalApp(){}
bool Initiate();
void Shutdown();
private:
virtual void HandleNodeHandShake(communication::Connection* p, const Message& msg) override;
virtual void HandleNodeDisconnect(std::shared_ptr<communication::Connection>& pconn
, const TError& te) override;
TSystem::ClientSocket client_socket_;
TSystem::ClientSocket msg_relay_socket_;
// sync
//TSystem::MessageHandlerGroup msg_handlers_;
};
#endif // TERMINAL_APP_H_ | [
"32713201+spartawwy@users.noreply.github.com"
] | 32713201+spartawwy@users.noreply.github.com |
7cf9496159783e85008b7baea156633470194b55 | 460062f73dc03d1b668851fe5d33881e10b95504 | /ringct/rctSigs.cpp | 6e304b0b50bb08c88b953e70f85707bf2a33eb56 | [] | no_license | Bitcoin-Confidential/bc-core-custom | 24d8e86b50418988cac96c07a7c6c85231f6d5d8 | 00ae1eb2496262432e12dda10335793d04e372b7 | refs/heads/master | 2020-06-23T18:23:09.525440 | 2019-09-05T01:47:55 | 2019-09-05T01:47:55 | 198,713,705 | 0 | 0 | null | 2019-07-24T21:44:13 | 2019-07-24T21:44:12 | null | UTF-8 | C++ | false | false | 51,609 | cpp | // Copyright (c) 2016, Monero Research Labs
//
// Author: Shen Noether <shen.noether@gmx.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.
//
// 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.
#include "misc_log_ex.h"
// #include "common/perf_timer.h"
#include "common/threadpool.h"
#include "common/util.h"
#include "rctSigs.h"
#include "bulletproofs.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
using namespace crypto;
using namespace std;
#undef BC_DEFAULT_LOG_CATEGORY
#define BC_DEFAULT_LOG_CATEGORY "ringct"
#define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}}
namespace rct {
Bulletproof proveRangeBulletproof(keyV &C, keyV &masks, const std::vector<uint64_t> &amounts, const std::vector<key> &sk)
{
CHECK_AND_ASSERT_THROW_MES(amounts.size() == sk.size(), "Invalid amounts/sk sizes");
masks.resize(amounts.size());
for (size_t i = 0; i < masks.size(); ++i)
masks[i] = genCommitmentMask(sk[i]);
Bulletproof proof = bulletproof_PROVE(amounts, masks);
CHECK_AND_ASSERT_THROW_MES(proof.V.size() == amounts.size(), "V does not have the expected size");
C = proof.V;
return proof;
}
bool verBulletproof(const Bulletproof &proof)
{
try { return bulletproof_VERIFY(proof); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
bool verBulletproof(const std::vector<const Bulletproof*> &proofs)
{
try { return bulletproof_VERIFY(proofs); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
//Borromean (c.f. gmax/andytoshi's paper)
boroSig genBorromean(const key64 x, const key64 P1, const key64 P2, const bits indices) {
key64 L[2], alpha;
key c;
int naught = 0, prime = 0, ii = 0, jj=0;
boroSig bb;
for (ii = 0 ; ii < 64 ; ii++) {
naught = indices[ii]; prime = (indices[ii] + 1) % 2;
skGen(alpha[ii]);
scalarmultBase(L[naught][ii], alpha[ii]);
if (naught == 0) {
skGen(bb.s1[ii]);
c = hash_to_scalar(L[naught][ii]);
addKeys2(L[prime][ii], bb.s1[ii], c, P2[ii]);
}
}
bb.ee = hash_to_scalar(L[1]); //or L[1]..
key LL, cc;
for (jj = 0 ; jj < 64 ; jj++) {
if (!indices[jj]) {
sc_mulsub(bb.s0[jj].bytes, x[jj].bytes, bb.ee.bytes, alpha[jj].bytes);
} else {
skGen(bb.s0[jj]);
addKeys2(LL, bb.s0[jj], bb.ee, P1[jj]); //different L0
cc = hash_to_scalar(LL);
sc_mulsub(bb.s1[jj].bytes, x[jj].bytes, cc.bytes, alpha[jj].bytes);
}
}
return bb;
}
//see above.
bool verifyBorromean(const boroSig &bb, const ge_p3 P1[64], const ge_p3 P2[64]) {
key64 Lv1; key chash, LL;
int ii = 0;
ge_p2 p2;
for (ii = 0 ; ii < 64 ; ii++) {
// equivalent of: addKeys2(LL, bb.s0[ii], bb.ee, P1[ii]);
ge_double_scalarmult_base_vartime(&p2, bb.ee.bytes, &P1[ii], bb.s0[ii].bytes);
ge_tobytes(LL.bytes, &p2);
chash = hash_to_scalar(LL);
// equivalent of: addKeys2(Lv1[ii], bb.s1[ii], chash, P2[ii]);
ge_double_scalarmult_base_vartime(&p2, chash.bytes, &P2[ii], bb.s1[ii].bytes);
ge_tobytes(Lv1[ii].bytes, &p2);
}
key eeComputed = hash_to_scalar(Lv1); //hash function fine
return equalKeys(eeComputed, bb.ee);
}
bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) {
ge_p3 P1_p3[64], P2_p3[64];
for (size_t i = 0 ; i < 64 ; ++i) {
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed");
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed");
}
return verifyBorromean(bb, P1_p3, P2_p3);
}
//Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures)
//This is a just slghtly more efficient version than the ones described below
//(will be explained in more detail in Ring Multisig paper
//These are aka MG signatutes in earlier drafts of the ring ct paper
// c.f. https://eprint.iacr.org/2015/1098 section 2.
// Gen creates a signature which proves that for some column in the keymatrix "pk"
// the signer knows a secret key for each row in that column
// Ver verifies that the MG sig was created correctly
mgSig MLSAG_Gen(const key &message, const keyM & pk, const keyV & xx, const multisig_kLRki *kLRki, key *mscout, const unsigned int index, size_t dsRows, hw::device &hwdev) {
mgSig rv;
size_t cols = pk.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 2, "Error! What is c if cols = 1!");
CHECK_AND_ASSERT_THROW_MES(index < cols, "Index out of range");
size_t rows = pk[0].size();
CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pk");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_THROW_MES(pk[i].size() == rows, "pk is not rectangular");
}
CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, "Bad xx size");
CHECK_AND_ASSERT_THROW_MES(dsRows <= rows, "Bad dsRows size");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
CHECK_AND_ASSERT_THROW_MES(!kLRki || dsRows == 1, "Multisig requires exactly 1 dsRows");
size_t i = 0, j = 0, ii = 0;
key c, c_old, L, R, Hi;
sc_0(c_old.bytes);
vector<geDsmp> Ip(dsRows);
rv.II = keyV(dsRows);
keyV alpha(rows);
keyV aG(rows);
rv.ss = keyM(cols, aG);
keyV aHP(dsRows);
keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows));
toHash[0] = message;
DP("here1");
for (i = 0; i < dsRows; i++) {
toHash[3 * i + 1] = pk[index][i];
if (kLRki) {
// multisig
alpha[i] = kLRki->k;
toHash[3 * i + 2] = kLRki->L;
toHash[3 * i + 3] = kLRki->R;
rv.II[i] = kLRki->ki;
}
else {
Hi = hashToPoint(pk[index][i]);
hwdev.mlsag_prepare(Hi, xx[i], alpha[i] , aG[i] , aHP[i] , rv.II[i]);
toHash[3 * i + 2] = aG[i];
toHash[3 * i + 3] = aHP[i];
}
precomp(Ip[i].k, rv.II[i]);
}
size_t ndsRows = 3 * dsRows; //non Double Spendable Rows (see identity chains paper)
for (i = dsRows, ii = 0 ; i < rows ; i++, ii++) {
skpkGen(alpha[i], aG[i]); //need to save alphas for later..
toHash[ndsRows + 2 * ii + 1] = pk[index][i];
toHash[ndsRows + 2 * ii + 2] = aG[i];
}
hwdev.mlsag_hash(toHash, c_old);
i = (index + 1) % cols;
if (i == 0) {
copy(rv.cc, c_old);
}
while (i != index) {
rv.ss[i] = skvGen(rows);
sc_0(c.bytes);
for (j = 0; j < dsRows; j++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
hashToPoint(Hi, pk[i][j]);
addKeys3(R, rv.ss[i][j], Hi, c_old, Ip[j].k);
toHash[3 * j + 1] = pk[i][j];
toHash[3 * j + 2] = L;
toHash[3 * j + 3] = R;
}
for (j = dsRows, ii = 0; j < rows; j++, ii++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
toHash[ndsRows + 2 * ii + 1] = pk[i][j];
toHash[ndsRows + 2 * ii + 2] = L;
}
hwdev.mlsag_hash(toHash, c);
copy(c_old, c);
i = (i + 1) % cols;
if (i == 0) {
copy(rv.cc, c_old);
}
}
hwdev.mlsag_sign(c, xx, alpha, rows, dsRows, rv.ss[index]);
if (mscout)
*mscout = c;
return rv;
}
//Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures)
//This is a just slghtly more efficient version than the ones described below
//(will be explained in more detail in Ring Multisig paper
//These are aka MG signatutes in earlier drafts of the ring ct paper
// c.f. https://eprint.iacr.org/2015/1098 section 2.
// Gen creates a signature which proves that for some column in the keymatrix "pk"
// the signer knows a secret key for each row in that column
// Ver verifies that the MG sig was created correctly
bool MLSAG_Ver(const key &message, const keyM & pk, const mgSig & rv, size_t dsRows) {
size_t cols = pk.size();
CHECK_AND_ASSERT_MES(cols >= 2, false, "Error! What is c if cols = 1!");
size_t rows = pk[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pk");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pk[i].size() == rows, false, "pk is not rectangular");
}
CHECK_AND_ASSERT_MES(rv.II.size() == dsRows, false, "Bad II size");
CHECK_AND_ASSERT_MES(rv.ss.size() == cols, false, "Bad rv.ss size");
for (size_t i = 0; i < cols; ++i) {
CHECK_AND_ASSERT_MES(rv.ss[i].size() == rows, false, "rv.ss is not rectangular");
}
CHECK_AND_ASSERT_MES(dsRows <= rows, false, "Bad dsRows value");
for (size_t i = 0; i < rv.ss.size(); ++i)
for (size_t j = 0; j < rv.ss[i].size(); ++j)
CHECK_AND_ASSERT_MES(sc_check(rv.ss[i][j].bytes) == 0, false, "Bad ss slot");
CHECK_AND_ASSERT_MES(sc_check(rv.cc.bytes) == 0, false, "Bad cc");
size_t i = 0, j = 0, ii = 0;
key c, L, R, Hi;
key c_old = copy(rv.cc);
vector<geDsmp> Ip(dsRows);
for (i = 0 ; i < dsRows ; i++) {
precomp(Ip[i].k, rv.II[i]);
}
size_t ndsRows = 3 * dsRows; //non Double Spendable Rows (see identity chains paper
keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows));
toHash[0] = message;
i = 0;
while (i < cols) {
sc_0(c.bytes);
for (j = 0; j < dsRows; j++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
hashToPoint(Hi, pk[i][j]);
CHECK_AND_ASSERT_MES(!(Hi == rct::identity()), false, "Data hashed to point at infinity");
addKeys3(R, rv.ss[i][j], Hi, c_old, Ip[j].k);
toHash[3 * j + 1] = pk[i][j];
toHash[3 * j + 2] = L;
toHash[3 * j + 3] = R;
}
for (j = dsRows, ii = 0 ; j < rows ; j++, ii++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
toHash[ndsRows + 2 * ii + 1] = pk[i][j];
toHash[ndsRows + 2 * ii + 2] = L;
}
c = hash_to_scalar(toHash);
copy(c_old, c);
i = (i + 1);
}
sc_sub(c.bytes, c_old.bytes, rv.cc.bytes);
return sc_isnonzero(c.bytes) == 0;
}
//proveRange and verRange
//proveRange gives C, and mask such that \sumCi = C
// c.f. https://eprint.iacr.org/2015/1098 section 5.1
// and Ci is a commitment to either 0 or 2^i, i=0,...,63
// thus this proves that "amount" is in [0, 2^64]
// mask is a such that C = aG + bH, and b = amount
//verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i
rangeSig proveRange(key & C, key & mask, const xmr_amount & amount) {
sc_0(mask.bytes);
identity(C);
bits b;
d2b(b, amount);
rangeSig sig;
key64 ai;
key64 CiH;
int i = 0;
for (i = 0; i < ATOMS; i++) {
skGen(ai[i]);
if (b[i] == 0) {
scalarmultBase(sig.Ci[i], ai[i]);
}
if (b[i] == 1) {
addKeys1(sig.Ci[i], ai[i], H2[i]);
}
subKeys(CiH[i], sig.Ci[i], H2[i]);
sc_add(mask.bytes, mask.bytes, ai[i].bytes);
addKeys(C, C, sig.Ci[i]);
}
sig.asig = genBorromean(ai, sig.Ci, CiH, b);
return sig;
}
//proveRange and verRange
//proveRange gives C, and mask such that \sumCi = C
// c.f. https://eprint.iacr.org/2015/1098 section 5.1
// and Ci is a commitment to either 0 or 2^i, i=0,...,63
// thus this proves that "amount" is in [0, 2^64]
// mask is a such that C = aG + bH, and b = amount
//verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i
bool verRange(const key & C, const rangeSig & as) {
try
{
// PERF_TIMER(verRange);
ge_p3 CiH[64], asCi[64];
int i = 0;
ge_p3 Ctmp_p3 = ge_p3_identity;
for (i = 0; i < 64; i++) {
// faster equivalent of:
// subKeys(CiH[i], as.Ci[i], H2[i]);
// addKeys(Ctmp, Ctmp, as.Ci[i]);
ge_cached cached;
ge_p3 p3;
ge_p1p1 p1;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, H2[i].bytes) == 0, false, "point conv failed");
ge_p3_to_cached(&cached, &p3);
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) == 0, false, "point conv failed");
ge_sub(&p1, &asCi[i], &cached);
ge_p3_to_cached(&cached, &asCi[i]);
ge_p1p1_to_p3(&CiH[i], &p1);
ge_add(&p1, &Ctmp_p3, &cached);
ge_p1p1_to_p3(&Ctmp_p3, &p1);
}
key Ctmp;
ge_p3_tobytes(Ctmp.bytes, &Ctmp_p3);
if (!equalKeys(C, Ctmp))
return false;
if (!verifyBorromean(as.asig, asCi, CiH))
return false;
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
key get_pre_mlsag_hash(const rctSig &rv, hw::device &hwdev)
{
keyV hashes;
hashes.reserve(3);
hashes.push_back(rv.message);
crypto::hash h;
std::stringstream ss;
binary_archive<true> ba(ss);
CHECK_AND_ASSERT_THROW_MES(!rv.mixRing.empty(), "Empty mixRing");
const size_t inputs = is_rct_simple(rv.type) ? rv.mixRing.size() : rv.mixRing[0].size();
const size_t outputs = rv.ecdhInfo.size();
key prehash;
CHECK_AND_ASSERT_THROW_MES(const_cast<rctSig&>(rv).serialize_rctsig_base(ba, inputs, outputs),
"Failed to serialize rctSigBase");
cryptonote::get_blob_hash(ss.str(), h);
hashes.push_back(hash2rct(h));
keyV kv;
if (rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2)
{
kv.reserve((6*2+9) * rv.p.bulletproofs.size());
for (const auto &p: rv.p.bulletproofs)
{
// V are not hashed as they're expanded from outPk.mask
// (and thus hashed as part of rctSigBase above)
kv.push_back(p.A);
kv.push_back(p.S);
kv.push_back(p.T1);
kv.push_back(p.T2);
kv.push_back(p.taux);
kv.push_back(p.mu);
for (size_t n = 0; n < p.L.size(); ++n)
kv.push_back(p.L[n]);
for (size_t n = 0; n < p.R.size(); ++n)
kv.push_back(p.R[n]);
kv.push_back(p.a);
kv.push_back(p.b);
kv.push_back(p.t);
}
}
else
{
kv.reserve((64*3+1) * rv.p.rangeSigs.size());
for (const auto &r: rv.p.rangeSigs)
{
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s0[n]);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s1[n]);
kv.push_back(r.asig.ee);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.Ci[n]);
}
}
hashes.push_back(cn_fast_hash(kv));
hwdev.mlsag_prehash(ss.str(), inputs, outputs, hashes, rv.outPk, prehash);
return prehash;
}
//Ring-ct MG sigs
//Prove:
// c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10.
// This does the MG sig on the "dest" part of the given key matrix, and
// the last row is the sum of input commitments from that column - sum output commitments
// this shows that sum inputs = sum outputs
//Ver:
// verifies the above sig is created corretly
mgSig proveRctMG(const key &message, const ctkeyM & pubs, const ctkeyV & inSk, const ctkeyV &outSk, const ctkeyV & outPk, const multisig_kLRki *kLRki, key *mscout, unsigned int index, key txnFeeKey, hw::device &hwdev) {
mgSig mg;
//setup vars
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
size_t rows = pubs[0].size();
CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pubs");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_THROW_MES(pubs[i].size() == rows, "pubs is not rectangular");
}
CHECK_AND_ASSERT_THROW_MES(inSk.size() == rows, "Bad inSk size");
CHECK_AND_ASSERT_THROW_MES(outSk.size() == outPk.size(), "Bad outSk/outPk size");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV sk(rows + 1);
keyV tmp(rows + 1);
size_t i = 0, j = 0;
for (i = 0; i < rows + 1; i++) {
sc_0(sk[i].bytes);
identity(tmp[i]);
}
keyM M(cols, tmp);
//create the matrix to mg sig
for (i = 0; i < cols; i++) {
M[i][rows] = identity();
for (j = 0; j < rows; j++) {
M[i][j] = pubs[i][j].dest;
addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add input commitments in last row
}
}
sc_0(sk[rows].bytes);
for (j = 0; j < rows; j++) {
sk[j] = copy(inSk[j].dest);
sc_add(sk[rows].bytes, sk[rows].bytes, inSk[j].mask.bytes); //add masks in last row
}
for (i = 0; i < cols; i++) {
for (size_t j = 0; j < outPk.size(); j++) {
subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row
}
//subtract txn fee output in last row
subKeys(M[i][rows], M[i][rows], txnFeeKey);
}
for (size_t j = 0; j < outPk.size(); j++) {
sc_sub(sk[rows].bytes, sk[rows].bytes, outSk[j].mask.bytes); //subtract output masks in last row..
}
mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev);
memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
//Ring-ct MG sigs Simple
// Simple version for when we assume only
// post rct inputs
// here pubs is a vector of (P, C) length mixin
// inSk is x, a_in corresponding to signing index
// a_out, Cout is for the output commitment
// index is the signing index..
mgSig proveRctMGSimple(const key &message, const ctkeyV & pubs, const ctkey & inSk, const key &a , const key &Cout, const multisig_kLRki *kLRki, key *mscout, unsigned int index, hw::device &hwdev) {
mgSig mg;
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV tmp(rows + 1);
keyV sk(rows + 1);
size_t i;
keyM M(cols, tmp);
sk[0] = copy(inSk.dest);
sc_sub(sk[1].bytes, inSk.mask.bytes, a.bytes);
for (i = 0; i < cols; i++) {
M[i][0] = pubs[i].dest;
subKeys(M[i][1], pubs[i].mask, Cout);
}
mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev);
memwipe(&sk[0], sizeof(key));
return result;
}
//Ring-ct MG sigs
//Prove:
// c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10.
// This does the MG sig on the "dest" part of the given key matrix, and
// the last row is the sum of input commitments from that column - sum output commitments
// this shows that sum inputs = sum outputs
//Ver:
// verifies the above sig is created corretly
bool verRctMG(const mgSig &mg, const ctkeyM & pubs, const ctkeyV & outPk, key txnFeeKey, const key &message) {
// PERF_TIMER(verRctMG);
//setup vars
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
size_t rows = pubs[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pubs");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pubs[i].size() == rows, false, "pubs is not rectangular");
}
keyV tmp(rows + 1);
size_t i = 0, j = 0;
for (i = 0; i < rows + 1; i++) {
identity(tmp[i]);
}
keyM M(cols, tmp);
//create the matrix to mg sig
for (j = 0; j < rows; j++) {
for (i = 0; i < cols; i++) {
M[i][j] = pubs[i][j].dest;
addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add Ci in last row
}
}
for (i = 0; i < cols; i++) {
for (j = 0; j < outPk.size(); j++) {
subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row
}
//subtract txn fee output in last row
subKeys(M[i][rows], M[i][rows], txnFeeKey);
}
return MLSAG_Ver(message, M, mg, rows);
}
//Ring-ct Simple MG sigs
//Ver:
//This does a simplified version, assuming only post Rct
//inputs
bool verRctMGSimple(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C) {
try
{
// PERF_TIMER(verRctMGSimple);
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
keyV tmp(rows + 1);
size_t i;
keyM M(cols, tmp);
//create the matrix to mg sig
for (i = 0; i < cols; i++) {
M[i][0] = pubs[i].dest;
subKeys(M[i][1], pubs[i].mask, C);
}
//DP(C);
return MLSAG_Ver(message, M, mg, rows);
}
catch (...) { return false; }
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
void getKeyFromBlockchain(ctkey & a, size_t reference_index) {
a.mask = pkGen();
a.dest = pkGen();
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" + 1 columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
tuple<ctkeyM, xmr_amount> populateFromBlockchain(ctkeyV inPk, int mixin) {
int rows = inPk.size();
ctkeyM rv(mixin + 1, inPk);
int index = randXmrAmount(mixin);
int i = 0, j = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
for (j = 0; j < rows; j++) {
getKeyFromBlockchain(rv[i][j], (size_t)randXmrAmount);
}
}
}
return make_tuple(rv, index);
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
xmr_amount populateFromBlockchainSimple(ctkeyV & mixRing, const ctkey & inPk, int mixin) {
int index = randXmrAmount(mixin);
int i = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
getKeyFromBlockchain(mixRing[i], (size_t)randXmrAmount(1000));
} else {
mixRing[i] = inPk;
}
}
return index;
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
// Note: For txn fees, the last index in the amounts vector should contain that
// Thus the amounts vector will be "one" longer than the destinations vectort
rctSig genRct(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> & amounts, const ctkeyM &mixRing, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, unsigned int index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) {
CHECK_AND_ASSERT_THROW_MES(amounts.size() == destinations.size() || amounts.size() == destinations.size() + 1, "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations");
CHECK_AND_ASSERT_THROW_MES(index < mixRing.size(), "Bad index into mixRing");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(mixRing[n].size() == inSk.size(), "Bad mixRing size");
}
CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present");
rctSig rv;
rv.type = RCTTypeFull;
rv.message = message;
rv.outPk.resize(destinations.size());
rv.p.rangeSigs.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i = 0;
keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outPk[i].dest = copy(destinations[i]);
//compute range proof
rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, amounts[i]);
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof");
#endif
//mask amount and mask
rv.ecdhInfo[i].mask = copy(outSk[i].mask);
rv.ecdhInfo[i].amount = d2h(amounts[i]);
hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2);
}
//set txn fee
if (amounts.size() > destinations.size())
{
rv.txnFee = amounts[destinations.size()];
}
else
{
rv.txnFee = 0;
}
key txnFeeKey = scalarmultH(d2h(rv.txnFee));
rv.mixRing = mixRing;
if (msout)
msout->c.resize(1);
rv.p.MGs.push_back(proveRctMG(get_pre_mlsag_hash(rv, hwdev), rv.mixRing, inSk, outSk, rv.outPk, kLRki, msout ? &msout->c[0] : NULL, index, txnFeeKey,hwdev));
return rv;
}
rctSig genRct(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> & amounts, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, const int mixin, const RCTConfig &rct_config, hw::device &hwdev) {
unsigned int index;
ctkeyM mixRing;
ctkeyV outSk;
tie(mixRing, index) = populateFromBlockchain(inPk, mixin);
return genRct(message, inSk, destinations, amounts, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev);
}
//RCT simple
//for post-rct only
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, xmr_amount txnFee, const ctkeyM & mixRing, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, const std::vector<unsigned int> & index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) {
const bool bulletproof = rct_config.range_proof_type != RangeProofBorromean;
CHECK_AND_ASSERT_THROW_MES(inamounts.size() > 0, "Empty inamounts");
CHECK_AND_ASSERT_THROW_MES(inamounts.size() == inSk.size(), "Different number of inamounts/inSk");
CHECK_AND_ASSERT_THROW_MES(outamounts.size() == destinations.size(), "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations");
CHECK_AND_ASSERT_THROW_MES(index.size() == inSk.size(), "Different number of index/inSk");
CHECK_AND_ASSERT_THROW_MES(mixRing.size() == inSk.size(), "Different number of mixRing/inSk");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(index[n] < mixRing[n].size(), "Bad index into mixRing");
}
CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present");
if (kLRki && msout) {
CHECK_AND_ASSERT_THROW_MES(kLRki->size() == inamounts.size(), "Mismatched kLRki/inamounts sizes");
}
rctSig rv;
rv.type = bulletproof ? (rct_config.bp_version == 0 || rct_config.bp_version >= 2 ? RCTTypeBulletproof2 : RCTTypeBulletproof) : RCTTypeSimple;
rv.message = message;
rv.outPk.resize(destinations.size());
if (!bulletproof)
rv.p.rangeSigs.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i;
keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outPk[i].dest = copy(destinations[i]);
//compute range proof
if (!bulletproof)
rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, outamounts[i]);
#ifdef DBG
if (!bulletproof)
CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof");
#endif
}
rv.p.bulletproofs.clear();
if (bulletproof)
{
std::vector<uint64_t> proof_amounts;
size_t n_amounts = outamounts.size();
size_t amounts_proved = 0;
if (rct_config.range_proof_type == RangeProofPaddedBulletproof)
{
rct::keyV C, masks;
const std::vector<key> keys(amount_keys.begin(), amount_keys.end());
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, outamounts, keys));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
for (i = 0; i < outamounts.size(); ++i)
{
rv.outPk[i].mask = rct::scalarmult8(C[i]);
outSk[i].mask = masks[i];
}
}
else while (amounts_proved < n_amounts)
{
size_t batch_size = 1;
if (rct_config.range_proof_type == RangeProofMultiOutputBulletproof)
while (batch_size * 2 + amounts_proved <= n_amounts && batch_size * 2 <= BULLETPROOF_MAX_OUTPUTS)
batch_size *= 2;
rct::keyV C, masks;
std::vector<uint64_t> batch_amounts(batch_size);
for (i = 0; i < batch_size; ++i)
batch_amounts[i] = outamounts[i + amounts_proved];
std::vector<key> keys(batch_size);
for (size_t j = 0; j < batch_size; ++j)
keys[j] = amount_keys[amounts_proved + j];
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, batch_amounts, keys));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
for (i = 0; i < batch_size; ++i)
{
rv.outPk[i + amounts_proved].mask = rct::scalarmult8(C[i]);
outSk[i + amounts_proved].mask = masks[i];
}
amounts_proved += batch_size;
}
}
key sumout = zero();
for (i = 0; i < outSk.size(); ++i)
{
sc_add(sumout.bytes, outSk[i].mask.bytes, sumout.bytes);
//mask amount and mask
rv.ecdhInfo[i].mask = copy(outSk[i].mask);
rv.ecdhInfo[i].amount = d2h(outamounts[i]);
hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2);
}
//set txn fee
rv.txnFee = txnFee;
// TODO: unused ??
// key txnFeeKey = scalarmultH(d2h(rv.txnFee));
rv.mixRing = mixRing;
keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
pseudoOuts.resize(inamounts.size());
rv.p.MGs.resize(inamounts.size());
key sumpouts = zero(); //sum pseudoOut masks
keyV a(inamounts.size());
for (i = 0 ; i < inamounts.size() - 1; i++) {
skGen(a[i]);
sc_add(sumpouts.bytes, a[i].bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
}
rv.mixRing = mixRing;
sc_sub(a[i].bytes, sumout.bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
DP(pseudoOuts[i]);
key full_message = get_pre_mlsag_hash(rv,hwdev);
if (msout)
msout->c.resize(inamounts.size());
for (i = 0 ; i < inamounts.size(); i++) {
rv.p.MGs[i] = proveRctMGSimple(full_message, rv.mixRing[i], inSk[i], a[i], pseudoOuts[i], kLRki ? &(*kLRki)[i]: NULL, msout ? &msout->c[i] : NULL, index[i], hwdev);
}
return rv;
}
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, xmr_amount txnFee, unsigned int mixin, const RCTConfig &rct_config, hw::device &hwdev) {
std::vector<unsigned int> index;
index.resize(inPk.size());
ctkeyM mixRing;
ctkeyV outSk;
mixRing.resize(inPk.size());
for (size_t i = 0; i < inPk.size(); ++i) {
mixRing[i].resize(mixin+1);
index[i] = populateFromBlockchainSimple(mixRing[i], inPk[i], mixin);
}
return genRctSimple(message, inSk, destinations, inamounts, outamounts, txnFee, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev);
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
bool verRct(const rctSig & rv, bool semantics) {
// PERF_TIMER(verRct);
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "verRct called on non-full rctSig");
if (semantics)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "full rctSig has not one MG");
}
else
{
// semantics check is early, we don't have the MGs resolved yet
}
// some rct ops can throw
try
{
if (semantics) {
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
std::deque<bool> results(rv.outPk.size(), false);
DP("range proofs verified?");
for (size_t i = 0; i < rv.outPk.size(); i++)
tpool.submit(&waiter, [&, i] { results[i] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
}
if (!semantics) {
//compute txn fee
key txnFeeKey = scalarmultH(d2h(rv.txnFee));
bool mgVerd = verRctMG(rv.p.MGs[0], rv.mixRing, rv.outPk, txnFeeKey, get_pre_mlsag_hash(rv, hw::get_device("default")));
DP("mg sig verified?");
DP(mgVerd);
if (!mgVerd) {
LOG_PRINT_L1("MG signature verification failed");
return false;
}
}
return true;
}
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRct: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRct, but not an actual exception");
return false;
}
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctSemanticsSimple(const std::vector<const rctSig*> & rvv) {
try
{
// PERF_TIMER(verRctSemanticsSimple);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
std::deque<bool> results;
std::vector<const Bulletproof*> proofs;
size_t max_non_bp_proofs = 0, offset = 0;
for (const rctSig *rvp: rvv)
{
CHECK_AND_ASSERT_MES(rvp, false, "rctSig pointer is NULL");
const rctSig &rv = *rvp;
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2,
false, "verRctSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
if (bulletproof)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == n_bulletproof_amounts(rv.p.bulletproofs), false, "Mismatched sizes of outPk and bulletproofs");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.MGs");
CHECK_AND_ASSERT_MES(rv.pseudoOuts.empty(), false, "rv.pseudoOuts is not empty");
}
else
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.pseudoOuts and rv.p.MGs");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.empty(), false, "rv.p.pseudoOuts is not empty");
}
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
if (!bulletproof)
max_non_bp_proofs += rv.p.rangeSigs.size();
}
results.resize(max_non_bp_proofs);
for (const rctSig *rvp: rvv)
{
const rctSig &rv = *rvp;
const bool bulletproof = is_rct_bulletproof(rv.type);
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
rct::keyV masks(rv.outPk.size());
for (size_t i = 0; i < rv.outPk.size(); i++) {
masks[i] = rv.outPk[i].mask;
}
key sumOutpks = addKeys(masks);
DP(sumOutpks);
const key txnFeeKey = scalarmultH(d2h(rv.txnFee));
addKeys(sumOutpks, txnFeeKey, sumOutpks);
key sumPseudoOuts = addKeys(pseudoOuts);
DP(sumPseudoOuts);
//check pseudoOuts vs Outs..
if (!equalKeys(sumPseudoOuts, sumOutpks)) {
LOG_PRINT_L1("Sum check failed");
return false;
}
if (bulletproof)
{
for (size_t i = 0; i < rv.p.bulletproofs.size(); i++)
proofs.push_back(&rv.p.bulletproofs[i]);
}
else
{
for (size_t i = 0; i < rv.p.rangeSigs.size(); i++)
tpool.submit(&waiter, [&, i, offset] { results[i+offset] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
offset += rv.p.rangeSigs.size();
}
}
if (!proofs.empty() && !verBulletproof(proofs))
{
LOG_PRINT_L1("Aggregate range proof verified failed");
return false;
}
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple, but not an actual exception");
return false;
}
}
bool verRctSemanticsSimple(const rctSig & rv)
{
return verRctSemanticsSimple(std::vector<const rctSig*>(1, &rv));
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctNonSemanticsSimple(const rctSig & rv) {
try
{
// PERF_TIMER(verRctNonSemanticsSimple);
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2,
false, "verRctNonSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
// semantics check is early, and mixRing/MGs aren't resolved yet
if (bulletproof)
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.p.pseudoOuts and mixRing");
else
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.pseudoOuts and mixRing");
const size_t threads = std::max(rv.outPk.size(), rv.mixRing.size());
std::deque<bool> results(threads);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
const key message = get_pre_mlsag_hash(rv, hw::get_device("default"));
results.clear();
results.resize(rv.mixRing.size());
for (size_t i = 0 ; i < rv.mixRing.size() ; i++) {
tpool.submit(&waiter, [&, i] {
results[i] = verRctMGSimple(message, rv.p.MGs[i], rv.mixRing[i], pseudoOuts[i]);
});
}
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("verRctMGSimple failed for input " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple, but not an actual exception");
return false;
}
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, key & mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "decodeRct called on non-full rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRct(rv, sk, i, mask, hwdev);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, key &mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2, false, "decodeRct called on non simple rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRctSimple(rv, sk, i, mask, hwdev);
}
bool signMultisig(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull || rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2,
false, "unsupported rct type");
CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes");
CHECK_AND_ASSERT_MES(k.size() == rv.p.MGs.size(), false, "Mismatched k/MGs size");
CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size");
if (rv.type == RCTTypeFull)
{
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "MGs not a single element");
}
for (size_t n = 0; n < indices.size(); ++n) {
CHECK_AND_ASSERT_MES(indices[n] < rv.p.MGs[n].ss.size(), false, "Index out of range");
CHECK_AND_ASSERT_MES(!rv.p.MGs[n].ss[indices[n]].empty(), false, "empty ss line");
}
for (size_t n = 0; n < indices.size(); ++n) {
rct::key diff;
sc_mulsub(diff.bytes, msout.c[n].bytes, secret_key.bytes, k[n].bytes);
sc_add(rv.p.MGs[n].ss[indices[n]][0].bytes, rv.p.MGs[n].ss[indices[n]][0].bytes, diff.bytes);
}
return true;
}
}
| [
"leoreinaux@gmail.com"
] | leoreinaux@gmail.com |
a0ac82b32b27edff01dd53c60453504ebd0d528d | cf450832dd79748ca18a42e3495185ec334e24e0 | /src/CalTrig/CalTrigTool.h | 42d425ec3b28c41bd055b7c460645c8f662aa861 | [
"BSD-3-Clause"
] | permissive | fermi-lat/CalXtalResponse | 2d3e83e4d1ae9f5f826dd17686c99b27ff2ce657 | 3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8 | refs/heads/master | 2022-02-17T03:12:05.147230 | 2019-08-27T17:27:11 | 2019-08-27T17:27:11 | 103,186,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,867 | h | // $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/CalXtalResponse/src/CalTrig/CalTrigTool.h,v 1.12 2008/08/01 01:45:59 fewtrell Exp $
/** @file
@author Z.Fewtrell
*/
#ifndef CalTrigTool_h
#define CalTrigTool_h
// LOCAL
#include "CalXtalResponse/ICalTrigTool.h"
#include "CalXtalResponse/ICalCalibSvc.h"
#include "CalXtalResponse/ICalSignalTool.h"
// GLAST
#include "CalUtil/CalDefs.h"
#include "CalUtil/CalVec.h"
#include "Event/Digi/CalDigi.h"
// EXTLIB
#include "GaudiKernel/IIncidentListener.h"
#include "GaudiKernel/AlgTool.h"
// STD
class IGlastDetSvc;
class IPrecalcCalibTool;
class IDataProviderSvc;
/*! \class CalTrigTool
\author Z.Fewtrell
\brief Default implementation of ICalTrigTool. Simulates GLAST Cal trigger
response based on either Cal xtal digi response or simulated signal
level (from MC)
jobOptions:
- CalCalibSvc - cal calibration data source (default="CalCalibSvc")
- PrecalcCalibTool - source for derived calibration quantities (default="PrecalcCalibTool")
- CalSignalToolName - source for cal signal levels (default="CalSignalTool")
*/
class CalTrigTool :
public AlgTool,
virtual public ICalTrigTool,
virtual public IIncidentListener
{
public:
/// default ctor, declares jobOptions
CalTrigTool( const std::string& type,
const std::string& name,
const IInterface* parent);
/// gets needed parameters and pointers to required services
StatusCode initialize();
StatusCode finalize() {return StatusCode::SUCCESS;}
/// \brief return 16 bit trigger vector for FLE trigger, one bit per tower
StatusCode getCALTriggerVector(idents::CalXtalId::DiodeType diode,
unsigned short &vec);
/// return trigger response for given channel (specify xtal, face & diode)
StatusCode getTriggerBit(CalUtil::DiodeIdx diodeIdx, bool &trigBit);
/// hook the BeginEvent so that we can check our validity once per event.
void handle ( const Incident& inc );
private:
/// update all Cal Trigger bits w/ current TDS data (either MC or
/// Digi)
StatusCode calcGlobalTrig();
/// update all Cal Trigger bits w/ current TDS MC data (via CalSignalTool)
StatusCode CalTrigTool::calcGlobalTrigSignalTool();
/// update all Cal Trigger bits w/ current TDS data from CalDigi
StatusCode CalTrigTool::calcGlobalTrigDigi(const Event::CalDigiCol &calDigiCol);
/// call to clear all trigger bits (like @ beginning of event)
void newEvent();
/// set single Cal trigger channel to high, set all corresponding
/// records simultaneously.
void setSingleBit(const CalUtil::DiodeIdx diodeIdx);
/// calculate single xtal trigger response from cal Digi object.
///
/// store results in internal private tables
StatusCode calcXtalTrig(const Event::CalDigi& calDigi);
/// calculate trigger response for single crystal from CIDAC diode
/// levels
///
/// store results in internal private tables
StatusCode calcXtalTrigSignalTool(const CalUtil::XtalIdx xtalIdx);
/// calculate trigger response from single crystal readout
StatusCode calcXtalTrig(const CalUtil::XtalIdx xtalIdx,
const Event::CalDigi::CalXtalReadout &ro);
/// calculate trigger response from pedestal subtracted adc values
/// for all 8 adc channels
StatusCode calcXtalTrig(const CalUtil::XtalIdx xtalIdx,
const CalUtil::CalVec<CalUtil::XtalRng, float> &adcPed);
/// store trigger values for each channel in Cal
typedef CalUtil::CalVec<CalUtil::DiodeIdx, bool> CalTriggerMap;
/// store trigger values for each channel in Cal
CalTriggerMap m_calTriggerMap;
/// store FLE trigger vector for each tower in cal
CalUtil::CalVec<CalUtil::DiodeNum,
unsigned short> m_calTriggerVec;
/// name of CalCalibSvc to use for calib constants.
StringProperty m_calCalibSvcName;
/// pointer to CalCalibSvc object.
ICalCalibSvc *m_calCalibSvc;
/// name of precalc calib tool
StringProperty m_precalcCalibName;
IPrecalcCalibTool *m_precalcCalibTool;
/// ptr to event svc
IDataProviderSvc* m_evtSvc;
// name of CalSignalTool tool
StringProperty m_calSignalToolName;
/// ptr to CalSignalTool tool
ICalSignalTool *m_calSignalTool;
/// used for constants & conversion routines.
IGlastDetSvc* m_detSvc;
/// list of active tower bays, populated at run time
std::vector<CalUtil::TwrNum> m_twrList;
/// if current private data store is valid
bool m_isValid;
/// CAL rows/columns selection for FLE/FHE trigger generation:
/// "default" - enable all channels to produce trigger
/// "erec" - enable only even columns in even rows and odd columns in odd rows
/// "eroc" - enable only odd columns in even rows and even columns in odd rows
StringProperty m_selectionRule;
};
#endif
| [
""
] | |
b4aac75bc7a20c4a4e81373d9ca9f580c38b3a83 | 9f9660f318732124b8a5154e6670e1cfc372acc4 | /Case_save/Case10/Case/case7/1200/U | 2e6720538622a223c01f220d2f8a1009902aea88 | [] | no_license | mamitsu2/aircond5 | 9a6857f4190caec15823cb3f975cdddb7cfec80b | 20a6408fb10c3ba7081923b61e44454a8f09e2be | refs/heads/master | 2020-04-10T22:41:47.782141 | 2019-09-02T03:42:37 | 2019-09-02T03:42:37 | 161,329,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,255 | // -*- C++ -*-
// File generated by PyFoam - sorry for the ugliness
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "1200";
object U;
}
dimensions [ 0 1 -1 0 0 0 0 ];
internalField nonuniform List<vector> 459
(
(0.0238908 0.0455331 0)
(-0.112869 0.00350263 0)
(-0.10594 -0.00961448 0)
(-0.095305 -0.0163906 0)
(-0.0782352 -0.0185444 0)
(-0.0594299 -0.0150278 0)
(-0.0438834 -0.0118614 0)
(-0.0312698 -0.0100464 0)
(-0.0207782 -0.00901629 0)
(-0.0118798 -0.00826639 0)
(-0.00443978 -0.00748535 0)
(0.00233104 -0.00621716 0)
(0.00586273 -0.00432649 0)
(-0.010586 -0.00144622 0)
(0.0958073 0.00584987 0)
(-0.0728346 -0.00313364 0)
(0.022837 0.00436803 0)
(-0.00444182 0.00293754 0)
(-0.00909259 0.000667632 0)
(-0.00839282 -0.00014741 0)
(-0.00793908 0.00151933 0)
(-0.00139452 -0.00526397 0)
(0.00379168 -0.00962933 0)
(0.0137322 -0.0072657 0)
(0.0198793 -0.00521533 0)
(0.024129 -0.00367964 0)
(0.0273302 -0.00270596 0)
(0.0301051 -0.00257239 0)
(0.032717 -0.00278348 0)
(0.0352661 -0.00194903 0)
(0.0318857 0.00341097 0)
(0.0227431 0.00815246 0)
(-0.0145985 0.0134679 0)
(0.065047 -0.00317626 0)
(0.249886 0.106543 0)
(-0.0736936 0.0385139 0)
(-0.0712958 -0.0127698 0)
(-0.0704802 -0.0266119 0)
(-0.0610871 -0.031365 0)
(-0.0476168 -0.0254302 0)
(-0.0374128 -0.0199802 0)
(-0.0294831 -0.0163821 0)
(-0.0233783 -0.0138959 0)
(-0.0188588 -0.0118328 0)
(-0.0157368 -0.0098121 0)
(-0.0137292 -0.00767034 0)
(-0.0130049 -0.00553163 0)
(-0.0139834 -0.00584228 0)
(0.0127203 0.0012368 0)
(0.00273979 0.0125265 0)
(0.00515922 0.0211245 0)
(-0.118716 0.00177435 0)
(0.0278498 0.00358634 0)
(0.00646858 0.00514904 0)
(0.00046028 0.00348963 0)
(-0.00652693 0.000695376 0)
(-0.0182473 -0.00161808 0)
(-0.00951097 -0.0149222 0)
(-0.00960853 -0.0178741 0)
(0.00307857 -0.0113122 0)
(0.00697839 -0.00774811 0)
(0.00851092 -0.00542244 0)
(0.00899083 -0.00366856 0)
(0.00837032 -0.00216395 0)
(0.00494955 0.000488579 0)
(-0.000972893 0.00678086 0)
(-0.00122238 0.0152007 0)
(-0.00344853 0.0159762 0)
(-0.0378693 0.0165629 0)
(0.1297 -0.0019709 0)
(0.29986 0.0615718 0)
(0.14224 0.084447 0)
(0.0645129 0.0687643 0)
(-0.00631406 0.0122885 0)
(-0.0364646 -0.0284577 0)
(-0.0360888 -0.0293469 0)
(-0.0341554 -0.0247677 0)
(-0.0320929 -0.0201401 0)
(-0.03127 -0.0160723 0)
(-0.0321894 -0.0122598 0)
(-0.0349395 -0.008568 0)
(-0.0393415 -0.00527334 0)
(-0.0449669 -0.00304219 0)
(-0.0502753 -0.00244556 0)
(-0.0509353 -0.00259128 0)
(-0.0514467 -0.00525788 0)
(-0.0614956 -0.0155281 0)
(-0.134557 0.0152451 0)
(-0.0069207 0.00163099 0)
(-0.0160387 0.0021834 0)
(-0.01271 0.00257651 0)
(-0.00612162 0.00303225 0)
(-0.00541508 0.00423905 0)
(0.0116659 -0.0106692 0)
(-0.0216733 -0.0150388 0)
(-0.0356962 -0.00933028 0)
(-0.0442647 -0.00649082 0)
(-0.0499875 -0.00477914 0)
(-0.0540795 -0.00361002 0)
(-0.0570545 -0.00286846 0)
(-0.0572062 -0.00255284 0)
(-0.0503811 -0.00292455 0)
(-0.0364637 -0.00150171 0)
(-0.0198533 0.00373456 0)
(-0.0442542 0.00694956 0)
(0.177995 -0.000229647 0)
(-0.255768 -0.0653209 0)
(0.109429 0.100786 0)
(0.0341762 0.0975474 0)
(-0.0138075 0.0413854 0)
(-0.032741 -0.0128158 0)
(-0.0378592 -0.0274271 0)
(-0.0391313 -0.0251639 0)
(-0.0414537 -0.0191586 0)
(-0.0457287 -0.012992 0)
(-0.0519579 -0.00707897 0)
(-0.0597983 -0.0018061 0)
(-0.0683162 0.00189192 0)
(-0.0764847 0.0028532 0)
(-0.0834984 0.000262752 0)
(-0.0889203 -0.00667382 0)
(-0.0957416 -0.0205609 0)
(-0.106515 -0.0446257 0)
(-0.10767 -0.0705374 0)
(-0.0988178 0.00502721 0)
(-0.083744 0.000627565 0)
(-0.0893092 0.00228801 0)
(-0.0934253 0.00284372 0)
(-0.0988121 0.00207608 0)
(-0.105417 -8.4988e-05 0)
(-0.110836 -0.000311784 0)
(-0.111402 -0.00181449 0)
(-0.1105 -0.00328954 0)
(-0.108014 -0.00457782 0)
(-0.104211 -0.00588971 0)
(-0.0991291 -0.00738663 0)
(-0.0923778 -0.00923743 0)
(-0.0829887 -0.0117155 0)
(-0.0703944 -0.0152412 0)
(-0.058497 -0.0197475 0)
(-0.0509071 -0.0224442 0)
(-0.0652292 -0.0227777 0)
(0.220665 0.00912027 0)
(-0.393607 -0.0565149 0)
(0.141295 0.0883131 0)
(0.0588227 0.119218 0)
(0.0103801 0.0821418 0)
(-0.0292624 0.00603448 0)
(-0.0439962 -0.0241601 0)
(-0.0478918 -0.0217367 0)
(-0.0544584 -0.0134088 0)
(-0.0626666 -0.00544795 0)
(-0.0713303 0.00144011 0)
(-0.0789041 0.00660526 0)
(-0.0851914 0.00987264 0)
(-0.0905464 0.0111486 0)
(-0.0951429 0.0102693 0)
(-0.0997298 0.0071159 0)
(-0.106754 0.00159955 0)
(-0.117648 -0.00373737 0)
(-0.123638 -0.00344823 0)
(-0.123036 0.000858199 0)
(-0.12114 0.00182929 0)
(-0.120766 0.00414062 0)
(-0.119865 0.00550127 0)
(-0.118909 0.00561538 0)
(-0.117933 0.00440374 0)
(-0.116522 0.0026282 0)
(-0.114602 -4.23849e-05 0)
(-0.112473 -0.00223693 0)
(-0.109928 -0.00403774 0)
(-0.106934 -0.00565969 0)
(-0.103564 -0.00731737 0)
(-0.0998702 -0.00924997 0)
(-0.0959382 -0.011863 0)
(-0.0924851 -0.0158471 0)
(-0.091644 -0.0214037 0)
(-0.0969121 -0.0253089 0)
(-0.107567 -0.0259839 0)
(-0.11072 -0.0132032 0)
(-0.142209 -0.0162836 0)
(-0.121458 -0.0346913 0)
(0.19038 -0.0956664 0)
(-0.423404 -0.115892 0)
(0.166351 0.054176 0)
(0.125101 0.136534 0)
(0.0712816 0.138848 0)
(0.00809496 0.0621463 0)
(-0.0417491 -0.0116682 0)
(-0.0541461 -0.0120818 0)
(-0.0671397 -0.00311799 0)
(-0.0783414 0.00429444 0)
(-0.0865514 0.00921766 0)
(-0.0922293 0.0124161 0)
(-0.0960237 0.0141467 0)
(-0.0985984 0.0142743 0)
(-0.100614 0.0124325 0)
(-0.103031 0.00826896 0)
(-0.107295 0.00218826 0)
(-0.113641 -0.00289696 0)
(-0.118723 -0.00290548 0)
(-0.120408 -0.000896472 0)
(-0.119768 0.000421962 0)
(-0.118018 0.00184587 0)
(-0.1153 0.00259195 0)
(-0.112169 0.00234783 0)
(-0.10897 0.00110227 0)
(-0.105859 -0.000797876 0)
(-0.103055 -0.00313685 0)
(-0.100497 -0.0053698 0)
(-0.0979597 -0.00737137 0)
(-0.0953186 -0.00918969 0)
(-0.0925468 -0.0108928 0)
(-0.0896812 -0.0125425 0)
(-0.0868758 -0.0142439 0)
(-0.0846273 -0.0161393 0)
(-0.0837842 -0.0179616 0)
(-0.0844007 -0.018317 0)
(-0.0835347 -0.0163149 0)
(-0.0798208 -0.0107461 0)
(-0.0934025 -0.0139356 0)
(-0.14096 -0.0236404 0)
(0.290921 -0.123206 0)
(-0.411249 -0.189394 0)
(0.175645 -0.0715267 0)
(0.190415 0.113795 0)
(0.127569 0.197055 0)
(0.0422126 0.139148 0)
(-0.0323461 0.0341332 0)
(-0.0578486 0.0126328 0)
(-0.0770546 0.0124334 0)
(-0.0886919 0.0140309 0)
(-0.0947434 0.0150454 0)
(-0.0970539 0.0155215 0)
(-0.096887 0.0154538 0)
(-0.0952239 0.0147099 0)
(-0.0930183 0.0129309 0)
(-0.0912933 0.00970954 0)
(-0.0910372 0.00520289 0)
(-0.092366 0.000946611 0)
(-0.0939273 -0.00108495 0)
(-0.094086 -0.00147417 0)
(-0.0928973 -0.00142513 0)
(-0.0907898 -0.00112826 0)
(-0.0879194 -0.00105083 0)
(-0.0846453 -0.00150133 0)
(-0.0813674 -0.00258345 0)
(-0.0783975 -0.00418735 0)
(-0.0758088 -0.00614397 0)
(-0.0735634 -0.00818455 0)
(-0.0715027 -0.0101854 0)
(-0.0694726 -0.0121312 0)
(-0.0673489 -0.0140438 0)
(-0.0650237 -0.0159577 0)
(-0.0624149 -0.0179299 0)
(-0.0595183 -0.0199855 0)
(-0.0563025 -0.0218626 0)
(-0.0519545 -0.0228135 0)
(-0.0432321 -0.022333 0)
(-0.0266859 -0.0219772 0)
(-0.0215612 -0.0272579 0)
(-0.16056 -0.0374831 0)
(0.445459 -0.134403 0)
(-0.386661 -0.187463 0)
(0.069829 -0.158877 0)
(0.155601 0.0410666 0)
(0.120372 0.269757 0)
(-0.0133461 0.195795 0)
(-0.0609266 0.0735684 0)
(-0.0736295 0.038209 0)
(-0.0863179 0.0262693 0)
(-0.0910977 0.0203005 0)
(-0.0902744 0.0165124 0)
(-0.0860516 0.0139441 0)
(-0.0799009 0.0119574 0)
(-0.0727243 0.0103062 0)
(-0.0653952 0.00859316 0)
(-0.0587694 0.00632917 0)
(-0.0536802 0.00340745 0)
(-0.0501981 0.000491558 0)
(-0.0479923 -0.00155715 0)
(-0.0462719 -0.00264848 0)
(-0.0444222 -0.00321757 0)
(-0.0423509 -0.00350012 0)
(-0.0400433 -0.00378575 0)
(-0.0376391 -0.00429015 0)
(-0.0353346 -0.00513845 0)
(-0.0333066 -0.00635368 0)
(-0.031651 -0.00786617 0)
(-0.030365 -0.00954941 0)
(-0.0293529 -0.0113299 0)
(-0.0284874 -0.0131914 0)
(-0.0276294 -0.0151531 0)
(-0.0266166 -0.0172653 0)
(-0.0252489 -0.0196242 0)
(-0.0232693 -0.0223614 0)
(-0.0202498 -0.0255537 0)
(-0.0150812 -0.0291882 0)
(-0.00438301 -0.0336901 0)
(0.0187411 -0.0411961 0)
(0.0452956 -0.0525297 0)
(-0.0857365 -0.0634453 0)
(0.743413 -0.0935043 0)
(-0.378842 -0.0789833 0)
(-0.287656 -0.101878 0)
(-0.546445 0.0290606 0)
(0.0302203 0.341105 0)
(-0.136879 0.209649 0)
(-0.115832 0.0918188 0)
(-0.0931626 0.0506152 0)
(-0.0802681 0.0333794 0)
(-0.0677845 0.0232337 0)
(-0.0546277 0.0163509 0)
(-0.040457 0.0118341 0)
(-0.0273712 0.00917146 0)
(-0.0154211 0.00762975 0)
(-0.00473328 0.00663131 0)
(0.00461272 0.00562344 0)
(0.011743 0.00440618 0)
(0.0167346 0.00310726 0)
(0.0199474 0.00198358 0)
(0.0220822 0.00114726 0)
(0.0236103 0.000531247 0)
(0.0248105 6.41046e-05 0)
(0.0258477 -0.00037384 0)
(0.0267575 -0.000894959 0)
(0.0274923 -0.00158315 0)
(0.0279717 -0.00248002 0)
(0.0281287 -0.00358083 0)
(0.0279424 -0.00485292 0)
(0.0274454 -0.00628121 0)
(0.0267023 -0.00788283 0)
(0.0257999 -0.00971101 0)
(0.0248529 -0.0118669 0)
(0.0240161 -0.0145276 0)
(0.0235011 -0.0179859 0)
(0.0236183 -0.0227028 0)
(0.0249862 -0.0294448 0)
(0.0296171 -0.039698 0)
(0.0411615 -0.0560125 0)
(0.0553519 -0.0793432 0)
(-0.0760206 -0.0904187 0)
(0.800292 -0.0400734 0)
(-2.58675 0.0604995 0)
(-0.0507152 0.208699 0)
(-0.202598 0.133504 0)
(-0.110385 0.047381 0)
(-0.0382945 0.0110299 0)
(0.0041223 0.00142837 0)
(0.0313338 -0.00230798 0)
(0.0510361 -0.00356016 0)
(0.0651905 -0.00274842 0)
(0.076286 -0.000583929 0)
(0.0851672 0.00226914 0)
(0.0922329 0.00529997 0)
(0.0977165 0.00812053 0)
(0.101733 0.0104216 0)
(0.104392 0.0119907 0)
(0.105836 0.0128121 0)
(0.106326 0.0129901 0)
(0.10614 0.0126708 0)
(0.105512 0.0120016 0)
(0.104612 0.0110832 0)
(0.103526 0.00996917 0)
(0.102268 0.00867742 0)
(0.100803 0.00720427 0)
(0.0990789 0.00553545 0)
(0.0970493 0.00364541 0)
(0.0946903 0.00148247 0)
(0.0919962 -0.00104182 0)
(0.0889735 -0.00406194 0)
(0.0856354 -0.00777338 0)
(0.0819914 -0.0124574 0)
(0.0780243 -0.0185157 0)
(0.0736338 -0.0265155 0)
(0.0685635 -0.0372589 0)
(0.0626866 -0.0519135 0)
(0.055282 -0.0720662 0)
(0.0376687 -0.0973473 0)
(-0.100532 -0.0993431 0)
(0.363815 0.025269 0)
(-1.17704 0.0740583 0)
(0.481846 -0.0740661 0)
(0.208455 -0.102376 0)
(0.180711 -0.134553 0)
(0.196041 -0.144758 0)
(0.209901 -0.145551 0)
(0.217342 -0.145489 0)
(0.221081 -0.147039 0)
(0.222496 -0.150121 0)
(0.222151 -0.153941 0)
(0.220373 -0.157639 0)
(0.217466 -0.160466 0)
(0.213778 -0.161882 0)
(0.209673 -0.161671 0)
(0.20545 -0.159964 0)
(0.201307 -0.157126 0)
(0.197362 -0.153634 0)
(0.193662 -0.149948 0)
(0.190186 -0.146434 0)
(0.186869 -0.14333 0)
(0.183611 -0.140756 0)
(0.180295 -0.138737 0)
(0.176801 -0.137239 0)
(0.173018 -0.136194 0)
(0.168853 -0.135521 0)
(0.164229 -0.13515 0)
(0.159078 -0.135023 0)
(0.153324 -0.135098 0)
(0.146857 -0.135345 0)
(0.139515 -0.135737 0)
(0.131028 -0.136234 0)
(0.120949 -0.136764 0)
(0.108534 -0.137193 0)
(0.0929515 -0.13731 0)
(0.0734941 -0.136883 0)
(0.049772 -0.138144 0)
(-0.0982036 -0.147965 0)
(0.426413 -0.26839 0)
(-0.85986 0.0070178 0)
(0.717893 0.479461 0)
(0.370712 0.39108 0)
(0.631615 0.303574 0)
(0.643075 0.288609 0)
(0.592637 0.288471 0)
(0.553177 0.291128 0)
(0.52349 0.300294 0)
(0.496041 0.315641 0)
(0.469727 0.334922 0)
(0.445513 0.35615 0)
(0.423892 0.377604 0)
(0.404885 0.39754 0)
(0.388396 0.414292 0)
(0.374279 0.426611 0)
(0.362289 0.433962 0)
(0.352068 0.43661 0)
(0.343187 0.435464 0)
(0.335225 0.431754 0)
(0.327814 0.426705 0)
(0.320672 0.421317 0)
(0.313596 0.416282 0)
(0.306446 0.411996 0)
(0.299126 0.408616 0)
(0.291559 0.406135 0)
(0.283679 0.404454 0)
(0.275407 0.403429 0)
(0.266649 0.402914 0)
(0.257274 0.402778 0)
(0.247108 0.402912 0)
(0.235918 0.403227 0)
(0.223396 0.403639 0)
(0.209144 0.404041 0)
(0.192655 0.404252 0)
(0.173265 0.403956 0)
(0.150269 0.402584 0)
(0.123604 0.39854 0)
(0.0983914 0.387992 0)
(-0.118428 0.437632 0)
(0.54914 0.707282 0)
)
;
boundaryField
{
floor
{
type noSlip;
}
ceiling
{
type noSlip;
}
sWall
{
type noSlip;
}
nWall
{
type noSlip;
}
sideWalls
{
type empty;
}
glass1
{
type noSlip;
}
glass2
{
type noSlip;
}
sun
{
type noSlip;
}
heatsource1
{
type noSlip;
}
heatsource2
{
type noSlip;
}
Table_master
{
type noSlip;
}
Table_slave
{
type noSlip;
}
inlet
{
type fixedValue;
value uniform (0.277164 -0.114805 0);
}
outlet
{
type zeroGradient;
}
} // ************************************************************************* //
| [
"mitsuaki.makino@tryeting.jp"
] | mitsuaki.makino@tryeting.jp | |
392ed315556e9cb63f7e731118aad2495dd68290 | 260a986070c2092c2befabf491d6a89b43b8c781 | /coregame_tasks/taskutil.cpp | 68ec411a2723303ed7eb39e2b3aa2233966c5cf0 | [] | no_license | razodactyl/darkreign2 | 7801e5c7e655f63c6789a0a8ed3fef9e5e276605 | b6dc795190c05d39baa41e883ddf4aabcf12f968 | refs/heads/master | 2023-03-26T11:45:41.086911 | 2020-07-10T22:43:26 | 2020-07-10T22:43:26 | 256,714,317 | 11 | 2 | null | 2020-04-20T06:10:20 | 2020-04-18T09:27:10 | C++ | UTF-8 | C++ | false | false | 7,965 | cpp | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright 1997-1999 Pandemic Studios, Dark Reign II
//
// Task Utils
//
///////////////////////////////////////////////////////////////////////////////
//
// Includes
//
#include "taskutil.h"
#include "utiltypes.h"
#include "sight.h"
#include "random.h"
#include "connectedregion.h"
///////////////////////////////////////////////////////////////////////////////
//
// NameSpace TaskUtil
//
namespace TaskUtil
{
///////////////////////////////////////////////////////////////////////////////
//
// Definitions
//
// Score to give to each visible spot
const U32 ExploreScoreVisible = 8;
// Score to give to each seen spot
const U32 ExploreScoreSeen = 4;
// Score to give to each edge spot
const U32 ExploreScoreEdge = 4;
// Score to give to each spot we can't move to
const U32 ExploreScoreMovement = 4;
// Score to add to invalid points
const U32 ExploreScoreInvalid = 1000000;
// Clamp to apply to occupation values
const U32 ExploreOccupationClamp = 8;
// Radius at which to pick the spots
const F32 ExploreRadius[2] = { 100.0f, 50.0F };
// Number of spots to consider
const U32 ExploreSpots = 64;
const F32 ExploreSpotsInv = 1.0F / F32(ExploreSpots);
// Mask which coresponds with the above number
const U32 ExploreSpotMask = (ExploreSpots - 1);
// Explore cell boundary
const U32 ExploreCellEdge = 8;
///////////////////////////////////////////////////////////////////////////////
//
// Struct ExploreSpot
//
struct ExploreSpot
{
// The point
Point<U32> cell;
// The score for the point
U32 score;
// Is the spot connected to current position?
U32 connected : 1;
};
//
// Find an unexplored point
//
void FindUnexplored(Vector &location, const Point<S32> &cell, U8 tractionType, Team *team)
{
ExploreSpot spots[ExploreSpots];
U32 i;
// Clear the scores
for (i = 0; i < ExploreSpots; i++)
{
spots[i].score = 0;
}
// Connected region index of source cell
ConnectedRegion::Pixel srcValue = ConnectedRegion::GetValue(tractionType, cell.x, cell.z);
for (i = 0; i < ExploreSpots; i++)
{
ExploreSpot &spot = spots[i];
F32 angle = F32(i) * PI2 * ExploreSpotsInv;
Point<F32> p(location.x, location.z);
p.x += F32(cos(angle)) * ExploreRadius[i & 1];
p.z += F32(sin(angle)) * ExploreRadius[i & 1];
WorldCtrl::ClampPlayFieldPoint(p);
WorldCtrl::MetresToCellPoint(p, spot.cell);
// Only consider points more than 2 cells away after clamping
S32 dist = Max<S32>(abs((long)spot.cell.x - (long)cell.x), abs((long)spot.cell.z - (long)cell.z));
if (dist > 2)
{
MapCluster *cluster = WorldCtrl::CellsToCluster(spot.cell.x, spot.cell.z);
U32 occupation = cluster->ai.GetOccupation(team->GetId());
if (occupation)
{
Clamp<U32>(0, occupation, ExploreOccupationClamp);
U32 a;
spot.score += occupation;
for (a = 1; a < occupation; a++)
{
spots[(i + a) & ExploreSpotMask].score += (occupation - a);
spots[(i - a) & ExploreSpotMask].score += (occupation - a);
}
}
// If the cell is close to the edge of the map, give it some score
if (spot.cell.x <= ExploreCellEdge)
{
U32 a;
spot.score += ExploreScoreEdge;
for (a = 1; a < ExploreScoreEdge; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
}
}
else if (spot.cell.x >= WorldCtrl::CellMapX() - ExploreCellEdge)
{
U32 a;
spot.score += ExploreScoreEdge;
for (a = 1; a < ExploreScoreEdge; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
}
}
else if (spot.cell.z <= ExploreCellEdge)
{
U32 a;
spot.score += ExploreScoreEdge;
for (a = 1; a < ExploreScoreEdge; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
}
}
else if (spot.cell.z >= WorldCtrl::CellMapZ() - ExploreCellEdge)
{
U32 a;
spot.score += ExploreScoreEdge;
for (a = 1; a < ExploreScoreEdge; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreEdge - a);
}
}
// If the cell can't be moved to by this traction type, bump it up
if (srcValue != ConnectedRegion::GetValue(tractionType, spot.cell.x, spot.cell.z))
{
U32 a;
spot.score += ExploreScoreMovement + ExploreScoreInvalid;
for (a = 1; a < ExploreScoreMovement; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreMovement - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreMovement - a);
}
}
// Get the visibility of this cell
Bool seen, visible;
Sight::SeenVisible(spot.cell.x, spot.cell.z, team, seen, visible);
if (visible)
{
U32 a;
spot.score += ExploreScoreVisible;
for (a = 1; a < ExploreScoreVisible; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreVisible - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreVisible - a);
}
}
else if (seen)
{
U32 a;
spot.score += ExploreScoreSeen;
for (a = 1; a < ExploreScoreSeen; a++)
{
spots[(i + a) & ExploreSpotMask].score += (ExploreScoreSeen - a);
spots[(i - a) & ExploreSpotMask].score += (ExploreScoreSeen - a);
}
}
}
else
{
spots[i].score += ExploreScoreInvalid;
}
}
// Build up the array of all of the spots which have the minimum score
ExploreSpot * minSpots[ExploreSpots];
U32 minNumSpots = 0;
for (i = 0; i < ExploreSpots; i++)
{
minSpots[i] = NULL;
}
U32 minScore = U32_MAX;
for (i = 0; i < ExploreSpots; i++)
{
// If this spot has the new smallest score,
// clear out the min spots and make this the only min spot
if (spots[i].score < minScore)
{
for (U32 s = 0; s < ExploreSpots; s++)
{
minSpots[s] = NULL;
}
minSpots[i] = &spots[i];
minScore = spots[i].score;
minNumSpots = 1;
}
else
// If this spot has the same score as the current smallest score,
// add this spot to the array of min spots
if (spots[i].score == minScore)
{
minSpots[i] = &spots[i];
minNumSpots++;
}
}
ASSERT(minNumSpots)
// We now have a pointer array to all of the min spots, select one at random
U32 spot = Random::sync.Integer(minNumSpots);
for (i = 0; i < ExploreSpots; i++)
{
if (minSpots[i])
{
if (!spot)
{
break;
}
else
{
spot--;
}
}
}
Point<F32> val;
WorldCtrl::CellToMetrePoint(minSpots[i]->cell, val);
// Put in the new location
location.x = val.x;
location.z = val.z;
}
}
| [
"razodactyl@gmail.com"
] | razodactyl@gmail.com |
8aa2ec4d06ae7a4c7a657ba12e383e70ccd39383 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/55/35e51d210d59ec/main.cpp | 5b12fb781f553768543ceecf62fca453e2e6d198 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,058 | cpp | // Heterogeneous vector (unordered) over specified sequence of types
#include <boost/fusion/algorithm/transformation/transform.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/phoenix/function/adapt_callable.hpp>
#include <boost/phoenix/stl/algorithm.hpp>
#include <boost/phoenix.hpp>
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace boost;
using namespace std;
using phoenix::arg_names::arg1;
// ___________________________________________________________________ //
// syntax sugar
struct get_fusion_pair_value
{
template<typename FusionPair>
auto operator()(FusionPair &fp) const -> decltype(fp.second)
{
return fp.second;
}
};
BOOST_PHOENIX_ADAPT_CALLABLE(fp_second, get_fusion_pair_value, 1)
// ___________________________________________________________________ //
template<typename ...Ts>
struct poly_sequence
{
typename fusion::result_of::as_map
<
typename mpl::transform
<
mpl::vector<Ts...>,
fusion::pair< mpl::_1, std::vector<mpl::_1> >
>::type
>::type vectors;
};
template<typename ...Ts, typename T>
void push_back(poly_sequence<Ts...> &seq, const T &value)
{
fusion::at_key<T>(seq.vectors).push_back(value);
}
template<typename ...Ts, typename PolymorhicUnaryFunctor>
void for_each(poly_sequence<Ts...> &seq, PolymorhicUnaryFunctor f)
{
fusion::for_each
(
seq.vectors,
phoenix::for_each(fp_second(arg1), f)
);
}
// ___________________________________________________________________ //
struct Print
{
template<typename T>
void operator()(const T &x)
{
cout << x << endl;
}
};
int main()
{
poly_sequence<int, double> seq;
for(int i=0; i!=3; ++i)
{
push_back(seq, i);
push_back(seq, i+0.1);
}
for_each(seq, Print{});
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
378457d8a5b745db187d2ad6de0f7e5cf968d0ad | ec38324d1535c500255487db1cf809f5790d62d6 | /WebTemperatureLogger/event.h | d6c0a748ac8327b256925604b8e7ebae28eb73f5 | [] | no_license | EmbeddedSystemClass/hardware-firmware-arduino | 4a7b36a01af82fecc0fde3f1b75e4e7ad7fb31f0 | b39010d20ba548f2b6425b0cda2a41826a01cf8f | refs/heads/master | 2020-04-13T10:40:17.062444 | 2016-05-30T09:57:32 | 2016-05-30T09:57:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,518 | h | #ifndef _EVENTSH_
#define _EVENTSH_
/*
Events: timer and logging events
This example code is in the public domain.
*/
// Touche Screen
#define YP A2 // must be an analog pin, use "An" notation!
#define XM A1 // must be an analog pin, use "An" notation!
#define YM 6 // can be a digital pin
#define XP 7 // can be a digital pin
#define TS_MINX 150
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940
#define MINPRESSURE 10
#define MAXPRESSURE 1000
// Events ****************************************************************
class EventManager {
private:
uint8_t lastButtonState;
uint16_t counter;
unsigned long lastTimerUpdate;
public:
unsigned bOnTouch:1;
unsigned bLock:1;
unsigned bT50MS:1;
unsigned bT500MS:1;
unsigned bT1000MS:1;
unsigned bT5S:1;
unsigned bT1MIN:1;
void dispatch() {
updateTimerEvents();
}
private:
void updateTimerEvents() {
bT50MS = false;
bT500MS = false;
bT1000MS = false;
bT5S = false;
bT1MIN = false;
// generate 50ms, 500ms timer events
if (millis() - lastTimerUpdate > 50) {
lastTimerUpdate = millis();
counter++;
bT50MS = true;
if (counter % 10 == 0) {
bT500MS = true;
}
if (counter % 20 == 0) {
bT1000MS = true;
}
if (counter % 100 == 0) {
bT5S = true;
}
if (counter % 1200 == 0) {
bT1MIN = true;
}
}
}
};
EventManager Events;
#define LOG_INTERVAL_HOUR 0
#define LOG_INTERVAL_MINUTE 1
#define LOG_INTERVAL_SECOND 2
#define LOG_INTERVAL_5S 5
class LogEventManager {
public:
unsigned bLog:1;
unsigned bEnabled:1;
uint32_t next; // next event timestamp
uint16_t interval; // seconds
public:
LogEventManager() {
bEnabled = false;
}
void dispatch() {
bLog = false;
if(!bEnabled || interval == 0)
return;
uint32_t current = RTC.getTimestamp();
if(current >= next) {
next = current + interval;
bLog = true;
}
}
void begin() {
bEnabled = true;
bLog = false;
next = 0;
interval = 0;
}
void stop() {
bEnabled = false;
bLog = false;
}
};
LogEventManager LogEvents;
#endif
| [
"lucasgaertner@arcor.de"
] | lucasgaertner@arcor.de |
6add0873c0143128b9f4c414961eb801b65036ae | 79813a2689ae22b0315323f398337017639662bb | /src/modules/processes/Flux/FluxCalibrationProcess.cpp | 780f8472558b684be64f04b7af89eea3713e75b7 | [
"LicenseRef-scancode-other-permissive"
] | permissive | jackros1022/PCL-1 | 4b51b494c69e4d97182387aa84ead1a964798264 | 059423bc8a3d7946a628fe1913b805bc3633aea5 | refs/heads/master | 2021-01-23T05:09:19.844862 | 2017-02-08T11:53:24 | 2017-02-08T11:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,990 | cpp | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.01.0784
// ----------------------------------------------------------------------------
// Standard Flux Process Module Version 01.00.01.0135
// ----------------------------------------------------------------------------
// FluxCalibrationProcess.cpp - Released 2016/03/14 10:07:00 UTC
// ----------------------------------------------------------------------------
// This file is part of the standard Flux PixInsight module.
//
// Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 "FluxCalibrationProcess.h"
#include "FluxCalibrationParameters.h"
#include "FluxCalibrationInstance.h"
#include "FluxCalibrationInterface.h"
#include <pcl/Console.h>
#include <pcl/Arguments.h>
#include <pcl/View.h>
#include <pcl/Exception.h>
namespace pcl
{
// ----------------------------------------------------------------------------
#include "FluxCalibrationIcon.xpm"
// ----------------------------------------------------------------------------
FluxCalibrationProcess* TheFluxCalibrationProcess = 0;
// ----------------------------------------------------------------------------
FluxCalibrationProcess::FluxCalibrationProcess() : MetaProcess()
{
TheFluxCalibrationProcess = this;
// Instantiate process parameters
new FCWavelengthValue( this );
new FCWavelengthMode( this );
new FCWavelengthKeyword( this );
new FCTransmissivityValue( this );
new FCTransmissivityMode( this );
new FCTransmissivityKeyword( this );
new FCFilterWidthValue( this );
new FCFilterWidthMode( this );
new FCFilterWidthKeyword( this );
new FCApertureValue( this );
new FCApertureMode( this );
new FCApertureKeyword( this );
new FCCentralObstructionValue( this );
new FCCentralObstructionMode( this );
new FCCentralObstructionKeyword( this );
new FCExposureTimeValue( this );
new FCExposureTimeMode( this );
new FCExposureTimeKeyword( this );
new FCAtmosphericExtinctionValue( this );
new FCAtmosphericExtinctionMode( this );
new FCAtmosphericExtinctionKeyword( this );
new FCSensorGainValue( this );
new FCSensorGainMode( this );
new FCSensorGainKeyword( this );
new FCQuantumEfficiencyValue( this );
new FCQuantumEfficiencyMode( this );
new FCQuantumEfficiencyKeyword( this );
}
// ----------------------------------------------------------------------------
IsoString FluxCalibrationProcess::Id() const
{
return "FluxCalibration";
}
// ----------------------------------------------------------------------------
IsoString FluxCalibrationProcess::Category() const
{
return "Flux"; // No category
}
// ----------------------------------------------------------------------------
uint32 FluxCalibrationProcess::Version() const
{
return 0x100; // required
}
// ----------------------------------------------------------------------------
String FluxCalibrationProcess::Description() const
{
return
"<html>"
"</html>";
}
// ----------------------------------------------------------------------------
const char** FluxCalibrationProcess::IconImageXPM() const
{
return FluxCalibrationIcon_XPM;
}
// ----------------------------------------------------------------------------
ProcessInterface* FluxCalibrationProcess::DefaultInterface() const
{
return TheFluxCalibrationInterface;
}
// ----------------------------------------------------------------------------
ProcessImplementation* FluxCalibrationProcess::Create() const
{
return new FluxCalibrationInstance( this );
}
// ----------------------------------------------------------------------------
ProcessImplementation* FluxCalibrationProcess::Clone( const ProcessImplementation& p ) const
{
const FluxCalibrationInstance* instPtr = dynamic_cast<const FluxCalibrationInstance*>( &p );
return (instPtr != 0) ? new FluxCalibrationInstance( *instPtr ) : 0;
}
// ----------------------------------------------------------------------------
bool FluxCalibrationProcess::CanProcessCommandLines() const
{
return true;
}
// ----------------------------------------------------------------------------
static void ShowHelp()
{
Console().Write(
"<raw>"
"Usage: FluxCalibration [<arg_list>] [<view_list>]"
"\n"
"\n-l | --wavelength"
"\n"
"\n Effective filter wavelenth in nm. This parameter is mandatory."
"\n"
"\n-tr | --transmissivity"
"\n"
"\n Filter transmissivity in the range ]0,1]."
"\n"
"\n-w | --filter-width"
"\n"
"\n Filter bandwith in nm. This parameter is mandatory."
"\n"
"\n-a | --aperture"
"\n"
"\n Telescope aperture diameter in mm. This parameter is mandatory."
"\n"
"\n-o | --central-obstruction"
"\n"
"\n Telescope central obstruction diameter in mm."
"\n"
"\n-t | --exposure-time"
"\n"
"\n Exposure time in seconds. This parameter is mandatory."
"\n"
"\n-e | --atmospheric-extinction"
"\n"
"\n Atmospheric extinction in the range [0,1]."
"\n"
"\n-G | --sensor-gain"
"\n"
"\n Sensor gain (e-/ADU). The gain must be equal or greater than 0."
"\n"
"\n-qe | --quantum-efficiency"
"\n"
"\n Sensor quantum efficiency in the range [0,1[."
"\n"
"\n--interface"
"\n"
"\n Launches the interface of this process."
"\n"
"\n--help"
"\n"
"\n Displays this help and exits."
"</raw>" );
}
int FluxCalibrationProcess::ProcessCommandLine( const StringList& argv ) const
{
ArgumentList arguments =
ExtractArguments( argv, ArgumentItemMode::AsViews, ArgumentOption::AllowWildcards );
FluxCalibrationInstance instance( this );
bool launchInterface = false;
int count = 0;
for ( ArgumentList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
{
const Argument& arg = *i;
if ( arg.IsNumeric() )
{
if ( arg.Id() == "l" || arg.Id() == "-wavelength" )
instance.p_wavelength = arg.NumericValue();
else if ( arg.Id() == "tr" || arg.Id() == "-transmissivity" )
instance.p_transmissivity = arg.NumericValue();
else if ( arg.Id() == "w" || arg.Id() == "-filter-width" )
instance.p_filterWidth = arg.NumericValue();
else if ( arg.Id() == "a" || arg.Id() == "-aperture" )
instance.p_aperture = arg.NumericValue();
else if ( arg.Id() == "o" || arg.Id() == "-central-obstruction" )
instance.p_centralObstruction = arg.NumericValue();
else if ( arg.Id() == "t" || arg.Id() == "-exposure-time" )
instance.p_exposureTime = arg.NumericValue();
else if ( arg.Id() == "e" || arg.Id() == "-atmospheric-extinction" )
instance.p_atmosphericExtinction = arg.NumericValue();
else if ( arg.Id() == "G" || arg.Id() == "-sensor-gain" )
instance.p_sensorGain = arg.NumericValue();
else if ( arg.Id() == "qe" || arg.Id() == "-quantum-efficiency" )
instance.p_quantumEfficiency = arg.NumericValue();
else
throw Error( "Unknown numeric argument: " + arg.Token() );
}
else if ( arg.IsString() )
{
throw Error( "Unknown string argument: " + arg.Token() );
}
else if ( arg.IsSwitch() )
{
throw Error( "Unknown switch argument: " + arg.Token() );
}
else if ( arg.IsLiteral() )
{
// These are standard parameters that all processes should provide.
if ( arg.Id() == "-interface" )
launchInterface = true;
else if ( arg.Id() == "-help" )
{
ShowHelp();
return 0;
}
else
throw Error( "Unknown argument: " + arg.Token() );
}
else if ( arg.IsItemList() )
{
++count;
if ( arg.Items().IsEmpty() )
{
Console().WriteLn( "No view(s) found: " + arg.Token() );
throw;
}
for ( StringList::const_iterator j = arg.Items().Begin(); j != arg.Items().End(); ++j )
{
View v = View::ViewById( *j );
if ( v.IsNull() )
throw Error( "No such view: " + *j );
instance.LaunchOn( v );
}
}
}
if ( launchInterface )
instance.LaunchInterface();
else if ( count == 0 )
{
if ( ImageWindow::ActiveWindow().IsNull() )
throw Error( "There is no active image window." );
instance.LaunchOnCurrentView();
}
return 0;
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF FluxCalibrationProcess.cpp - Released 2016/03/14 10:07:00 UTC
| [
"juan.conejero@pixinsight.com"
] | juan.conejero@pixinsight.com |
e0ca27a477f4a7c925bb181acdd4ac103ec8d089 | 1e939513c8b45242587c8975c8ae1434a3375629 | /12289/main.cpp | e9814a1b53b03c81ac0441e4a75ffd77ebeba9f5 | [] | no_license | Seyfel/Competitive-Programming | e02cab82d653d7604989851b8902e8302c993997 | 50cc66eadcabadf91be5bc2c4fa4e19182e349c0 | refs/heads/master | 2021-04-06T19:50:43.959594 | 2018-03-22T11:27:48 | 2018-03-22T11:27:48 | 125,358,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <iostream>
#include <string>
bool isOne(const std::string &word) {
if (word[0] == 'o' && (word[1] == 'n' || word[2] == 'e')) {
return true;
} else if (word[1] == 'n' && word[2] == 'e') {
return true;
}
return false;
}
int main(int argc, char* argv[]) {
int N;
std::cin >> N;
std::cin.ignore(10000,'\n');
for (int n = 0; n < N; n++) {
std::string word;
std::cin >> word;
if (word.length() == 5) {
std::cout << "3" << std::endl;
} else if (isOne(word)) {
std::cout << "1" << std::endl;
} else {
std::cout << "2" << std::endl;
}
}
return 0;
} | [
"seyfel@gmail.com"
] | seyfel@gmail.com |
345222a999cdebc4b01c7d7c46d6a67389462a58 | cc1701cadaa3b0e138e30740f98d48264e2010bd | /chrome/browser/ui/webui/management_ui_handler.cc | f5aeff7fa6be4f16011fca4836246ae26cf73c9d | [
"BSD-3-Clause"
] | permissive | dbuskariol-org/chromium | 35d3d7a441009c6f8961227f1f7f7d4823a4207e | e91a999f13a0bda0aff594961762668196c4d22a | refs/heads/master | 2023-05-03T10:50:11.717004 | 2020-06-26T03:33:12 | 2020-06-26T03:33:12 | 275,070,037 | 1 | 3 | BSD-3-Clause | 2020-06-26T04:04:30 | 2020-06-26T04:04:29 | null | UTF-8 | C++ | false | false | 42,123 | cc | // Copyright 2018 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 "chrome/browser/ui/webui/management_ui_handler.h"
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "extensions/buildflags/buildflags.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/base/load_flags.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/crostini/crostini_features.h"
#include "chrome/browser/chromeos/crostini/crostini_pref_names.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/policy_cert_service.h"
#include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
#include "chrome/browser/chromeos/policy/status_collector/device_status_collector.h"
#include "chrome/browser/chromeos/policy/status_collector/status_collector.h"
#include "chrome/browser/chromeos/policy/status_uploader.h"
#include "chrome/browser/chromeos/policy/system_log_uploader.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/ui/webui/management_ui_handler_chromeos.h"
#include "chrome/grit/chromium_strings.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/proxy/proxy_config_handler.h"
#include "chromeos/network/proxy/ui_proxy_config_service.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "ui/chromeos/devicetype_utils.h"
#endif // defined(OS_CHROMEOS)
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/common/extensions/permissions/chrome_permission_message_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/policy_constants.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest.h"
#include "extensions/common/permissions/permission_message_provider.h"
#include "extensions/common/permissions/permissions_data.h"
const char kOnPremReportingExtensionStableId[] =
"emahakmocgideepebncgnmlmliepgpgb";
const char kOnPremReportingExtensionBetaId[] =
"kigjhoekjcpdfjpimbdjegmgecmlicaf";
const char kCloudReportingExtensionId[] = "oempjldejiginopiohodkdoklcjklbaa";
const char kPolicyKeyReportMachineIdData[] = "report_machine_id_data";
const char kPolicyKeyReportUserIdData[] = "report_user_id_data";
const char kPolicyKeyReportVersionData[] = "report_version_data";
const char kPolicyKeyReportPolicyData[] = "report_policy_data";
const char kPolicyKeyReportExtensionsData[] = "report_extensions_data";
const char kPolicyKeyReportSafeBrowsingData[] = "report_safe_browsing_data";
const char kPolicyKeyReportSystemTelemetryData[] =
"report_system_telemetry_data";
const char kPolicyKeyReportUserBrowsingData[] = "report_user_browsing_data";
const char kManagementExtensionReportMachineName[] =
"managementExtensionReportMachineName";
const char kManagementExtensionReportMachineNameAddress[] =
"managementExtensionReportMachineNameAddress";
const char kManagementExtensionReportUsername[] =
"managementExtensionReportUsername";
const char kManagementExtensionReportVersion[] =
"managementExtensionReportVersion";
const char kManagementExtensionReportExtensionsPlugin[] =
"managementExtensionReportExtensionsPlugin";
const char kManagementExtensionReportSafeBrowsingWarnings[] =
"managementExtensionReportSafeBrowsingWarnings";
const char kManagementExtensionReportPerfCrash[] =
"managementExtensionReportPerfCrash";
const char kManagementExtensionReportUserBrowsingData[] =
"managementExtensionReportUserBrowsingData";
const char kThreatProtectionTitle[] = "threatProtectionTitle";
const char kManagementDataLossPreventionName[] =
"managementDataLossPreventionName";
const char kManagementDataLossPreventionPermissions[] =
"managementDataLossPreventionPermissions";
const char kManagementMalwareScanningName[] = "managementMalwareScanningName";
const char kManagementMalwareScanningPermissions[] =
"managementMalwareScanningPermissions";
const char kManagementEnterpriseReportingEvent[] =
"managementEnterpriseReportingEvent";
const char kManagementEnterpriseReportingVisibleData[] =
"managementEnterpriseReportingVisibleData";
const char kManagementOnFileAttachedEvent[] = "managementOnFileAttachedEvent";
const char kManagementOnFileAttachedVisibleData[] =
"managementOnFileAttachedVisibleData";
const char kManagementOnFileDownloadedEvent[] =
"managementOnFileDownloadedEvent";
const char kManagementOnFileDownloadedVisibleData[] =
"managementOnFileDownloadedVisibleData";
const char kManagementOnBulkDataEntryEvent[] = "managementOnBulkDataEntryEvent";
const char kManagementOnBulkDataEntryVisibleData[] =
"managementOnBulkDataEntryVisibleData";
const char kReportingTypeDevice[] = "device";
const char kReportingTypeExtensions[] = "extensions";
const char kReportingTypeSecurity[] = "security";
const char kReportingTypeUser[] = "user";
const char kReportingTypeUserActivity[] = "user-activity";
enum class ReportingType {
kDevice,
kExtensions,
kSecurity,
kUser,
kUserActivity
};
#if defined(OS_CHROMEOS)
const char kManagementLogUploadEnabled[] = "managementLogUploadEnabled";
const char kManagementReportActivityTimes[] = "managementReportActivityTimes";
const char kManagementReportHardwareStatus[] = "managementReportHardwareStatus";
const char kManagementReportNetworkInterfaces[] =
"managementReportNetworkInterfaces";
const char kManagementReportUsers[] = "managementReportUsers";
const char kManagementReportCrashReports[] = "managementReportCrashReports";
const char kManagementReportAppInfoAndActivity[] =
"managementReportAppInfoAndActivity";
const char kManagementReportExtensions[] = "managementReportExtensions";
const char kManagementReportAndroidApplications[] =
"managementReportAndroidApplications";
const char kManagementPrinting[] = "managementPrinting";
const char kManagementCrostini[] = "managementCrostini";
const char kManagementCrostiniContainerConfiguration[] =
"managementCrostiniContainerConfiguration";
const char kManagementReportProxyServer[] = "managementReportProxyServer";
const char kAccountManagedInfo[] = "accountManagedInfo";
const char kDeviceManagedInfo[] = "deviceManagedInfo";
const char kOverview[] = "overview";
#endif // defined(OS_CHROMEOS)
const char kCustomerLogo[] = "customerLogo";
const char kPowerfulExtensionsCountHistogram[] = "Extensions.PowerfulCount";
namespace {
bool IsProfileManaged(Profile* profile) {
return profile->GetProfilePolicyConnector()->IsManaged();
}
#if defined(OS_CHROMEOS)
bool IsDeviceManaged() {
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
return connector->IsEnterpriseManaged();
}
#endif // defined(OS_CHROMEOS)
#if !defined(OS_CHROMEOS)
bool IsBrowserManaged() {
return g_browser_process->browser_policy_connector()
->HasMachineLevelPolicies();
}
#endif // !defined(OS_CHROMEOS)
#if defined(OS_CHROMEOS)
enum class DeviceReportingType {
kSupervisedUser,
kDeviceActivity,
kDeviceStatistics,
kDevice,
kCrashReport,
kAppInfoAndActivity,
kLogs,
kPrint,
kCrostini,
kUsername,
kExtensions,
kAndroidApplication,
kProxyServer
};
// Corresponds to DeviceReportingType in management_browser_proxy.js
std::string ToJSDeviceReportingType(const DeviceReportingType& type) {
switch (type) {
case DeviceReportingType::kSupervisedUser:
return "supervised user";
case DeviceReportingType::kDeviceActivity:
return "device activity";
case DeviceReportingType::kDeviceStatistics:
return "device statistics";
case DeviceReportingType::kDevice:
return "device";
case DeviceReportingType::kCrashReport:
return "crash report";
case DeviceReportingType::kAppInfoAndActivity:
return "app info and activity";
case DeviceReportingType::kLogs:
return "logs";
case DeviceReportingType::kPrint:
return "print";
case DeviceReportingType::kCrostini:
return "crostini";
case DeviceReportingType::kUsername:
return "username";
case DeviceReportingType::kExtensions:
return "extension";
case DeviceReportingType::kAndroidApplication:
return "android application";
case DeviceReportingType::kProxyServer:
return "proxy server";
default:
NOTREACHED() << "Unknown device reporting type";
return "device";
}
}
void AddDeviceReportingElement(base::Value* report_sources,
const std::string& message_id,
const DeviceReportingType& type) {
base::Value data(base::Value::Type::DICTIONARY);
data.SetKey("messageId", base::Value(message_id));
data.SetKey("reportingType", base::Value(ToJSDeviceReportingType(type)));
report_sources->Append(std::move(data));
}
#endif // defined(OS_CHROMEOS)
std::vector<base::Value> GetPermissionsForExtension(
scoped_refptr<const extensions::Extension> extension) {
std::vector<base::Value> permission_messages;
// Only consider force installed extensions
if (!extensions::Manifest::IsPolicyLocation(extension->location()))
return permission_messages;
extensions::PermissionIDSet permissions =
extensions::PermissionMessageProvider::Get()
->GetManagementUIPermissionIDs(
extension->permissions_data()->active_permissions(),
extension->GetType());
const extensions::PermissionMessages messages =
extensions::PermissionMessageProvider::Get()->GetPermissionMessages(
permissions);
for (const auto& message : messages)
permission_messages.push_back(base::Value(message.message()));
return permission_messages;
}
base::Value GetPowerfulExtensions(const extensions::ExtensionSet& extensions) {
base::Value powerful_extensions(base::Value::Type::LIST);
for (const auto& extension : extensions) {
std::vector<base::Value> permission_messages =
GetPermissionsForExtension(extension);
// Only show extension on page if there is at least one permission
// message to show.
if (!permission_messages.empty()) {
std::unique_ptr<base::DictionaryValue> extension_to_add =
extensions::util::GetExtensionInfo(extension.get());
extension_to_add->SetKey("permissions",
base::Value(std::move(permission_messages)));
powerful_extensions.Append(std::move(*extension_to_add));
}
}
return powerful_extensions;
}
const char* GetReportingTypeValue(ReportingType reportingType) {
switch (reportingType) {
case ReportingType::kDevice:
return kReportingTypeDevice;
case ReportingType::kExtensions:
return kReportingTypeExtensions;
case ReportingType::kSecurity:
return kReportingTypeSecurity;
case ReportingType::kUser:
return kReportingTypeUser;
case ReportingType::kUserActivity:
return kReportingTypeUserActivity;
default:
return kReportingTypeSecurity;
}
}
} // namespace
// TODO(raleksandov) Move to util class or smth similar.
// static
std::string ManagementUIHandler::GetAccountDomain(Profile* profile) {
if (!IsProfileManaged(profile))
return std::string();
auto username = profile->GetProfileUserName();
size_t email_separator_pos = username.find('@');
bool is_email = email_separator_pos != std::string::npos &&
email_separator_pos < username.length() - 1;
if (!is_email)
return std::string();
const std::string domain = gaia::ExtractDomainName(std::move(username));
return (domain == "gmail.com" || domain == "googlemail.com") ? std::string()
: domain;
}
ManagementUIHandler::ManagementUIHandler() {
reporting_extension_ids_ = {kOnPremReportingExtensionStableId,
kOnPremReportingExtensionBetaId,
kCloudReportingExtensionId};
}
ManagementUIHandler::~ManagementUIHandler() {
DisallowJavascript();
}
void ManagementUIHandler::Initialize(content::WebUI* web_ui,
content::WebUIDataSource* source) {
InitializeInternal(web_ui, source, Profile::FromWebUI(web_ui));
}
// static
void ManagementUIHandler::InitializeInternal(content::WebUI* web_ui,
content::WebUIDataSource* source,
Profile* profile) {
auto handler = std::make_unique<ManagementUIHandler>();
#if defined(OS_CHROMEOS)
handler->account_managed_ = IsProfileManaged(profile);
handler->device_managed_ = IsDeviceManaged();
#else
handler->account_managed_ = IsProfileManaged(profile) || IsBrowserManaged();
#endif // defined(OS_CHROMEOS)
web_ui->AddMessageHandler(std::move(handler));
}
void ManagementUIHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"getContextualManagedData",
base::BindRepeating(&ManagementUIHandler::HandleGetContextualManagedData,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"getExtensions",
base::BindRepeating(&ManagementUIHandler::HandleGetExtensions,
base::Unretained(this)));
#if defined(OS_CHROMEOS)
web_ui()->RegisterMessageCallback(
"getLocalTrustRootsInfo",
base::BindRepeating(&ManagementUIHandler::HandleGetLocalTrustRootsInfo,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"getDeviceReportingInfo",
base::BindRepeating(&ManagementUIHandler::HandleGetDeviceReportingInfo,
base::Unretained(this)));
#endif // defined(OS_CHROMEOS)
web_ui()->RegisterMessageCallback(
"getThreatProtectionInfo",
base::BindRepeating(&ManagementUIHandler::HandleGetThreatProtectionInfo,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"initBrowserReportingInfo",
base::BindRepeating(&ManagementUIHandler::HandleInitBrowserReportingInfo,
base::Unretained(this)));
}
void ManagementUIHandler::OnJavascriptAllowed() {
AddObservers();
}
void ManagementUIHandler::OnJavascriptDisallowed() {
RemoveObservers();
}
void ManagementUIHandler::AddReportingInfo(base::Value* report_sources) {
const extensions::Extension* cloud_reporting_extension =
GetEnabledExtension(kCloudReportingExtensionId);
const policy::PolicyService* policy_service = GetPolicyService();
const policy::PolicyNamespace
on_prem_reporting_extension_stable_policy_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_EXTENSIONS,
kOnPremReportingExtensionStableId);
const policy::PolicyNamespace
on_prem_reporting_extension_beta_policy_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_EXTENSIONS,
kOnPremReportingExtensionBetaId);
const policy::PolicyMap& on_prem_reporting_extension_stable_policy_map =
policy_service->GetPolicies(
on_prem_reporting_extension_stable_policy_namespace);
const policy::PolicyMap& on_prem_reporting_extension_beta_policy_map =
policy_service->GetPolicies(
on_prem_reporting_extension_beta_policy_namespace);
const policy::PolicyMap* policy_maps[] = {
&on_prem_reporting_extension_stable_policy_map,
&on_prem_reporting_extension_beta_policy_map};
const bool cloud_reporting_extension_installed =
cloud_reporting_extension != nullptr;
const auto* cloud_reporting_policy_value =
GetPolicyService()
->GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
std::string()))
.GetValue(policy::key::kCloudReportingEnabled);
const bool cloud_reporting_policy_enabled =
cloud_reporting_policy_value && cloud_reporting_policy_value->is_bool() &&
cloud_reporting_policy_value->GetBool();
const struct {
const char* policy_key;
const char* message;
const ReportingType reporting_type;
const bool enabled_by_default;
} report_definitions[] = {
{kPolicyKeyReportMachineIdData, kManagementExtensionReportMachineName,
ReportingType::kDevice,
cloud_reporting_extension_installed || cloud_reporting_policy_enabled},
{kPolicyKeyReportMachineIdData,
kManagementExtensionReportMachineNameAddress, ReportingType::kDevice,
false},
{kPolicyKeyReportVersionData, kManagementExtensionReportVersion,
ReportingType::kDevice,
cloud_reporting_extension_installed || cloud_reporting_policy_enabled},
{kPolicyKeyReportSystemTelemetryData, kManagementExtensionReportPerfCrash,
ReportingType::kDevice, false},
{kPolicyKeyReportUserIdData, kManagementExtensionReportUsername,
ReportingType::kUser,
cloud_reporting_extension_installed || cloud_reporting_policy_enabled},
{kPolicyKeyReportSafeBrowsingData,
kManagementExtensionReportSafeBrowsingWarnings, ReportingType::kSecurity,
cloud_reporting_extension_installed},
{kPolicyKeyReportExtensionsData,
kManagementExtensionReportExtensionsPlugin, ReportingType::kExtensions,
cloud_reporting_extension_installed || cloud_reporting_policy_enabled},
{kPolicyKeyReportUserBrowsingData,
kManagementExtensionReportUserBrowsingData, ReportingType::kUserActivity,
false},
};
std::unordered_set<const char*> enabled_messages;
for (auto& report_definition : report_definitions) {
if (report_definition.enabled_by_default) {
enabled_messages.insert(report_definition.message);
} else if (report_definition.policy_key) {
for (const policy::PolicyMap* policy_map : policy_maps) {
const base::Value* policy_value =
policy_map->GetValue(report_definition.policy_key);
if (policy_value && policy_value->is_bool() &&
policy_value->GetBool()) {
enabled_messages.insert(report_definition.message);
break;
}
}
}
}
// The message with more data collected for kPolicyKeyReportMachineIdData
// trumps the one with less data.
if (enabled_messages.find(kManagementExtensionReportMachineNameAddress) !=
enabled_messages.end()) {
enabled_messages.erase(kManagementExtensionReportMachineName);
}
for (auto& report_definition : report_definitions) {
if (enabled_messages.find(report_definition.message) ==
enabled_messages.end()) {
continue;
}
base::Value data(base::Value::Type::DICTIONARY);
data.SetKey("messageId", base::Value(report_definition.message));
data.SetKey(
"reportingType",
base::Value(GetReportingTypeValue(report_definition.reporting_type)));
report_sources->Append(std::move(data));
}
}
#if defined(OS_CHROMEOS)
const policy::DeviceCloudPolicyManagerChromeOS*
ManagementUIHandler::GetDeviceCloudPolicyManager() const {
// Only check for report status in managed environment.
if (!device_managed_)
return nullptr;
const policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
return connector->GetDeviceCloudPolicyManager();
}
void ManagementUIHandler::AddDeviceReportingInfo(
base::Value* report_sources,
const policy::StatusCollector* collector,
const policy::SystemLogUploader* uploader,
Profile* profile) const {
if (!collector || !profile || !uploader)
return;
// Elements appear on the page in the order they are added.
if (collector->ShouldReportActivityTimes()) {
AddDeviceReportingElement(report_sources, kManagementReportActivityTimes,
DeviceReportingType::kDeviceActivity);
} else {
if (collector->ShouldReportUsers()) {
AddDeviceReportingElement(report_sources, kManagementReportUsers,
DeviceReportingType::kSupervisedUser);
}
}
if (collector->ShouldReportHardwareStatus()) {
AddDeviceReportingElement(report_sources, kManagementReportHardwareStatus,
DeviceReportingType::kDeviceStatistics);
}
if (collector->ShouldReportNetworkInterfaces()) {
AddDeviceReportingElement(report_sources,
kManagementReportNetworkInterfaces,
DeviceReportingType::kDevice);
}
if (collector->ShouldReportCrashReportInfo()) {
AddDeviceReportingElement(report_sources, kManagementReportCrashReports,
DeviceReportingType::kCrashReport);
}
if (collector->ShouldReportAppInfoAndActivity()) {
AddDeviceReportingElement(report_sources,
kManagementReportAppInfoAndActivity,
DeviceReportingType::kAppInfoAndActivity);
}
if (uploader->upload_enabled()) {
AddDeviceReportingElement(report_sources, kManagementLogUploadEnabled,
DeviceReportingType::kLogs);
}
if (profile->GetPrefs()->GetBoolean(
prefs::kPrintingSendUsernameAndFilenameEnabled)) {
AddDeviceReportingElement(report_sources, kManagementPrinting,
DeviceReportingType::kPrint);
}
if (crostini::CrostiniFeatures::Get()->IsAllowed(profile)) {
if (!profile->GetPrefs()
->GetFilePath(crostini::prefs::kCrostiniAnsiblePlaybookFilePath)
.empty()) {
AddDeviceReportingElement(report_sources,
kManagementCrostiniContainerConfiguration,
DeviceReportingType::kCrostini);
} else if (profile->GetPrefs()->GetBoolean(
crostini::prefs::kReportCrostiniUsageEnabled)) {
AddDeviceReportingElement(report_sources, kManagementCrostini,
DeviceReportingType::kCrostini);
}
}
if (g_browser_process->local_state()->GetBoolean(
prefs::kCloudReportingEnabled) &&
base::FeatureList::IsEnabled(features::kEnterpriseReportingInChromeOS)) {
AddDeviceReportingElement(report_sources,
kManagementExtensionReportUsername,
DeviceReportingType::kUsername);
AddDeviceReportingElement(report_sources, kManagementReportExtensions,
DeviceReportingType::kExtensions);
AddDeviceReportingElement(report_sources,
kManagementReportAndroidApplications,
DeviceReportingType::kAndroidApplication);
}
chromeos::NetworkHandler* network_handler = chromeos::NetworkHandler::Get();
base::Value proxy_settings(base::Value::Type::DICTIONARY);
// |ui_proxy_config_service| may be missing in tests. If the device is offline
// (no network connected) the |DefaultNetwork| is null.
if (network_handler->has_ui_proxy_config_service() &&
network_handler->network_state_handler()->DefaultNetwork()) {
// Check if proxy is enforced by user policy, a forced install extension or
// ONC policies. This will only read managed settings.
network_handler->ui_proxy_config_service()->MergeEnforcedProxyConfig(
network_handler->network_state_handler()->DefaultNetwork()->guid(),
&proxy_settings);
}
if (!proxy_settings.DictEmpty()) {
// Proxies can be specified by web server url, via a PAC script or via the
// web proxy auto-discovery protocol. Chrome also supports the "direct"
// mode, in which no proxy is used.
base::Value* proxy_specification_mode = proxy_settings.FindPath(
{::onc::network_config::kType, ::onc::kAugmentationActiveSetting});
bool use_proxy =
proxy_specification_mode &&
proxy_specification_mode->GetString() != ::onc::proxy::kDirect;
if (use_proxy) {
AddDeviceReportingElement(report_sources, kManagementReportProxyServer,
DeviceReportingType::kProxyServer);
}
}
}
#endif
base::Value ManagementUIHandler::GetContextualManagedData(Profile* profile) {
base::Value response(base::Value::Type::DICTIONARY);
#if defined(OS_CHROMEOS)
std::string management_domain = GetDeviceDomain();
if (management_domain.empty())
management_domain = GetAccountDomain(profile);
#else
std::string management_domain = GetAccountDomain(profile);
response.SetStringPath(
"browserManagementNotice",
l10n_util::GetStringFUTF16(
managed_() ? IDS_MANAGEMENT_BROWSER_NOTICE
: IDS_MANAGEMENT_NOT_MANAGED_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
#endif
if (management_domain.empty()) {
response.SetStringPath(
"extensionReportingTitle",
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
#if !defined(OS_CHROMEOS)
response.SetStringPath(
"pageSubtitle", l10n_util::GetStringUTF16(
managed_() ? IDS_MANAGEMENT_SUBTITLE
: IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE));
#else
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
response.SetStringPath(
"pageSubtitle",
managed_()
? l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED,
l10n_util::GetStringUTF16(device_type))
: l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE,
l10n_util::GetStringUTF16(device_type)));
#endif // !defined(OS_CHROMEOS)
} else {
response.SetStringPath(
"extensionReportingTitle",
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
base::UTF8ToUTF16(management_domain)));
#if !defined(OS_CHROMEOS)
response.SetStringPath(
"pageSubtitle",
managed_()
? l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
base::UTF8ToUTF16(management_domain))
: l10n_util::GetStringUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE));
#else
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
response.SetStringPath(
"pageSubtitle",
managed_()
? l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
l10n_util::GetStringUTF16(device_type),
base::UTF8ToUTF16(management_domain))
: l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE,
l10n_util::GetStringUTF16(device_type)));
#endif // !defined(OS_CHROMEOS)
}
response.SetBoolPath("managed", managed_());
GetManagementStatus(profile, &response);
AsyncUpdateLogo();
if (!fetched_image_.empty())
response.SetPath(kCustomerLogo, base::Value(fetched_image_));
return response;
}
base::Value ManagementUIHandler::GetThreatProtectionInfo(
Profile* profile) const {
base::Value info(base::Value::Type::LIST);
const policy::PolicyService* policy_service = GetPolicyService();
const auto& chrome_policies = policy_service->GetPolicies(
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()));
auto* on_file_attached =
chrome_policies.GetValue(policy::key::kOnFileAttachedEnterpriseConnector);
if (on_file_attached && on_file_attached->is_list() &&
!on_file_attached->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementOnFileAttachedEvent);
value.SetStringKey("permission", kManagementOnFileAttachedVisibleData);
info.Append(std::move(value));
}
auto* on_file_downloaded = chrome_policies.GetValue(
policy::key::kOnFileDownloadedEnterpriseConnector);
if (on_file_downloaded && on_file_downloaded->is_list() &&
!on_file_downloaded->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementOnFileDownloadedEvent);
value.SetStringKey("permission", kManagementOnFileDownloadedVisibleData);
info.Append(std::move(value));
}
auto* on_bulk_data_entry = chrome_policies.GetValue(
policy::key::kOnBulkDataEntryEnterpriseConnector);
if (on_bulk_data_entry && on_bulk_data_entry->is_list() &&
!on_bulk_data_entry->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementOnBulkDataEntryEvent);
value.SetStringKey("permission", kManagementOnBulkDataEntryVisibleData);
info.Append(std::move(value));
}
auto* on_security_event = chrome_policies.GetValue(
policy::key::kOnSecurityEventEnterpriseConnector);
if (on_security_event && on_security_event->is_list() &&
!on_security_event->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementEnterpriseReportingEvent);
value.SetStringKey("permission", kManagementEnterpriseReportingVisibleData);
info.Append(std::move(value));
}
#if defined(OS_CHROMEOS)
std::string management_domain = GetDeviceDomain();
if (management_domain.empty())
management_domain = GetAccountDomain(profile);
#else
std::string management_domain = GetAccountDomain(profile);
#endif // defined(OS_CHROMEOS)
base::Value result(base::Value::Type::DICTIONARY);
result.SetStringKey("description",
management_domain.empty()
? l10n_util::GetStringUTF16(
IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION)
: l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION_BY,
base::UTF8ToUTF16(management_domain)));
result.SetKey("info", std::move(info));
return result;
}
policy::PolicyService* ManagementUIHandler::GetPolicyService() const {
return Profile::FromWebUI(web_ui())
->GetProfilePolicyConnector()
->policy_service();
}
const extensions::Extension* ManagementUIHandler::GetEnabledExtension(
const std::string& extensionId) const {
return extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
->GetExtensionById(kCloudReportingExtensionId,
extensions::ExtensionRegistry::ENABLED);
}
void ManagementUIHandler::AsyncUpdateLogo() {
#if defined(OS_CHROMEOS)
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
const auto url = connector->GetCustomerLogoURL();
if (!url.empty() && GURL(url) != logo_url_) {
icon_fetcher_ = std::make_unique<BitmapFetcher>(
GURL(url), this, GetManagementUICustomerLogoAnnotation());
icon_fetcher_->Init(std::string(), net::URLRequest::NEVER_CLEAR_REFERRER,
network::mojom::CredentialsMode::kOmit);
auto* profile = Profile::FromWebUI(web_ui());
icon_fetcher_->Start(
content::BrowserContext::GetDefaultStoragePartition(profile)
->GetURLLoaderFactoryForBrowserProcess()
.get());
}
#endif // defined(OS_CHROMEOS)
}
void ManagementUIHandler::OnFetchComplete(const GURL& url,
const SkBitmap* bitmap) {
if (!bitmap)
return;
fetched_image_ = webui::GetBitmapDataUrl(*bitmap);
logo_url_ = url;
// Fire listener to reload managed data.
FireWebUIListener("managed_data_changed");
}
#if defined(OS_CHROMEOS)
void AddStatusOverviewManagedDeviceAndAccount(
base::Value* status,
bool device_managed,
bool account_managed,
const std::string& device_domain,
const std::string& account_domain) {
if (device_managed && account_managed &&
(account_domain.empty() || account_domain == device_domain)) {
status->SetKey(kOverview, base::Value(l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_DEVICE_AND_ACCOUNT_MANAGED_BY,
base::UTF8ToUTF16(device_domain))));
return;
}
if (account_managed && !account_domain.empty()) {
status->SetKey(kOverview, base::Value(l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_ACCOUNT_MANAGED_BY,
base::UTF8ToUTF16(account_domain))));
}
if (account_managed && device_managed && !account_domain.empty() &&
account_domain != device_domain) {
status->SetKey(kOverview,
base::Value(l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_DEVICE_MANAGED_BY_ACCOUNT_MANAGED_BY,
base::UTF8ToUTF16(device_domain),
base::UTF8ToUTF16(account_domain))));
}
}
const std::string ManagementUIHandler::GetDeviceDomain() const {
std::string device_domain;
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
if (device_managed_)
device_domain = connector->GetEnterpriseDisplayDomain();
if (device_domain.empty() && connector->IsActiveDirectoryManaged())
device_domain = connector->GetRealm();
return device_domain;
}
#endif // defined(OS_CHROMEOS)
void ManagementUIHandler::GetManagementStatus(Profile* profile,
base::Value* status) const {
#if defined(OS_CHROMEOS)
status->SetKey(kDeviceManagedInfo, base::Value());
status->SetKey(kAccountManagedInfo, base::Value());
status->SetKey(kOverview, base::Value());
if (!managed_()) {
status->SetKey(kOverview, base::Value(l10n_util::GetStringUTF16(
IDS_MANAGEMENT_DEVICE_NOT_MANAGED)));
return;
}
std::string account_domain = GetAccountDomain(profile);
auto* primary_user = user_manager::UserManager::Get()->GetPrimaryUser();
auto* primary_profile =
primary_user
? chromeos::ProfileHelper::Get()->GetProfileByUser(primary_user)
: nullptr;
const bool primary_user_managed =
primary_profile ? IsProfileManaged(primary_profile) : false;
if (primary_user_managed)
account_domain = GetAccountDomain(primary_profile);
std::string device_domain = GetDeviceDomain();
AddStatusOverviewManagedDeviceAndAccount(
status, device_managed_, account_managed_ || primary_user_managed,
device_domain, account_domain);
#endif // defined(OS_CHROMEOS)
}
void ManagementUIHandler::HandleGetExtensions(const base::ListValue* args) {
AllowJavascript();
// List of all enabled extensions
const extensions::ExtensionSet& extensions =
extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
->enabled_extensions();
base::Value powerful_extensions = GetPowerfulExtensions(extensions);
// The number of extensions to be reported in chrome://management with
// powerful permissions.
base::UmaHistogramCounts1000(kPowerfulExtensionsCountHistogram,
powerful_extensions.GetList().size());
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
powerful_extensions);
}
#if defined(OS_CHROMEOS)
void ManagementUIHandler::HandleGetLocalTrustRootsInfo(
const base::ListValue* args) {
CHECK_EQ(1U, args->GetSize());
base::Value trust_roots_configured(false);
AllowJavascript();
policy::PolicyCertService* policy_service =
policy::PolicyCertServiceFactory::GetForProfile(
Profile::FromWebUI(web_ui()));
if (policy_service && policy_service->has_policy_certificates())
trust_roots_configured = base::Value(true);
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
trust_roots_configured);
}
void ManagementUIHandler::HandleGetDeviceReportingInfo(
const base::ListValue* args) {
base::Value report_sources(base::Value::Type::LIST);
AllowJavascript();
const policy::DeviceCloudPolicyManagerChromeOS* manager =
GetDeviceCloudPolicyManager();
policy::StatusUploader* uploader = nullptr;
policy::SystemLogUploader* syslog_uploader = nullptr;
policy::StatusCollector* collector = nullptr;
if (manager) {
uploader = manager->GetStatusUploader();
syslog_uploader = manager->GetSystemLogUploader();
if (uploader)
collector = uploader->status_collector();
}
AddDeviceReportingInfo(&report_sources, collector, syslog_uploader,
Profile::FromWebUI(web_ui()));
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
report_sources);
}
#endif // defined(OS_CHROMEOS)
void ManagementUIHandler::HandleGetContextualManagedData(
const base::ListValue* args) {
AllowJavascript();
auto result = GetContextualManagedData(Profile::FromWebUI(web_ui()));
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
std::move(result));
}
void ManagementUIHandler::HandleGetThreatProtectionInfo(
const base::ListValue* args) {
AllowJavascript();
ResolveJavascriptCallback(
args->GetList()[0] /* callback_id */,
GetThreatProtectionInfo(Profile::FromWebUI(web_ui())));
}
void ManagementUIHandler::HandleInitBrowserReportingInfo(
const base::ListValue* args) {
base::Value report_sources(base::Value::Type::LIST);
AllowJavascript();
AddReportingInfo(&report_sources);
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
report_sources);
}
void ManagementUIHandler::NotifyBrowserReportingInfoUpdated() {
base::Value report_sources(base::Value::Type::LIST);
AddReportingInfo(&report_sources);
FireWebUIListener("browser-reporting-info-updated", report_sources);
}
void ManagementUIHandler::NotifyThreatProtectionInfoUpdated() {
FireWebUIListener("threat-protection-info-updated",
GetThreatProtectionInfo(Profile::FromWebUI(web_ui())));
}
void ManagementUIHandler::OnExtensionLoaded(
content::BrowserContext* /*browser_context*/,
const extensions::Extension* extension) {
if (reporting_extension_ids_.find(extension->id()) !=
reporting_extension_ids_.end()) {
NotifyBrowserReportingInfoUpdated();
}
}
void ManagementUIHandler::OnExtensionUnloaded(
content::BrowserContext* /*browser_context*/,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason /*reason*/) {
if (reporting_extension_ids_.find(extension->id()) !=
reporting_extension_ids_.end()) {
NotifyBrowserReportingInfoUpdated();
}
}
void ManagementUIHandler::UpdateManagedState() {
auto* profile = Profile::FromWebUI(web_ui());
bool managed_state_changed = false;
#if defined(OS_CHROMEOS)
managed_state_changed |= account_managed_ != IsProfileManaged(profile);
managed_state_changed |= device_managed_ != IsDeviceManaged();
account_managed_ = IsProfileManaged(profile);
device_managed_ = IsDeviceManaged();
#else
managed_state_changed |=
account_managed_ != (IsProfileManaged(profile) || IsBrowserManaged());
account_managed_ = IsProfileManaged(profile) || IsBrowserManaged();
#endif // defined(OS_CHROMEOS)
if (managed_state_changed)
FireWebUIListener("managed_data_changed");
}
void ManagementUIHandler::OnPolicyUpdated(
const policy::PolicyNamespace& /*ns*/,
const policy::PolicyMap& /*previous*/,
const policy::PolicyMap& /*current*/) {
UpdateManagedState();
NotifyBrowserReportingInfoUpdated();
NotifyThreatProtectionInfoUpdated();
}
void ManagementUIHandler::AddObservers() {
if (has_observers_)
return;
has_observers_ = true;
auto* profile = Profile::FromWebUI(web_ui());
extensions::ExtensionRegistry::Get(profile)->AddObserver(this);
auto* policy_service = GetPolicyService();
policy_service->AddObserver(policy::POLICY_DOMAIN_EXTENSIONS, this);
pref_registrar_.Init(profile->GetPrefs());
pref_registrar_.Add(
prefs::kSupervisedUserId,
base::BindRepeating(&ManagementUIHandler::UpdateManagedState,
base::Unretained(this)));
}
void ManagementUIHandler::RemoveObservers() {
if (!has_observers_)
return;
has_observers_ = false;
extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
->RemoveObserver(this);
policy::PolicyService* policy_service = Profile::FromWebUI(web_ui())
->GetProfilePolicyConnector()
->policy_service();
policy_service->RemoveObserver(policy::POLICY_DOMAIN_EXTENSIONS, this);
pref_registrar_.RemoveAll();
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1da4ef9bb7585a2ed949b319cbe10897549799aa | 9a1fba32fe46c41b450222e6f45408e53d9b6c23 | /tools/aapt2/BigBuffer.cpp | 8f571728d729399a0d224912e72df48d991d80e1 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | FireHound/android_frameworks_base | 779dda285e75a615d75150b8c10c21d13fa3e731 | e9d54decbb07004f74e78b57f095f614362828b5 | refs/heads/mm | 2021-11-26T05:13:54.745879 | 2016-09-10T05:37:47 | 2016-12-18T06:50:12 | 64,948,641 | 4 | 38 | NOASSERTION | 2020-03-14T21:24:38 | 2016-08-04T16:06:28 | Java | UTF-8 | C++ | false | false | 1,462 | cpp | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 "BigBuffer.h"
#include <algorithm>
#include <memory>
#include <vector>
namespace aapt {
void* BigBuffer::nextBlockImpl(size_t size) {
if (!mBlocks.empty()) {
Block& block = mBlocks.back();
if (block.mBlockSize - block.size >= size) {
void* outBuffer = block.buffer.get() + block.size;
block.size += size;
mSize += size;
return outBuffer;
}
}
const size_t actualSize = std::max(mBlockSize, size);
Block block = {};
// Zero-allocate the block's buffer.
block.buffer = std::unique_ptr<uint8_t[]>(new uint8_t[actualSize]());
assert(block.buffer);
block.size = size;
block.mBlockSize = actualSize;
mBlocks.push_back(std::move(block));
mSize += size;
return mBlocks.back().buffer.get();
}
} // namespace aapt
| [
"adamlesinski@google.com"
] | adamlesinski@google.com |
d750ed7b54f1aa500b32086adc14845e2a12e08d | dac5254630fefae851da7c843dcab7f6a6af9703 | /Sources_Common/Calendar_Store/Clients/CLocalCalendarClient.cpp | 50fb582caff0e596b3f0b3a00f506c6221a8401b | [
"Apache-2.0"
] | permissive | gpreviato/Mulberry-Mail | dd4e3618468fff36361bd2aeb0a725593faa0f8d | ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a | refs/heads/master | 2021-01-20T03:31:39.515653 | 2017-09-21T13:09:55 | 2017-09-21T13:09:55 | 18,178,314 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 18,029 | cpp | /*
Copyright (c) 2007-2009 Cyrus Daboo. 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.
*/
/*
CLocalCalendarClient.cpp
Author:
Description: <describe the CLocalCalendarClient class here>
*/
#include "CLocalCalendarClient.h"
#include "CCalendarAccount.h"
#include "CCalendarProtocol.h"
#include "CCalendarRecord.h"
#include "CCalendarStoreNode.h"
#include "CCalendarStoreWebcal.h"
#include "CDisplayItem.h"
#include "CGeneralException.h"
#include "CLocalCommon.h"
#include "CICalendar.h"
#if __dest_os == __win32_os || __dest_os == __linux_os
#include "StValueChanger.h"
#endif
#include "diriterator.h"
#include "cdfstream.h"
#include __stat_header
using namespace calstore;
CLocalCalendarClient::CLocalCalendarClient(CCalendarProtocol* owner) :
CCalendarClient(owner)
{
// Init instance variables
InitLocalClient();
}
CLocalCalendarClient::CLocalCalendarClient(const CLocalCalendarClient& copy, CCalendarProtocol* owner) :
CCalendarClient(copy, owner)
{
// Init instance variables
InitLocalClient();
mCWD = copy.mCWD;
mRecorder = copy.mRecorder;
}
CLocalCalendarClient::~CLocalCalendarClient()
{
mRecorder = NULL;
}
void CLocalCalendarClient::InitLocalClient()
{
// Protocol that can disconnect will always be cached
mCaching = GetCalendarProtocol()->CanDisconnect();
mRecorder = NULL;
mRecordID = 0;
}
// Create duplicate, empty connection
CINETClient* CLocalCalendarClient::CloneConnection()
{
// Copy construct this
return new CLocalCalendarClient(*this, GetCalendarProtocol());
}
bool CLocalCalendarClient::IsCaching() const
{
return mCaching;
}
#pragma mark ____________________________Start/Stop
// Start TCP
void CLocalCalendarClient::Open()
{
// Do account reset
Reset();
}
// Reset acount info
void CLocalCalendarClient::Reset()
{
// get CWD from owner
mCWD = GetCalendarProtocol()->GetOfflineCWD();
// Must append dir delim if not present
if (mCWD.length() && (mCWD[mCWD.length() - 1] != os_dir_delim))
mCWD += os_dir_delim;
// May need to check for INBOX on POP3
CheckCWD();
}
// Check CWD
void CLocalCalendarClient::CheckCWD()
{
// Local does nothing
}
// Release TCP
void CLocalCalendarClient::Close()
{
// Local does nothing
}
// Program initiated abort
void CLocalCalendarClient::Abort()
{
}
// Forced close
void CLocalCalendarClient::Forceoff()
{
}
#pragma mark ____________________________Login & Logout
void CLocalCalendarClient::Logon()
{
// Local does nothing
// Must fail if empty CWD
if (mCWD.empty())
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
void CLocalCalendarClient::Logoff()
{
// Nothing to do for local
}
#pragma mark ____________________________Handle Errors
// Descriptor for object error context
const char* CLocalCalendarClient::INETGetErrorDescriptor() const
{
return "Calendar: ";
}
#pragma mark ____________________________Protocol
// Tickle to keep connection alive
void CLocalCalendarClient::_Tickle(bool force_tickle)
{
// Local does nothing
}
void CLocalCalendarClient::_ListCalendars(CCalendarStoreNode* root)
{
// Node must be protocol or directory
if (!root->IsProtocol() && !root->IsDirectory())
return;
// Get name for new file
cdstring fpath = MapName(*root);
// Directory scan starting at the root
ListCalendars(root, fpath);
// Always sort children after adding all of them
root->SortChildren();
}
void CLocalCalendarClient::ListCalendars(CCalendarStoreNode* root, const cdstring& path)
{
// Directory scan
diriterator _dir(path, true, ".ics");
const char* fname = NULL;
while(_dir.next(&fname))
{
// Get the full path of the found item
cdstring fpath(path);
::addtopath(fpath, fname);
// Get the relative path which will be the name of the node.
// This is relative to the root path for this client.
cdstring rpath(fpath, mCWD.length());
// Strip off trailing .ics
if (rpath.compare_end(".ics"))
rpath.erase(rpath.length() - 4);
// Create the new node and add to parent
CCalendarStoreNode* node = new CCalendarStoreNode(GetCalendarProtocol(), root, _dir.is_dir(), false, false, rpath);
root->AddChild(node);
// Scan into directories
if (_dir.is_dir())
{
// Use new node as the root
ListCalendars(node, fpath);
// Always mark node as ahving been expanded
node->SetHasExpanded(true);
// Always sort the children after adding all of them
node->SortChildren();
}
}
}
void CLocalCalendarClient::_CreateCalendar(const CCalendarStoreNode& node)
{
// Get name for new file
cdstring fpath = MapName(node);
// Make sure it does not already exist
if (::fileexists(fpath) || ::direxists(fpath))
{
//throw CGeneralException(-1, "Calendar file/directory exists");
throw CGeneralException(-1);
}
// Must ensure entire path exists
{
cdstring convert = LocalFileName(node.GetName(), GetCalendarProtocol()->GetDirDelim(), GetCalendarProtocol()->IsDisconnectedCache());
if (!node.IsDirectory())
convert += ".ics";
cdstring mbox_name = mCWD;
cdstring dir_delim = os_dir_delim;
char* dir = ::strtok(convert.c_str_mod(), dir_delim);
char* next_dir = ::strtok(NULL, dir_delim);
while(dir && next_dir)
{
mbox_name += dir;
::chkdir(mbox_name);
mbox_name += os_dir_delim;
dir = next_dir;
next_dir = ::strtok(NULL, dir_delim);
}
}
if (node.IsDirectory())
{
if (__mkdir(fpath, S_IRWXU))
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not create directory");
throw CGeneralException(my_errno);
}
}
else
{
FILE* file;
if ((file = ::fopen_utf8(fpath, "ab")) != NULL)
::fclose(file);
else
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not create calendar file");
throw CGeneralException(my_errno);
}
// Always clear any existing cache file as a precaution
if (IsCaching())
{
cdstring cpath = MapCacheName(node);
if (::fileexists(cpath))
::remove_utf8(cpath);
}
}
// Record action
if (mRecorder)
{
CActionRecorder::StActionRecorder record(mRecorder, mRecordID);
mRecorder->Create(node);
}
}
void CLocalCalendarClient::_DeleteCalendar(const CCalendarStoreNode& node)
{
// Get name for new file
cdstring fpath = MapName(node);
if (node.IsDirectory())
{
// Make sure it already exists
if (!::direxists(fpath))
{
//throw CGeneralException(-1, "Directory being deleted does not exist");
throw CGeneralException(-1);
}
// Make sure it is empty
if (::count_dir_contents(fpath) != 0)
{
//throw CGeneralException(-1, "Directory being deleted is not empty");
throw CGeneralException(-1);
}
if (::delete_dir(fpath) != 0)
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not delete directory");
throw CGeneralException(my_errno);
}
}
else
{
// Make sure it already exists
if (!::fileexists(fpath))
{
//throw CGeneralException(-1, "Calendar file does not exist");
throw CGeneralException(-1);
}
if (::remove_utf8(fpath) != 0)
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not delete calendar file");
throw CGeneralException(my_errno);
}
// Always clear any existing cache file
if (IsCaching())
{
cdstring cpath = MapCacheName(node);
if (::fileexists(cpath))
::remove_utf8(cpath);
}
}
// Record action
if (mRecorder)
{
CActionRecorder::StActionRecorder record(mRecorder, mRecordID);
mRecorder->Delete(node);
}
}
void CLocalCalendarClient::_RenameCalendar(const CCalendarStoreNode& node, const cdstring& node_new)
{
// Get name for new file
cdstring fpath_old = MapName(node);
cdstring convert = LocalFileName(node_new, GetCalendarProtocol()->GetDirDelim(), GetCalendarProtocol()->IsDisconnectedCache());
cdstring fpath_new = MapName(convert, node.IsDirectory());
if (node.IsDirectory())
{
// Make sure old already exists
if (!::direxists(fpath_old))
{
//throw CGeneralException(-1, "Directory being renamed does not exist");
throw CGeneralException(-1);
}
// Make sure new does not already exist
if (::direxists(fpath_new))
{
//throw CGeneralException(-1, "Directory being renamed to exists");
throw CGeneralException(-1);
}
if (::rename_utf8(fpath_old, fpath_new) != 0)
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not rename directory");
throw CGeneralException(my_errno);
}
}
else
{
// Make sure old already exists
if (!::fileexists(fpath_old))
{
//throw CGeneralException(-1, "Calendar file being renamed does not exist");
throw CGeneralException(-1);
}
// Make sure new does not already exist
if (::fileexists(fpath_new))
{
//throw CGeneralException(-1, "Calendar file being renamed to exists");
throw CGeneralException(-1);
}
if (::rename_utf8(fpath_old, fpath_new) != 0)
{
int my_errno = os_errno;
//throw CGeneralException(_errno, "Could not rename calendar file");
throw CGeneralException(my_errno);
}
// Always rename any existing cache file
if (IsCaching())
{
cdstring cpath_old = MapCacheName(node);
cdstring cpath_new = MapCacheName(convert, node.IsDirectory());
if (::fileexists(cpath_old))
{
// Delete existing cache file as a precaution
if (::fileexists(cpath_new))
::remove_utf8(cpath_new);
// Rename cache file
::rename_utf8(cpath_old, cpath_new);
}
}
}
// Record action
if (mRecorder)
{
CActionRecorder::StActionRecorder record(mRecorder, mRecordID);
mRecorder->Rename(node, node_new);
}
}
bool CLocalCalendarClient::_TestCalendar(const CCalendarStoreNode& node)
{
// Get name for new file
cdstring fpath = MapName(node);
// Make sure it already exists
if (node.IsDirectory())
{
return ::direxists(fpath);
}
else
{
return ::fileexists(fpath);
}
}
bool CLocalCalendarClient::_TouchCalendar(const CCalendarStoreNode& node)
{
if (!_TestCalendar(node))
{
StValueChanger<CCalendarRecord*> value(mRecorder, NULL);
_CreateCalendar(node);
return true;
}
else
return false;
}
void CLocalCalendarClient::_LockCalendar(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Nothing to do
}
void CLocalCalendarClient::_UnlockCalendar(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Nothing to do
}
bool CLocalCalendarClient::_CheckCalendar(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Nothing to do for local
return false;
}
bool CLocalCalendarClient::_CalendarChanged(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Nothing to do for local as this is only used when sync'ing with server
return false;
}
void CLocalCalendarClient::_UpdateSyncToken(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Nothing to do for local as this is only used when sync'ing with server
}
void CLocalCalendarClient::_SizeCalendar(CCalendarStoreNode& node)
{
// Does it exist on disk?
if (_TestCalendar(node))
{
cdstring fpath = MapName(node);
// Get sizes
unsigned long size = 0;
struct stat finfo;
if (::stat_utf8(fpath, &finfo))
{
int my_errno = os_errno;
CLOG_LOGTHROW(CGeneralException, my_errno);
throw CGeneralException(my_errno);
}
else
size += finfo.st_size;
// Add cache file if present
if (IsCaching())
{
cdstring cpath = MapCacheName(node);
if (!::stat_utf8(cpath, &finfo))
size += finfo.st_size;
}
node.SetSize(size);
}
else
// Not cached => size = 0
node.SetSize(0);
}
void CLocalCalendarClient::_ReadFullCalendar(const CCalendarStoreNode& node, iCal::CICalendar& cal, bool if_changed)
{
// Get name for new file
cdstring fpath = MapName(node);
// Make sure it already exists
if (!::fileexists(fpath))
{
//throw CGeneralException(-1, "Calendar file does not exist");
throw CGeneralException(-1);
}
// Read calendar from file
cdifstream is(fpath);
cal.Parse(is);
// Get read-only state
cal.SetReadOnly(!::filereadwriteable(fpath));
if (node.GetWebcal() && node.GetWebcal()->GetReadOnly())
cal.SetReadOnly(true);
// Load cache file
if (IsCaching())
{
cdstring cpath = MapCacheName(node);
cdifstream cis(cpath);
cal.ParseCache(cis);
}
}
void CLocalCalendarClient::_WriteFullCalendar(const CCalendarStoreNode& node, iCal::CICalendar& cal)
{
// Get name for new file
cdstring fpath = MapName(node);
cdstring cpath = MapCacheName(node);
// Make sure it already exists
if (!::fileexists(fpath))
{
//throw CGeneralException(-1, "Calendar file does not exist");
throw CGeneralException(-1);
}
// Make sure its writeable
if (!::filereadwriteable(fpath))
{
//throw CGeneralException(-1, "Calendar file not writeable");
throw CGeneralException(-1);
}
// Transactional write
cdstring fpath_tmp(fpath);
fpath_tmp += ".tmp";
cdstring cpath_tmp(cpath);
cpath_tmp += ".tmp";
// Create the file and write calendar to it
{
cdofstream os(fpath_tmp);
cal.Generate(os, IsCaching());
}
// Write cache file
if (IsCaching())
{
cdofstream cos(cpath_tmp);
cal.GenerateCache(cos);
}
// Remove old and rename the new
::remove_utf8(fpath);
::rename_utf8(fpath_tmp, fpath);
::remove_utf8(cpath);
::rename_utf8(cpath_tmp, cpath);
// Record action
if (mRecorder)
{
CActionRecorder::StActionRecorder record(mRecorder, mRecordID);
mRecorder->Change(node);
}
}
bool CLocalCalendarClient::_CanUseComponents() const
{
// Only handles entire calendar files
return false;
}
void CLocalCalendarClient::_TestFastSync(const CCalendarStoreNode& node)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_FastSync(const CCalendarStoreNode& node, iCal::CICalendar& cal, cdstrmap& changed, cdstrset& removed, cdstring& synctoken)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_GetComponentInfo(const CCalendarStoreNode& node, iCal::CICalendar& cal, cdstrmap& comps)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_AddComponent(const CCalendarStoreNode& node, iCal::CICalendar& cal, const iCal::CICalendarComponent& component)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_ChangeComponent(const CCalendarStoreNode& node, iCal::CICalendar& cal, const iCal::CICalendarComponent& component)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_RemoveComponent(const CCalendarStoreNode& node, iCal::CICalendar& cal, const iCal::CICalendarComponent& component)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_RemoveComponent(const CCalendarStoreNode& node, iCal::CICalendar& cal, const cdstring& rurl)
{
// Does nothing in this implementation
}
void CLocalCalendarClient::_ReadComponents(const CCalendarStoreNode& node, iCal::CICalendar& cal, const cdstrvect& rurls)
{
// Does nothing in this implementation
}
iCal::CICalendarComponent* CLocalCalendarClient::_ReadComponent(const CCalendarStoreNode& node, iCal::CICalendar& cal, const cdstring& rurl)
{
// Does nothing in this implementation
return NULL;
}
#pragma mark ____________________________ACLs
// Set acl on server
void CLocalCalendarClient::_SetACL(CCalendarStoreNode& node, CACL* acl)
{
}
// Delete acl on server
void CLocalCalendarClient::_DeleteACL(CCalendarStoreNode& node, CACL* acl)
{
}
// Get all acls for calendar from server
void CLocalCalendarClient::_GetACL(CCalendarStoreNode& node)
{
}
// Get allowed rights for user
void CLocalCalendarClient::_ListRights(CCalendarStoreNode& node, CACL* acl)
{
}
// Get current user's rights to calendar
void CLocalCalendarClient::_MyRights(CCalendarStoreNode& node)
{
}
#pragma mark ____________________________Schedule
// Get Scheduling Inbox/Outbox URIs
void CLocalCalendarClient::_GetScheduleInboxOutbox(const CCalendarStoreNode& node, cdstring& inboxURI, cdstring& outboxURI)
{
}
// Run scheduling request
void CLocalCalendarClient::_Schedule(const cdstring& outboxURI,
const cdstring& originator,
const cdstrvect& recipients,
const iCal::CICalendar& cal,
iCal::CITIPScheduleResultsList& results)
{
}
void CLocalCalendarClient::_GetFreeBusyCalendars(cdstrvect& calendars)
{
}
void CLocalCalendarClient::_SetFreeBusyCalendars(const cdstrvect& calendars)
{
}
#pragma mark ____________________________Utils
cdstring CLocalCalendarClient::MapName(const CCalendarStoreNode& node) const
{
if (node.IsProtocol())
return mCWD;
else
{
cdstring convert = LocalFileName(node.GetName(), GetCalendarProtocol()->GetDirDelim(), GetCalendarProtocol()->IsDisconnectedCache());
return MapName(convert, node.IsDirectory());
}
}
cdstring CLocalCalendarClient::MapName(const cdstring& node_name, bool is_dir) const
{
// Create path from calendar name
cdstring result(mCWD);
::addtopath(result, node_name);
// Always add ".ics" for actual calendars
if (!is_dir)
result += ".ics";
return result;
}
cdstring CLocalCalendarClient::MapCacheName(const CCalendarStoreNode& node) const
{
if (node.IsProtocol())
return mCWD;
else
{
cdstring convert = LocalFileName(node.GetName(), GetCalendarProtocol()->GetDirDelim(), GetCalendarProtocol()->IsDisconnectedCache());
return MapCacheName(convert, node.IsDirectory());
}
}
cdstring CLocalCalendarClient::MapCacheName(const cdstring& node_name, bool is_dir) const
{
// Create path from calendar name
cdstring result(mCWD);
::addtopath(result, node_name);
// Always add ".xml" for actual calendar cache files
if (!is_dir)
result += ".xml";
return result;
}
| [
"svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132"
] | svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132 |
df186dac9ade6de27a8fda6f7bb2ba09e48a05cd | 4876da9c10f3dbb085132b504d03c6ced56b8a0f | /main.cc | 2c2515ce7b4219fb5ebd9b2e636866aff4a5694d | [] | no_license | jicewarwick/MA417 | a237f345b9f4da424f808da02e97cb468a5905ff | a607d5ecaca8ec3f32053ffda6d7f681b4028dd5 | refs/heads/master | 2021-01-19T13:53:05.489122 | 2014-04-13T17:15:36 | 2014-04-13T17:15:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,904 | cc | #include <iostream>
#include "Normals.h"
#include "Sampler.h"
#include "UniformSampler.h"
#include "ExpInvSampler.h"
#include "NormalAccSampler.h"
#include "NormalBoxMullerSampler.h"
#include "BrownianMotion.h"
#include "MonteCarloSimulation.h"
#include "ControlVariates.h"
#include <cmath>
#include <algorithm>
#include <ctime>
double f(double);
double g(double);
int main(){
UniformSampler *U = new UniformSampler();
std::vector<double> u = U->getnumbers(34);
MonteCarloSimulation *uni_sim = new MonteCarloSimulation(*g, U, 1000000);
double uni_mean = uni_sim->simulate();
//Monte Carlo Simulation for \E[e^(-rT)(S(T)-K)]
NormalBoxMullerSampler *W = new NormalBoxMullerSampler();
long n = 10;
double sigma = 0.3;
MonteCarloSimulation *mon_sim = new MonteCarloSimulation(*f, W, n);
double price_call = mon_sim->simulate();
double lower_limit = price_call - InverseCumulativeNormal(.99) * sigma / sqrt(n);
double upper_limit = price_call + InverseCumulativeNormal(.99) * sigma / sqrt(n);
//Control Variates Estimator
ControlVariates call(W, f, n, 0);
//double call_var = call.getCotrolVariatesEstimator();
//clean up
U->~UniformSampler();
std::cout << "Monte Carlo Estimator for mean of Uniform Distribution is " << uni_mean << std::endl;
std::cout << "Monte Carlo Estimator for Call option is " << price_call << std::endl;
std::cout << "With 98\% confidence interval: (" << lower_limit << "," << upper_limit << ")" << std::endl;
//std::cout << "The control variates estimator for Y_i: " << call_var << std::endl;
std::cout << "Antithetic estimator for Y_i: " << std::endl;
return 0;
}
double g(double x){
return x;
}
double f(double x){
double T = 1;
double sigma = 0.3;
double r = 0.05;
double K = 50;
double S0 = 50;
double ret = 0;
ret = exp(-r * T)*(S0 * exp((r - pow(sigma, 2)/ 2.0) * T + sigma * x * sqrt(T)) - K);
ret = std::max(ret, 0.0);
return ret;
}
| [
"jicewarwick@gmail.com"
] | jicewarwick@gmail.com |
0cdd9196c2caf9a3615152aeebf8cd382c6e3096 | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-glacier/source/model/Encryption.cpp | b2460bb73334589847951b60b9ad06b2254b06a9 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 2,256 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/glacier/model/Encryption.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Glacier
{
namespace Model
{
Encryption::Encryption() :
m_encryptionType(EncryptionType::NOT_SET),
m_encryptionTypeHasBeenSet(false),
m_kMSKeyIdHasBeenSet(false),
m_kMSContextHasBeenSet(false)
{
}
Encryption::Encryption(const JsonValue& jsonValue) :
m_encryptionType(EncryptionType::NOT_SET),
m_encryptionTypeHasBeenSet(false),
m_kMSKeyIdHasBeenSet(false),
m_kMSContextHasBeenSet(false)
{
*this = jsonValue;
}
Encryption& Encryption::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("EncryptionType"))
{
m_encryptionType = EncryptionTypeMapper::GetEncryptionTypeForName(jsonValue.GetString("EncryptionType"));
m_encryptionTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("KMSKeyId"))
{
m_kMSKeyId = jsonValue.GetString("KMSKeyId");
m_kMSKeyIdHasBeenSet = true;
}
if(jsonValue.ValueExists("KMSContext"))
{
m_kMSContext = jsonValue.GetString("KMSContext");
m_kMSContextHasBeenSet = true;
}
return *this;
}
JsonValue Encryption::Jsonize() const
{
JsonValue payload;
if(m_encryptionTypeHasBeenSet)
{
payload.WithString("EncryptionType", EncryptionTypeMapper::GetNameForEncryptionType(m_encryptionType));
}
if(m_kMSKeyIdHasBeenSet)
{
payload.WithString("KMSKeyId", m_kMSKeyId);
}
if(m_kMSContextHasBeenSet)
{
payload.WithString("KMSContext", m_kMSContext);
}
return payload;
}
} // namespace Model
} // namespace Glacier
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
f3029d2e89853447c41c34eb99c5243405494f4e | 6573e414ab8da20dcf7ef725f5d1ff60e2bb3030 | /1_5.cpp | 87e29aacc011ee49134c0f6c249b682c9d093885 | [] | no_license | praj1wal/crackingTheCodingInterview | fcd495e2f4800bd46a5c72bddb6e46cb8352d314 | 38d548c78d03f64b2b0f5dab079f08b9ef203151 | refs/heads/master | 2021-04-01T03:46:58.780151 | 2020-03-19T12:10:33 | 2020-03-19T12:10:33 | 248,153,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"hii";
return 0;
} | [
"prajwalkotalwar@gmail.com"
] | prajwalkotalwar@gmail.com |
8d56c504795f25a455f37add536e37c6b6243b68 | 1fc7a6ff8d4f93c9716a2074c71911f192745d95 | /imagelib/cmath/CMathLib.h | 0046082506ea97c54f5fbbc4a8579c103a658960 | [] | no_license | playbar/gllearn | 14dc6e671f5161cac768884771e2a6401a5ed5b7 | 19e20ffd681eadff2559f13a42af12763b00b03e | refs/heads/master | 2021-12-06T05:15:10.299208 | 2021-11-09T11:00:46 | 2021-11-09T11:00:46 | 180,532,777 | 0 | 2 | null | 2020-10-13T12:55:49 | 2019-04-10T08:04:15 | C++ | UTF-8 | C++ | false | false | 1,037 | h | #ifndef CMATH_LIB_H
#define CMATH_LIB_H
namespace CMath {
// test if type is real
template<typename T> struct is_real { enum { Value=-1 }; };
template<> struct is_real<double> { enum { Value=1 }; };
template<> struct is_real<float> { enum { Value=1 }; };
#define ASSERT_IS_REAL(T) { int a[is_real<T>::Value]; }
//---
template<typename T>
int sign(T v) {
return (T(0) < v) - (v < T(0));
}
template<typename T>
T abs(T v) {
return (v >= T(0) ? v : -v);
}
template<typename T>
T avg(T v1, T v2) {
return (v1 + v2)/T(2);
}
template<typename T>
int round(T v) {
ASSERT_IS_REAL(T)
return (v >= T(0) ? int(v+0.5) : int(v-0.5));
}
template<typename T>
bool realEq(T r1, T r2, T tol=1E-6) {
ASSERT_IS_REAL(T)
if (r1 == r2 || abs(r1 - r2) < tol) return true;
return (abs((r1 - r2)/(abs(r2) > abs(r1) ? r2 : r1)) <= tol);
}
template<typename T>
double radToDeg(T v) {
return (double(v)*180.0/M_PI);
}
template<typename T>
double degToRad(T v) {
return (double(v)/180.0*M_PI);
}
#undef ASSERT_IS_REAL
}
#endif
| [
"hgl868@126.com"
] | hgl868@126.com |
e29b8cce2f2009b702311f243aad462d3c8ecca7 | 7396a56d1f6c61b81355fc6cb034491b97feb785 | /algorithms/kernel/logitboost/logitboost_predict_dense_default_kernel.h | 882dbad32c39488c14019b300c7463e77f29726e | [
"Apache-2.0",
"Intel"
] | permissive | francktcheng/daal | 0ad1703be1e628a5e761ae41d2d9f8c0dde7c0bc | 875ddcc8e055d1dd7e5ea51e7c1b39886f9c7b79 | refs/heads/master | 2018-10-01T06:08:39.904147 | 2017-09-20T22:37:02 | 2017-09-20T22:37:02 | 119,408,979 | 0 | 0 | null | 2018-01-29T16:29:51 | 2018-01-29T16:29:51 | null | UTF-8 | C++ | false | false | 3,310 | h | /* file: logitboost_predict_dense_default_kernel.h */
/*******************************************************************************
* Copyright 2014-2017 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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.
*******************************************************************************/
/*
//++
// Common functions for Logit Boost predictions calculation
//--
*/
#ifndef __LOGITBOOST_PREDICT_DENSE_DEFAULT_KERNEL_H__
#define __LOGITBOOST_PREDICT_DENSE_DEFAULT_KERNEL_H__
#include "algorithm.h"
#include "service_numeric_table.h"
#include "logitboost_model.h"
#include "daal_defines.h"
#include "logitboost_predict_kernel.h"
namespace daal
{
namespace algorithms
{
namespace logitboost
{
namespace prediction
{
namespace internal
{
/**
* \brief Specialization of the structure that contains kernels
* for Logit Boost prediction calculation using Fast method
*/
template<typename algorithmFPType, CpuType cpu>
struct LogitBoostPredictKernel<defaultDense, algorithmFPType, cpu> : public Kernel
{
typedef typename daal::internal::HomogenNumericTableCPU<algorithmFPType, cpu> HomogenNT;
typedef typename services::SharedPtr<HomogenNT> HomogenNTPtr;
services::Status compute(const NumericTablePtr& a, const Model *m, NumericTable *r, const Parameter *par);
};
} // namepsace internal
} // namespace prediction
} // namespace logitboost
} // namespace algorithms
} // namespace daal
#endif
| [
"vasily.rubtsov@intel.com"
] | vasily.rubtsov@intel.com |
a7e10232ed275f40c6e5437124b2523c5cadd87e | 0f92f25f30f9dc773cefb6ccd09ede3bb260ee14 | /Source/KrazyKartsProject/KrazyKartsProjectGameMode.cpp | 7cd02c85d3d2d8b043962641a9ad4b17ac4e9e21 | [] | no_license | FixeoUnreal/KrazyKarts | 9bf9ef4f027bc22197b2b229aea2573ee566fe67 | 0548cc3984e1e7ee6075bef05cba4573b59ec66b | refs/heads/master | 2020-03-28T20:41:39.561197 | 2018-11-25T20:37:15 | 2018-11-25T20:37:15 | 149,094,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "KrazyKartsProjectGameMode.h"
#include "KrazyKartsProjectPawn.h"
#include "KrazyKartsProjectHud.h"
AKrazyKartsProjectGameMode::AKrazyKartsProjectGameMode()
{
DefaultPawnClass = AKrazyKartsProjectPawn::StaticClass();
HUDClass = AKrazyKartsProjectHud::StaticClass();
}
| [
"giang151093@yahoo.com.vn"
] | giang151093@yahoo.com.vn |
3c898bebc39669254c6e3ab9f5b823eb1ad60136 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/third_party/pdfium/fpdfsdk/formfiller/cffl_combobox.cpp | 262c485138a8d5719c60cc3cdb70e87a753ec4b8 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 8,661 | cpp | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "fpdfsdk/formfiller/cffl_combobox.h"
#include "fpdfsdk/formfiller/cba_fontmap.h"
#include "fpdfsdk/formfiller/cffl_formfiller.h"
#include "fpdfsdk/formfiller/cffl_iformfiller.h"
#include "fpdfsdk/include/fsdk_common.h"
#include "fpdfsdk/include/fsdk_mgr.h"
#include "fpdfsdk/pdfwindow/PWL_ComboBox.h"
CFFL_ComboBox::CFFL_ComboBox(CPDFDoc_Environment* pApp, CPDFSDK_Annot* pAnnot)
: CFFL_FormFiller(pApp, pAnnot), m_pFontMap(nullptr) {
m_State.nIndex = 0;
m_State.nStart = 0;
m_State.nEnd = 0;
}
CFFL_ComboBox::~CFFL_ComboBox() {
for (const auto& it : m_Maps)
it.second->InvalidateFocusHandler(this);
delete m_pFontMap;
}
PWL_CREATEPARAM CFFL_ComboBox::GetCreateParam() {
PWL_CREATEPARAM cp = CFFL_FormFiller::GetCreateParam();
int nFlags = m_pWidget->GetFieldFlags();
if (nFlags & FIELDFLAG_EDIT) {
cp.dwFlags |= PCBS_ALLOWCUSTOMTEXT;
}
if (!m_pFontMap)
m_pFontMap = new CBA_FontMap(m_pWidget, GetSystemHandler());
cp.pFontMap = m_pFontMap;
cp.pFocusHandler = this;
return cp;
}
CPWL_Wnd* CFFL_ComboBox::NewPDFWindow(const PWL_CREATEPARAM& cp,
CPDFSDK_PageView* pPageView) {
CPWL_ComboBox* pWnd = new CPWL_ComboBox();
pWnd->AttachFFLData(this);
pWnd->Create(cp);
CFFL_IFormFiller* pFormFiller = m_pApp->GetIFormFiller();
pWnd->SetFillerNotify(pFormFiller);
int32_t nCurSel = m_pWidget->GetSelectedIndex(0);
CFX_WideString swText;
if (nCurSel < 0)
swText = m_pWidget->GetValue();
else
swText = m_pWidget->GetOptionLabel(nCurSel);
for (int32_t i = 0, sz = m_pWidget->CountOptions(); i < sz; i++) {
pWnd->AddString(m_pWidget->GetOptionLabel(i).c_str());
}
pWnd->SetSelect(nCurSel);
pWnd->SetText(swText.c_str());
return pWnd;
}
FX_BOOL CFFL_ComboBox::OnChar(CPDFSDK_Annot* pAnnot,
FX_UINT nChar,
FX_UINT nFlags) {
return CFFL_FormFiller::OnChar(pAnnot, nChar, nFlags);
}
FX_BOOL CFFL_ComboBox::IsDataChanged(CPDFSDK_PageView* pPageView) {
CPWL_ComboBox* pWnd = (CPWL_ComboBox*)GetPDFWindow(pPageView, FALSE);
if (!pWnd)
return FALSE;
int32_t nCurSel = pWnd->GetSelect();
if (!(m_pWidget->GetFieldFlags() & FIELDFLAG_EDIT))
return nCurSel != m_pWidget->GetSelectedIndex(0);
if (nCurSel >= 0)
return nCurSel != m_pWidget->GetSelectedIndex(0);
return pWnd->GetText() != m_pWidget->GetValue();
}
void CFFL_ComboBox::SaveData(CPDFSDK_PageView* pPageView) {
CPWL_ComboBox* pWnd =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE));
if (!pWnd)
return;
CFX_WideString swText = pWnd->GetText();
int32_t nCurSel = pWnd->GetSelect();
bool bSetValue = false;
if (m_pWidget->GetFieldFlags() & FIELDFLAG_EDIT)
bSetValue = (nCurSel < 0) || (swText != m_pWidget->GetOptionLabel(nCurSel));
if (bSetValue) {
m_pWidget->SetValue(swText, FALSE);
} else {
m_pWidget->GetSelectedIndex(0);
m_pWidget->SetOptionSelection(nCurSel, TRUE, FALSE);
}
m_pWidget->ResetFieldAppearance(TRUE);
m_pWidget->UpdateField();
SetChangeMark();
m_pWidget->GetPDFPage();
}
void CFFL_ComboBox::GetActionData(CPDFSDK_PageView* pPageView,
CPDF_AAction::AActionType type,
PDFSDK_FieldAction& fa) {
switch (type) {
case CPDF_AAction::KeyStroke:
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE))) {
if (CPWL_Edit* pEdit = pComboBox->GetEdit()) {
fa.bFieldFull = pEdit->IsTextFull();
int nSelStart = 0;
int nSelEnd = 0;
pEdit->GetSel(nSelStart, nSelEnd);
fa.nSelEnd = nSelEnd;
fa.nSelStart = nSelStart;
fa.sValue = pEdit->GetText();
fa.sChangeEx = GetSelectExportText();
if (fa.bFieldFull) {
fa.sChange = L"";
fa.sChangeEx = L"";
}
}
}
break;
case CPDF_AAction::Validate:
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE))) {
if (CPWL_Edit* pEdit = pComboBox->GetEdit()) {
fa.sValue = pEdit->GetText();
}
}
break;
case CPDF_AAction::LoseFocus:
case CPDF_AAction::GetFocus:
fa.sValue = m_pWidget->GetValue();
break;
default:
break;
}
}
void CFFL_ComboBox::SetActionData(CPDFSDK_PageView* pPageView,
CPDF_AAction::AActionType type,
const PDFSDK_FieldAction& fa) {
switch (type) {
case CPDF_AAction::KeyStroke:
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE))) {
if (CPWL_Edit* pEdit = pComboBox->GetEdit()) {
pEdit->SetSel(fa.nSelStart, fa.nSelEnd);
pEdit->ReplaceSel(fa.sChange.c_str());
}
}
break;
default:
break;
}
}
FX_BOOL CFFL_ComboBox::IsActionDataChanged(CPDF_AAction::AActionType type,
const PDFSDK_FieldAction& faOld,
const PDFSDK_FieldAction& faNew) {
switch (type) {
case CPDF_AAction::KeyStroke:
return (!faOld.bFieldFull && faOld.nSelEnd != faNew.nSelEnd) ||
faOld.nSelStart != faNew.nSelStart ||
faOld.sChange != faNew.sChange;
default:
break;
}
return FALSE;
}
void CFFL_ComboBox::SaveState(CPDFSDK_PageView* pPageView) {
ASSERT(pPageView);
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE))) {
m_State.nIndex = pComboBox->GetSelect();
if (CPWL_Edit* pEdit = pComboBox->GetEdit()) {
pEdit->GetSel(m_State.nStart, m_State.nEnd);
m_State.sValue = pEdit->GetText();
}
}
}
void CFFL_ComboBox::RestoreState(CPDFSDK_PageView* pPageView) {
ASSERT(pPageView);
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, TRUE))) {
if (m_State.nIndex >= 0) {
pComboBox->SetSelect(m_State.nIndex);
} else {
if (CPWL_Edit* pEdit = pComboBox->GetEdit()) {
pEdit->SetText(m_State.sValue.c_str());
pEdit->SetSel(m_State.nStart, m_State.nEnd);
}
}
}
}
CPWL_Wnd* CFFL_ComboBox::ResetPDFWindow(CPDFSDK_PageView* pPageView,
FX_BOOL bRestoreValue) {
if (bRestoreValue)
SaveState(pPageView);
DestroyPDFWindow(pPageView);
CPWL_Wnd* pRet = nullptr;
if (bRestoreValue) {
RestoreState(pPageView);
pRet = GetPDFWindow(pPageView, FALSE);
} else {
pRet = GetPDFWindow(pPageView, TRUE);
}
m_pWidget->UpdateField();
return pRet;
}
#ifdef PDF_ENABLE_XFA
FX_BOOL CFFL_ComboBox::IsFieldFull(CPDFSDK_PageView* pPageView) {
if (CPWL_ComboBox* pComboBox =
static_cast<CPWL_ComboBox*>(GetPDFWindow(pPageView, FALSE))) {
if (CPWL_Edit* pEdit = pComboBox->GetEdit())
return pEdit->IsTextFull();
}
return FALSE;
}
#endif // PDF_ENABLE_XFA
void CFFL_ComboBox::OnSetFocus(CPWL_Wnd* pWnd) {
ASSERT(m_pApp);
if (pWnd->GetClassName() == PWL_CLASSNAME_EDIT) {
CPWL_Edit* pEdit = (CPWL_Edit*)pWnd;
pEdit->SetCharSet(FXFONT_GB2312_CHARSET);
pEdit->SetCodePage(936);
pEdit->SetReadyToInput();
CFX_WideString wsText = pEdit->GetText();
int nCharacters = wsText.GetLength();
CFX_ByteString bsUTFText = wsText.UTF16LE_Encode();
unsigned short* pBuffer = (unsigned short*)bsUTFText.c_str();
m_pApp->FFI_OnSetFieldInputFocus(m_pWidget->GetFormField(), pBuffer,
nCharacters, TRUE);
pEdit->SetEditNotify(this);
}
}
void CFFL_ComboBox::OnKillFocus(CPWL_Wnd* pWnd) {
ASSERT(m_pApp);
}
void CFFL_ComboBox::OnAddUndo(CPWL_Edit* pEdit) {
ASSERT(pEdit);
}
CFX_WideString CFFL_ComboBox::GetSelectExportText() {
CFX_WideString swRet;
int nExport = -1;
CPDFSDK_PageView* pPageView = GetCurPageView();
if (CPWL_ComboBox* pComboBox =
(CPWL_ComboBox*)GetPDFWindow(pPageView, FALSE)) {
nExport = pComboBox->GetSelect();
}
if (nExport >= 0) {
if (CPDF_FormField* pFormField = m_pWidget->GetFormField()) {
swRet = pFormField->GetOptionValue(nExport);
if (swRet.IsEmpty())
swRet = pFormField->GetOptionLabel(nExport);
}
}
return swRet;
}
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
fca819a729d1f66f58b3aabea06fd46cadb74ef3 | 85f750c5afef14adafb6beb5767a50c2486dbd68 | /third_parties/cmake-3.10.2/Source/cmVisualStudio10TargetGenerator.cxx | c61902ab6a43e9154f8a17d608683890676c03eb | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | stallpool/cruise | bbe3479ae6696b995a2df9be920e5d697f7b635d | 6d7b4bfff31b5e92574775bcb4f6362cf518ee92 | refs/heads/master | 2021-05-03T09:13:40.884789 | 2018-02-07T07:47:51 | 2018-02-07T07:47:51 | 120,572,164 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 171,279 | cxx | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmVisualStudio10TargetGenerator.h"
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalVisualStudio10Generator.h"
#include "cmLocalVisualStudio7Generator.h"
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
#include "cmVisualStudioGeneratorOptions.h"
#include "windows.h"
#include <memory> // IWYU pragma: keep
static std::string cmVS10EscapeXML(std::string arg)
{
cmSystemTools::ReplaceString(arg, "&", "&");
cmSystemTools::ReplaceString(arg, "<", "<");
cmSystemTools::ReplaceString(arg, ">", ">");
return arg;
}
static std::string cmVS10EscapeQuotes(std::string arg)
{
cmSystemTools::ReplaceString(arg, "\"", """);
return arg;
}
static std::string cmVS10EscapeComment(std::string comment)
{
// MSBuild takes the CDATA of a <Message></Message> element and just
// does "echo $CDATA" with no escapes. We must encode the string.
// http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx
std::string echoable;
for (std::string::iterator c = comment.begin(); c != comment.end(); ++c) {
switch (*c) {
case '\r':
break;
case '\n':
echoable += '\t';
break;
case '"': /* no break */
case '|': /* no break */
case '&': /* no break */
case '<': /* no break */
case '>': /* no break */
case '^':
echoable += '^'; /* no break */
default:
echoable += *c;
break;
}
}
return echoable;
}
static bool cmVS10IsTargetsFile(std::string const& path)
{
std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
}
static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
{
std::string res;
res = ".vcxproj";
if (cmGlobalVisualStudioGenerator::TargetIsCSharpOnly(t)) {
res = ".csproj";
}
return res;
}
cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
{
this->GlobalGenerator = gg;
this->GeneratorTarget = target;
this->Makefile = target->Target->GetMakefile();
this->Makefile->GetConfigurations(this->Configurations);
this->LocalGenerator =
(cmLocalVisualStudio7Generator*)this->GeneratorTarget->GetLocalGenerator();
this->Name = this->GeneratorTarget->GetName();
this->GUID = this->GlobalGenerator->GetGUID(this->Name);
this->Platform = gg->GetPlatformName();
this->NsightTegra = gg->IsNsightTegra();
for (int i = 0; i < 4; ++i) {
this->NsightTegraVersion[i] = 0;
}
sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
&this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
&this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
this->MSTools = !this->NsightTegra;
this->Managed = false;
this->TargetCompileAsWinRT = false;
this->BuildFileStream = 0;
this->IsMissingFiles = false;
this->DefaultArtifactDir =
this->LocalGenerator->GetCurrentBinaryDirectory() + std::string("/") +
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->InSourceBuild =
(strcmp(this->Makefile->GetCurrentSourceDirectory(),
this->Makefile->GetCurrentBinaryDirectory()) == 0);
}
cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
{
for (OptionsMap::iterator i = this->ClOptions.begin();
i != this->ClOptions.end(); ++i) {
delete i->second;
}
for (OptionsMap::iterator i = this->LinkOptions.begin();
i != this->LinkOptions.end(); ++i) {
delete i->second;
}
for (OptionsMap::iterator i = this->CudaOptions.begin();
i != this->CudaOptions.end(); ++i) {
delete i->second;
}
for (OptionsMap::iterator i = this->CudaLinkOptions.begin();
i != this->CudaLinkOptions.end(); ++i) {
delete i->second;
}
if (!this->BuildFileStream) {
return;
}
if (this->BuildFileStream->Close()) {
this->GlobalGenerator->FileReplacedDuringGenerate(this->PathToProjectFile);
}
delete this->BuildFileStream;
}
void cmVisualStudio10TargetGenerator::WritePlatformConfigTag(
const char* tag, const std::string& config, int indentLevel,
const char* attribute, const char* end, std::ostream* stream)
{
if (!stream) {
stream = this->BuildFileStream;
}
stream->fill(' ');
stream->width(indentLevel * 2);
(*stream) << ""; // applies indentation
(*stream) << "<" << tag << " Condition=\"";
(*stream) << "'$(Configuration)|$(Platform)'=='";
(*stream) << config << "|" << this->Platform;
(*stream) << "'";
// handle special case for 32 bit C# targets
if (this->ProjectType == csproj && this->Platform == "Win32") {
(*stream) << " Or ";
(*stream) << "'$(Configuration)|$(Platform)'=='";
(*stream) << config << "|x86";
(*stream) << "'";
}
(*stream) << "\"";
if (attribute) {
(*stream) << attribute;
}
// close the tag
(*stream) << ">";
if (end) {
(*stream) << end;
}
}
void cmVisualStudio10TargetGenerator::WriteString(const char* line,
int indentLevel)
{
this->BuildFileStream->fill(' ');
this->BuildFileStream->width(indentLevel * 2);
// write an empty string to get the fill level indent to print
(*this->BuildFileStream) << "";
(*this->BuildFileStream) << line;
}
#define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
#define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
#define VS10_CXX_USER_PROPS \
"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
#define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
#define VS10_CSharp_DEFAULT_PROPS \
"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
// This does not seem to exist by default, it's just provided for consistency
// in case users want to have default custom props for C# targets
#define VS10_CSharp_USER_PROPS \
"$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
#define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
void cmVisualStudio10TargetGenerator::Generate()
{
// do not generate external ms projects
if (this->GeneratorTarget->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
this->GeneratorTarget->GetProperty("EXTERNAL_MSPROJECT")) {
return;
}
this->ProjectFileExtension =
computeProjectFileExtension(this->GeneratorTarget);
if (this->ProjectFileExtension == ".vcxproj") {
this->ProjectType = vcxproj;
this->Managed = false;
} else if (this->ProjectFileExtension == ".csproj") {
this->ProjectType = csproj;
this->Managed = true;
}
// Tell the global generator the name of the project file
this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
this->Name.c_str());
this->GeneratorTarget->Target->SetProperty(
"GENERATOR_FILE_NAME_EXT", this->ProjectFileExtension.c_str());
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
if (!this->ComputeClOptions()) {
return;
}
if (!this->ComputeRcOptions()) {
return;
}
if (!this->ComputeCudaOptions()) {
return;
}
if (!this->ComputeCudaLinkOptions()) {
return;
}
if (!this->ComputeMasmOptions()) {
return;
}
if (!this->ComputeNasmOptions()) {
return;
}
if (!this->ComputeLinkOptions()) {
return;
}
if (!this->ComputeLibOptions()) {
return;
}
}
std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
path += "/";
path += this->Name;
path += this->ProjectFileExtension;
this->BuildFileStream = new cmGeneratedFileStream(path.c_str());
this->PathToProjectFile = path;
this->BuildFileStream->SetCopyIfDifferent(true);
// Write the encoding header into the file
char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
this->BuildFileStream->write(magic, 3);
// get the tools version to use
const std::string toolsVer(this->GlobalGenerator->GetToolsVersion());
std::string project_defaults = "<?xml version=\"1.0\" encoding=\"" +
this->GlobalGenerator->Encoding() + "\"?>\n";
project_defaults.append("<Project DefaultTargets=\"Build\" ToolsVersion=\"");
project_defaults.append(toolsVer + "\" ");
project_defaults.append(
"xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n");
this->WriteString(project_defaults.c_str(), 0);
if (this->NsightTegra) {
this->WriteString("<PropertyGroup Label=\"NsightTegraProject\">\n", 1);
const int nsightTegraMajorVersion = this->NsightTegraVersion[0];
const int nsightTegraMinorVersion = this->NsightTegraVersion[1];
if (nsightTegraMajorVersion >= 2) {
this->WriteString("<NsightTegraProjectRevisionNumber>", 2);
if (nsightTegraMajorVersion > 3 ||
(nsightTegraMajorVersion == 3 && nsightTegraMinorVersion >= 1)) {
(*this->BuildFileStream) << "11";
} else {
// Nsight Tegra 2.0 uses project revision 9.
(*this->BuildFileStream) << "9";
}
(*this->BuildFileStream) << "</NsightTegraProjectRevisionNumber>\n";
// Tell newer versions to upgrade silently when loading.
this->WriteString("<NsightTegraUpgradeOnceWithoutPrompt>"
"true"
"</NsightTegraUpgradeOnceWithoutPrompt>\n",
2);
} else {
// Require Nsight Tegra 1.6 for JCompile support.
this->WriteString("<NsightTegraProjectRevisionNumber>"
"7"
"</NsightTegraProjectRevisionNumber>\n",
2);
}
this->WriteString("</PropertyGroup>\n", 1);
}
if (const char* hostArch =
this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
this->WriteString("<PropertyGroup>\n", 1);
this->WriteString("<PreferredToolArchitecture>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(hostArch)
<< "</PreferredToolArchitecture>\n";
this->WriteString("</PropertyGroup>\n", 1);
}
if (this->ProjectType != csproj) {
this->WriteProjectConfigurations();
}
this->WriteString("<PropertyGroup Label=\"Globals\">\n", 1);
this->WriteString("<ProjectGuid>", 2);
(*this->BuildFileStream) << "{" << this->GUID << "}</ProjectGuid>\n";
if (this->MSTools &&
this->GeneratorTarget->GetType() <= cmStateEnums::GLOBAL_TARGET) {
this->WriteApplicationTypeSettings();
this->VerifyNecessaryFiles();
}
const char* vsProjectTypes =
this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
if (vsProjectTypes) {
std::string tagName = "ProjectTypes";
if (this->ProjectType == csproj) {
tagName = "ProjectTypeGuids";
}
this->WriteString("", 2);
(*this->BuildFileStream) << "<" << tagName << ">"
<< cmVS10EscapeXML(vsProjectTypes) << "</"
<< tagName << ">\n";
}
const char* vsProjectName =
this->GeneratorTarget->GetProperty("VS_SCC_PROJECTNAME");
const char* vsLocalPath =
this->GeneratorTarget->GetProperty("VS_SCC_LOCALPATH");
const char* vsProvider =
this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER");
if (vsProjectName && vsLocalPath && vsProvider) {
this->WriteString("<SccProjectName>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsProjectName)
<< "</SccProjectName>\n";
this->WriteString("<SccLocalPath>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsLocalPath)
<< "</SccLocalPath>\n";
this->WriteString("<SccProvider>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsProvider)
<< "</SccProvider>\n";
const char* vsAuxPath =
this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH");
if (vsAuxPath) {
this->WriteString("<SccAuxPath>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsAuxPath)
<< "</SccAuxPath>\n";
}
}
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
this->WriteString("<WinMDAssembly>true</WinMDAssembly>\n", 2);
}
const char* vsGlobalKeyword =
this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD");
if (!vsGlobalKeyword) {
this->WriteString("<Keyword>Win32Proj</Keyword>\n", 2);
} else {
this->WriteString("<Keyword>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsGlobalKeyword)
<< "</Keyword>\n";
}
const char* vsGlobalRootNamespace =
this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE");
if (vsGlobalRootNamespace) {
this->WriteString("<RootNamespace>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(vsGlobalRootNamespace)
<< "</RootNamespace>\n";
}
this->WriteString("<Platform>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(this->Platform)
<< "</Platform>\n";
const char* projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
if (!projLabel) {
projLabel = this->Name.c_str();
}
this->WriteString("<ProjectName>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(projLabel) << "</ProjectName>\n";
if (const char* targetFrameworkVersion = this->GeneratorTarget->GetProperty(
"VS_DOTNET_TARGET_FRAMEWORK_VERSION")) {
this->WriteString("<TargetFrameworkVersion>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(targetFrameworkVersion)
<< "</TargetFrameworkVersion>\n";
}
// Disable the project upgrade prompt that is displayed the first time a
// project using an older toolset version is opened in a newer version of
// the IDE (respected by VS 2013 and above).
if (this->GlobalGenerator->GetVersion() >=
cmGlobalVisualStudioGenerator::VS12) {
this->WriteString("<VCProjectUpgraderObjectName>NoUpgrade"
"</VCProjectUpgraderObjectName>\n",
2);
}
std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
for (std::vector<std::string>::const_iterator keyIt = keys.begin();
keyIt != keys.end(); ++keyIt) {
static const char* prefix = "VS_GLOBAL_";
if (keyIt->find(prefix) != 0)
continue;
std::string globalKey = keyIt->substr(strlen(prefix));
// Skip invalid or separately-handled properties.
if (globalKey.empty() || globalKey == "PROJECT_TYPES" ||
globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") {
continue;
}
const char* value = this->GeneratorTarget->GetProperty(*keyIt);
if (!value)
continue;
this->WriteString("<", 2);
(*this->BuildFileStream) << globalKey << ">" << cmVS10EscapeXML(value)
<< "</" << globalKey << ">\n";
}
if (this->Managed) {
std::string outputType = "<OutputType>";
switch (this->GeneratorTarget->GetType()) {
case cmStateEnums::OBJECT_LIBRARY:
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::SHARED_LIBRARY:
outputType += "Library";
break;
case cmStateEnums::MODULE_LIBRARY:
outputType += "Module";
break;
case cmStateEnums::EXECUTABLE:
if (this->GeneratorTarget->Target->GetPropertyAsBool(
"WIN32_EXECUTABLE")) {
outputType += "WinExe";
} else {
outputType += "Exe";
}
break;
case cmStateEnums::UTILITY:
case cmStateEnums::GLOBAL_TARGET:
outputType += "Utility";
break;
case cmStateEnums::UNKNOWN_LIBRARY:
case cmStateEnums::INTERFACE_LIBRARY:
break;
}
outputType += "</OutputType>\n";
this->WriteString(outputType.c_str(), 2);
this->WriteString("<AppDesignerFolder>Properties</AppDesignerFolder>\n",
2);
}
this->WriteString("</PropertyGroup>\n", 1);
switch (this->ProjectType) {
case vcxproj:
this->WriteString("<Import Project=\"" VS10_CXX_DEFAULT_PROPS "\" />\n",
1);
break;
case csproj:
this->WriteString("<Import Project=\"" VS10_CSharp_DEFAULT_PROPS "\" "
"Condition=\"Exists('" VS10_CSharp_DEFAULT_PROPS "')\""
"/>\n",
1);
break;
}
this->WriteProjectConfigurationValues();
if (this->ProjectType == vcxproj) {
this->WriteString("<Import Project=\"" VS10_CXX_PROPS "\" />\n", 1);
}
this->WriteString("<ImportGroup Label=\"ExtensionSettings\">\n", 1);
if (this->GlobalGenerator->IsCudaEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
"BuildCustomizations\\CUDA ",
2);
(*this->BuildFileStream)
<< cmVS10EscapeXML(this->GlobalGenerator->GetPlatformToolsetCudaString())
<< ".props\" />\n";
}
if (this->GlobalGenerator->IsMasmEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
"BuildCustomizations\\masm.props\" />\n",
2);
}
if (this->GlobalGenerator->IsNasmEnabled()) {
// Always search in the standard modules location.
std::string propsTemplate =
GetCMakeFilePath("Templates/MSBuild/nasm.props.in");
std::string propsLocal;
propsLocal += this->DefaultArtifactDir;
propsLocal += "\\nasm.props";
this->ConvertToWindowsSlash(propsLocal);
this->Makefile->ConfigureFile(propsTemplate.c_str(), propsLocal.c_str(),
false, true, true);
std::string import = std::string("<Import Project=\"") +
cmVS10EscapeXML(propsLocal) + "\" />\n";
this->WriteString(import.c_str(), 2);
}
this->WriteString("</ImportGroup>\n", 1);
this->WriteString("<ImportGroup Label=\"PropertySheets\">\n", 1);
{
std::string props;
switch (this->ProjectType) {
case vcxproj:
props = VS10_CXX_USER_PROPS;
break;
case csproj:
props = VS10_CSharp_USER_PROPS;
break;
}
if (const char* p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
props = p;
}
if (!props.empty()) {
this->ConvertToWindowsSlash(props);
this->WriteString("", 2);
(*this->BuildFileStream)
<< "<Import Project=\"" << cmVS10EscapeXML(props) << "\""
<< " Condition=\"exists('" << cmVS10EscapeXML(props) << "')\""
<< " Label=\"LocalAppDataPlatform\" />\n";
}
}
this->WritePlatformExtensions();
this->WriteString("</ImportGroup>\n", 1);
this->WriteString("<PropertyGroup Label=\"UserMacros\" />\n", 1);
this->WriteWinRTPackageCertificateKeyFile();
this->WritePathAndIncrementalLinkOptions();
this->WriteItemDefinitionGroups();
this->WriteCustomCommands();
this->WriteAllSources();
this->WriteDotNetReferences();
this->WriteEmbeddedResourceGroup();
this->WriteXamlFilesGroup();
this->WriteWinRTReferences();
this->WriteProjectReferences();
this->WriteSDKReferences();
switch (this->ProjectType) {
case vcxproj:
this->WriteString("<Import Project=\"" VS10_CXX_TARGETS "\" />\n", 1);
break;
case csproj:
this->WriteString("<Import Project=\"" VS10_CSharp_TARGETS "\" />\n", 1);
break;
}
this->WriteTargetSpecificReferences();
this->WriteString("<ImportGroup Label=\"ExtensionTargets\">\n", 1);
this->WriteTargetsFileReferences();
if (this->GlobalGenerator->IsCudaEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
"BuildCustomizations\\CUDA ",
2);
(*this->BuildFileStream)
<< cmVS10EscapeXML(this->GlobalGenerator->GetPlatformToolsetCudaString())
<< ".targets\" />\n";
}
if (this->GlobalGenerator->IsMasmEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
"BuildCustomizations\\masm.targets\" />\n",
2);
}
if (this->GlobalGenerator->IsNasmEnabled()) {
std::string nasmTargets =
GetCMakeFilePath("Templates/MSBuild/nasm.targets");
std::string import = "<Import Project=\"";
import += cmVS10EscapeXML(nasmTargets) + "\" />\n";
this->WriteString(import.c_str(), 2);
}
this->WriteString("</ImportGroup>\n", 1);
if (this->ProjectType == csproj) {
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
this->WriteString("<PropertyGroup Condition=\"'$(Configuration)' == '",
1);
(*this->BuildFileStream) << *i << "'\">\n";
this->WriteEvents(*i);
this->WriteString("</PropertyGroup>\n", 1);
}
// make sure custom commands are executed before build (if necessary)
this->WriteString("<PropertyGroup>\n", 1);
this->WriteString("<BuildDependsOn>\n", 2);
for (std::set<std::string>::const_iterator i =
this->CSharpCustomCommandNames.begin();
i != this->CSharpCustomCommandNames.end(); ++i) {
this->WriteString(i->c_str(), 3);
(*this->BuildFileStream) << ";\n";
}
this->WriteString("$(BuildDependsOn)\n", 3);
this->WriteString("</BuildDependsOn>\n", 2);
this->WriteString("</PropertyGroup>\n", 1);
}
this->WriteString("</Project>", 0);
// The groups are stored in a separate file for VS 10
this->WriteGroups();
}
void cmVisualStudio10TargetGenerator::WriteDotNetReferences()
{
std::vector<std::string> references;
typedef std::pair<std::string, std::string> HintReference;
std::vector<HintReference> hintReferences;
if (const char* vsDotNetReferences =
this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
cmSystemTools::ExpandListArgument(vsDotNetReferences, references);
}
cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
for (cmPropertyMap::const_iterator i = props.begin(); i != props.end();
++i) {
if (i->first.find("VS_DOTNET_REFERENCE_") == 0) {
std::string name = i->first.substr(20);
if (!name.empty()) {
std::string path = i->second.GetValue();
if (!cmsys::SystemTools::FileIsFullPath(path)) {
path = std::string(this->GeneratorTarget->Target->GetMakefile()
->GetCurrentSourceDirectory()) +
"/" + path;
}
this->ConvertToWindowsSlash(path);
hintReferences.push_back(HintReference(name, path));
}
}
}
if (!references.empty() || !hintReferences.empty()) {
this->WriteString("<ItemGroup>\n", 1);
for (std::vector<std::string>::iterator ri = references.begin();
ri != references.end(); ++ri) {
// if the entry from VS_DOTNET_REFERENCES is an existing file, generate
// a new hint-reference and name it from the filename
if (cmsys::SystemTools::FileExists(*ri, true)) {
std::string name =
cmsys::SystemTools::GetFilenameWithoutExtension(*ri);
std::string path = *ri;
this->ConvertToWindowsSlash(path);
hintReferences.push_back(HintReference(name, path));
} else {
this->WriteDotNetReference(*ri, "");
}
}
for (std::vector<std::pair<std::string, std::string>>::const_iterator i =
hintReferences.begin();
i != hintReferences.end(); ++i) {
this->WriteDotNetReference(i->first, i->second);
}
this->WriteString("</ItemGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteDotNetReference(
std::string const& ref, std::string const& hint)
{
this->WriteString("<Reference Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(ref) << "\">\n";
this->WriteString("<CopyLocalSatelliteAssemblies>true"
"</CopyLocalSatelliteAssemblies>\n",
3);
this->WriteString("<ReferenceOutputAssembly>true"
"</ReferenceOutputAssembly>\n",
3);
if (!hint.empty()) {
const char* privateReference = "True";
if (const char* value = this->GeneratorTarget->GetProperty(
"VS_DOTNET_REFERENCES_COPY_LOCAL")) {
if (cmSystemTools::IsOff(value)) {
privateReference = "False";
}
}
this->WriteString("<Private>", 3);
(*this->BuildFileStream) << privateReference << "</Private>\n";
this->WriteString("<HintPath>", 3);
(*this->BuildFileStream) << hint << "</HintPath>\n";
}
this->WriteDotNetReferenceCustomTags(ref);
this->WriteString("</Reference>\n", 2);
}
void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
std::string const& ref)
{
static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
static const std::string refpropInfix = "_TAG_";
const std::string refPropFullPrefix = refpropPrefix + ref + refpropInfix;
typedef std::map<std::string, std::string> CustomTags;
CustomTags tags;
cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
for (cmPropertyMap::const_iterator i = props.begin(); i != props.end();
++i) {
if (i->first.find(refPropFullPrefix) == 0) {
std::string refTag = i->first.substr(refPropFullPrefix.length());
std::string refVal = i->second.GetValue();
if (!refTag.empty() && !refVal.empty()) {
tags[refTag] = refVal;
}
}
}
for (CustomTags::const_iterator tag = tags.begin(); tag != tags.end();
++tag) {
this->WriteString("<", 3);
(*this->BuildFileStream) << tag->first << ">"
<< cmVS10EscapeXML(tag->second) << "</"
<< tag->first << ">\n";
}
}
void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
{
std::vector<cmSourceFile const*> resxObjs;
this->GeneratorTarget->GetResxSources(resxObjs, "");
if (!resxObjs.empty()) {
this->WriteString("<ItemGroup>\n", 1);
std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
this->ConvertToWindowsSlash(srcDir);
for (std::vector<cmSourceFile const*>::const_iterator oi =
resxObjs.begin();
oi != resxObjs.end(); ++oi) {
std::string obj = (*oi)->GetFullPath();
this->WriteString("<EmbeddedResource Include=\"", 2);
this->ConvertToWindowsSlash(obj);
bool useRelativePath = false;
if (this->ProjectType == csproj && this->InSourceBuild) {
// If we do an in-source build and the resource file is in a
// subdirectory
// of the .csproj file, we have to use relative pathnames, otherwise
// visual studio does not show the file in the IDE. Sorry.
if (obj.find(srcDir) == 0) {
obj = this->ConvertPath(obj, true);
this->ConvertToWindowsSlash(obj);
useRelativePath = true;
}
}
(*this->BuildFileStream) << obj << "\">\n";
if (this->ProjectType != csproj) {
this->WriteString("<DependentUpon>", 3);
std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
(*this->BuildFileStream) << hFileName << "</DependentUpon>\n";
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
this->WritePlatformConfigTag("LogicalName", *i, 3);
if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
// Handle variant of VS_GLOBAL_<variable> for RootNamespace.
this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
(*this->BuildFileStream) << "$(RootNamespace).";
}
(*this->BuildFileStream) << "%(Filename)";
(*this->BuildFileStream) << ".resources";
(*this->BuildFileStream) << "</LogicalName>\n";
}
} else {
std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
this->ConvertToWindowsSlash(binDir);
// If the resource was NOT added using a relative path (which should
// be the default), we have to provide a link here
if (!useRelativePath) {
std::string link;
if (obj.find(srcDir) == 0) {
link = obj.substr(srcDir.length() + 1);
} else if (obj.find(binDir) == 0) {
link = obj.substr(binDir.length() + 1);
} else {
link = cmsys::SystemTools::GetFilenameName(obj);
}
if (!link.empty()) {
this->WriteString("<Link>", 3);
(*this->BuildFileStream) << link << "</Link>\n";
}
}
// Determine if this is a generated resource from a .Designer.cs file
std::string designerResource =
cmSystemTools::GetFilenamePath((*oi)->GetFullPath()) + "/" +
cmSystemTools::GetFilenameWithoutLastExtension(
(*oi)->GetFullPath()) +
".Designer.cs";
if (cmsys::SystemTools::FileExists(designerResource)) {
std::string generator = "PublicResXFileCodeGenerator";
if (const char* g = (*oi)->GetProperty("VS_RESOURCE_GENERATOR")) {
generator = g;
}
if (!generator.empty()) {
this->WriteString("<Generator>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(generator)
<< "</Generator>\n";
if (designerResource.find(srcDir) == 0) {
designerResource = designerResource.substr(srcDir.length() + 1);
} else if (designerResource.find(binDir) == 0) {
designerResource = designerResource.substr(binDir.length() + 1);
} else {
designerResource =
cmsys::SystemTools::GetFilenameName(designerResource);
}
this->ConvertToWindowsSlash(designerResource);
this->WriteString("<LastGenOutput>", 3);
(*this->BuildFileStream) << designerResource
<< "</LastGenOutput>\n";
}
}
const cmPropertyMap& props = (*oi)->GetProperties();
for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
++p) {
static const std::string propNamePrefix = "VS_CSHARP_";
if (p->first.find(propNamePrefix) == 0) {
std::string tagName = p->first.substr(propNamePrefix.length());
if (!tagName.empty()) {
std::string value = props.GetPropertyValue(p->first);
if (!value.empty()) {
this->WriteString("<", 3);
(*this->BuildFileStream) << tagName << ">";
(*this->BuildFileStream) << cmVS10EscapeXML(value);
(*this->BuildFileStream) << "</" << tagName << ">\n";
}
}
}
}
}
this->WriteString("</EmbeddedResource>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup()
{
std::vector<cmSourceFile const*> xamlObjs;
this->GeneratorTarget->GetXamlSources(xamlObjs, "");
if (!xamlObjs.empty()) {
this->WriteString("<ItemGroup>\n", 1);
for (std::vector<cmSourceFile const*>::const_iterator oi =
xamlObjs.begin();
oi != xamlObjs.end(); ++oi) {
std::string obj = (*oi)->GetFullPath();
std::string xamlType;
const char* xamlTypeProperty = (*oi)->GetProperty("VS_XAML_TYPE");
if (xamlTypeProperty) {
xamlType = xamlTypeProperty;
} else {
xamlType = "Page";
}
this->WriteSource(xamlType, *oi, ">\n");
if (this->ProjectType == csproj && !this->InSourceBuild) {
// add <Link> tag to written XAML source if necessary
const std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
const std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
std::string link;
if (obj.find(srcDir) == 0) {
link = obj.substr(srcDir.length() + 1);
} else if (obj.find(binDir) == 0) {
link = obj.substr(binDir.length() + 1);
} else {
link = cmsys::SystemTools::GetFilenameName(obj);
}
if (!link.empty()) {
this->ConvertToWindowsSlash(link);
this->WriteString("<Link>", 3);
(*this->BuildFileStream) << link << "</Link>\n";
}
}
this->WriteString("<SubType>Designer</SubType>\n", 3);
this->WriteString("</", 2);
(*this->BuildFileStream) << xamlType << ">\n";
}
this->WriteString("</ItemGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences()
{
if (this->MSTools) {
if (this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0") {
this->WriteString("<Import Project=\""
"$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
"$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
"$(TargetPlatformVersion).targets\" />\n",
1);
}
}
}
void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences()
{
for (std::vector<TargetsFileAndConfigs>::iterator i =
this->TargetsFileAndConfigsVec.begin();
i != this->TargetsFileAndConfigsVec.end(); ++i) {
TargetsFileAndConfigs const& tac = *i;
this->WriteString("<Import Project=\"", 3);
(*this->BuildFileStream) << tac.File << "\" ";
(*this->BuildFileStream) << "Condition=\"";
(*this->BuildFileStream) << "Exists('" << tac.File << "')";
if (!tac.Configs.empty()) {
(*this->BuildFileStream) << " And (";
for (size_t j = 0; j < tac.Configs.size(); ++j) {
if (j > 0) {
(*this->BuildFileStream) << " Or ";
}
(*this->BuildFileStream) << "'$(Configuration)'=='" << tac.Configs[j]
<< "'";
}
(*this->BuildFileStream) << ")";
}
(*this->BuildFileStream) << "\" />\n";
}
}
void cmVisualStudio10TargetGenerator::WriteWinRTReferences()
{
std::vector<std::string> references;
if (const char* vsWinRTReferences =
this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) {
cmSystemTools::ExpandListArgument(vsWinRTReferences, references);
}
if (this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0" &&
references.empty()) {
references.push_back("platform.winmd");
}
if (!references.empty()) {
this->WriteString("<ItemGroup>\n", 1);
for (std::vector<std::string>::iterator ri = references.begin();
ri != references.end(); ++ri) {
this->WriteString("<Reference Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(*ri) << "\">\n";
this->WriteString("<IsWinMDFile>true</IsWinMDFile>\n", 3);
this->WriteString("</Reference>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
}
}
// ConfigurationType Application, Utility StaticLibrary DynamicLibrary
void cmVisualStudio10TargetGenerator::WriteProjectConfigurations()
{
this->WriteString("<ItemGroup Label=\"ProjectConfigurations\">\n", 1);
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
this->WriteString("<ProjectConfiguration Include=\"", 2);
(*this->BuildFileStream) << *i << "|" << this->Platform << "\">\n";
this->WriteString("<Configuration>", 3);
(*this->BuildFileStream) << *i << "</Configuration>\n";
this->WriteString("<Platform>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(this->Platform)
<< "</Platform>\n";
this->WriteString("</ProjectConfiguration>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
}
void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues()
{
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
this->WritePlatformConfigTag("PropertyGroup", *i, 1,
" Label=\"Configuration\"", "\n");
if (this->ProjectType != csproj) {
std::string configType = "<ConfigurationType>";
if (const char* vsConfigurationType =
this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
configType += cmVS10EscapeXML(vsConfigurationType);
} else {
switch (this->GeneratorTarget->GetType()) {
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
configType += "DynamicLibrary";
break;
case cmStateEnums::OBJECT_LIBRARY:
case cmStateEnums::STATIC_LIBRARY:
configType += "StaticLibrary";
break;
case cmStateEnums::EXECUTABLE:
if (this->NsightTegra &&
!this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
// Android executables are .so too.
configType += "DynamicLibrary";
} else {
configType += "Application";
}
break;
case cmStateEnums::UTILITY:
case cmStateEnums::GLOBAL_TARGET:
if (this->NsightTegra) {
// Tegra-Android platform does not understand "Utility".
configType += "StaticLibrary";
} else {
configType += "Utility";
}
break;
case cmStateEnums::UNKNOWN_LIBRARY:
case cmStateEnums::INTERFACE_LIBRARY:
break;
}
}
configType += "</ConfigurationType>\n";
this->WriteString(configType.c_str(), 2);
}
if (this->MSTools) {
if (!this->Managed) {
this->WriteMSToolConfigurationValues(*i);
} else {
this->WriteMSToolConfigurationValuesManaged(*i);
}
} else if (this->NsightTegra) {
this->WriteNsightTegraConfigurationValues(*i);
}
this->WriteString("</PropertyGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
std::string const& config)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
const char* mfcFlag =
this->GeneratorTarget->Target->GetMakefile()->GetDefinition(
"CMAKE_MFC_FLAG");
if (mfcFlag) {
std::string const mfcFlagValue = mfcFlag;
std::string useOfMfcValue = "false";
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
if (mfcFlagValue == "1") {
useOfMfcValue = "Static";
} else if (mfcFlagValue == "2") {
useOfMfcValue = "Dynamic";
}
}
std::string mfcLine = "<UseOfMfc>";
mfcLine += useOfMfcValue + "</UseOfMfc>\n";
this->WriteString(mfcLine.c_str(), 2);
}
if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
this->ClOptions[config]->UsingUnicode()) ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore() ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
this->WriteString("<CharacterSet>Unicode</CharacterSet>\n", 2);
} else if (this->GeneratorTarget->GetType() <=
cmStateEnums::MODULE_LIBRARY &&
this->ClOptions[config]->UsingSBCS()) {
this->WriteString("<CharacterSet>NotSet</CharacterSet>\n", 2);
} else {
this->WriteString("<CharacterSet>MultiByte</CharacterSet>\n", 2);
}
if (const char* toolset = gg->GetPlatformToolset()) {
std::string pts = "<PlatformToolset>";
pts += toolset;
pts += "</PlatformToolset>\n";
this->WriteString(pts.c_str(), 2);
}
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
this->WriteString("<WindowsAppContainer>true"
"</WindowsAppContainer>\n",
2);
}
}
void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
std::string const& config)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
Options& o = *(this->ClOptions[config]);
if (o.IsDebug()) {
this->WriteString("<DebugSymbols>true</DebugSymbols>\n", 2);
this->WriteString("<DefineDebug>true</DefineDebug>\n", 2);
}
std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
this->ConvertToWindowsSlash(outDir);
this->WriteString("<OutputPath>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(outDir) << "</OutputPath>\n";
if (o.HasFlag("Platform")) {
this->WriteString("<PlatformTarget>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(o.GetFlag("Platform"))
<< "</PlatformTarget>\n";
o.RemoveFlag("Platform");
}
if (const char* toolset = gg->GetPlatformToolset()) {
this->WriteString("<PlatformToolset>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(toolset)
<< "</PlatformToolset>\n";
}
std::string postfixName = cmSystemTools::UpperCase(config);
postfixName += "_POSTFIX";
std::string assemblyName = this->GeneratorTarget->GetOutputName(
config, cmStateEnums::RuntimeBinaryArtifact);
if (const char* postfix = this->GeneratorTarget->GetProperty(postfixName)) {
assemblyName += postfix;
}
this->WriteString("<AssemblyName>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(assemblyName)
<< "</AssemblyName>\n";
if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
this->WriteString("<StartAction>Program</StartAction>\n", 2);
this->WriteString("<StartProgram>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(outDir)
<< cmVS10EscapeXML(assemblyName)
<< ".exe</StartProgram>\n";
}
o.OutputFlagMap(*this->BuildFileStream, " ");
}
//----------------------------------------------------------------------------
void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
std::string const&)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
const char* toolset = gg->GetPlatformToolset();
std::string ntv = "<NdkToolchainVersion>";
ntv += toolset ? toolset : "Default";
ntv += "</NdkToolchainVersion>\n";
this->WriteString(ntv.c_str(), 2);
if (const char* minApi =
this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) {
this->WriteString("<AndroidMinAPI>", 2);
(*this->BuildFileStream) << "android-" << cmVS10EscapeXML(minApi)
<< "</AndroidMinAPI>\n";
}
if (const char* api = this->GeneratorTarget->GetProperty("ANDROID_API")) {
this->WriteString("<AndroidTargetAPI>", 2);
(*this->BuildFileStream) << "android-" << cmVS10EscapeXML(api)
<< "</AndroidTargetAPI>\n";
}
if (const char* cpuArch =
this->GeneratorTarget->GetProperty("ANDROID_ARCH")) {
this->WriteString("<AndroidArch>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(cpuArch) << "</AndroidArch>\n";
}
if (const char* stlType =
this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) {
this->WriteString("<AndroidStlType>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(stlType)
<< "</AndroidStlType>\n";
}
}
void cmVisualStudio10TargetGenerator::WriteCustomCommands()
{
this->SourcesVisited.clear();
this->CSharpCustomCommandNames.clear();
std::vector<cmSourceFile const*> customCommands;
this->GeneratorTarget->GetCustomCommands(customCommands, "");
for (std::vector<cmSourceFile const*>::const_iterator si =
customCommands.begin();
si != customCommands.end(); ++si) {
this->WriteCustomCommand(*si);
}
}
void cmVisualStudio10TargetGenerator::WriteCustomCommand(
cmSourceFile const* sf)
{
if (this->SourcesVisited.insert(sf).second) {
if (std::vector<cmSourceFile*> const* depends =
this->GeneratorTarget->GetSourceDepends(sf)) {
for (std::vector<cmSourceFile*>::const_iterator di = depends->begin();
di != depends->end(); ++di) {
this->WriteCustomCommand(*di);
}
}
if (cmCustomCommand const* command = sf->GetCustomCommand()) {
// C# projects write their <Target> within WriteCustomRule()
if (this->ProjectType != csproj) {
this->WriteString("<ItemGroup>\n", 1);
}
this->WriteCustomRule(sf, *command);
if (this->ProjectType != csproj) {
this->WriteString("</ItemGroup>\n", 1);
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRule(
cmSourceFile const* source, cmCustomCommand const& command)
{
std::string sourcePath = source->GetFullPath();
// VS 10 will always rebuild a custom command attached to a .rule
// file that doesn't exist so create the file explicitly.
if (source->GetPropertyAsBool("__CMAKE_RULE")) {
if (!cmSystemTools::FileExists(sourcePath.c_str())) {
// Make sure the path exists for the file
std::string path = cmSystemTools::GetFilenamePath(sourcePath);
cmSystemTools::MakeDirectory(path.c_str());
cmsys::ofstream fout(sourcePath.c_str());
if (fout) {
fout << "# generated from CMake\n";
fout.flush();
fout.close();
// Force given file to have a very old timestamp, thus
// preventing dependent rebuilds.
this->ForceOld(sourcePath);
} else {
std::string error = "Could not create file: [";
error += sourcePath;
error += "] ";
cmSystemTools::Error(error.c_str(),
cmSystemTools::GetLastSystemError().c_str());
}
}
}
cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
if (this->ProjectType != csproj) {
this->WriteSource("CustomBuild", source, ">\n");
} else {
this->WriteString("<ItemGroup>\n", 1);
std::string link;
this->GetCSharpSourceLink(source, link);
this->WriteSource("None", source, ">\n");
if (!link.empty()) {
this->WriteString("<Link>", 3);
(*this->BuildFileStream) << link << "</Link>\n";
}
this->WriteString("</None>\n", 2);
this->WriteString("</ItemGroup>\n", 1);
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
cmCustomCommandGenerator ccg(command, *i, this->LocalGenerator);
std::string comment = lg->ConstructComment(ccg);
comment = cmVS10EscapeComment(comment);
std::string script = cmVS10EscapeXML(lg->ConstructScript(ccg));
// input files for custom command
std::stringstream inputs;
inputs << cmVS10EscapeXML(source->GetFullPath());
for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin();
d != ccg.GetDepends().end(); ++d) {
std::string dep;
if (this->LocalGenerator->GetRealDependency(*d, *i, dep)) {
this->ConvertToWindowsSlash(dep);
inputs << ";" << cmVS10EscapeXML(dep);
}
}
// output files for custom command
std::stringstream outputs;
const char* sep = "";
for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin();
o != ccg.GetOutputs().end(); ++o) {
std::string out = *o;
this->ConvertToWindowsSlash(out);
outputs << sep << cmVS10EscapeXML(out);
sep = ";";
}
if (this->ProjectType == csproj) {
std::string name = "CustomCommand_" + *i + "_" +
cmSystemTools::ComputeStringMD5(sourcePath);
std::string inputs_s = inputs.str();
std::string outputs_s = outputs.str();
comment = cmVS10EscapeQuotes(comment);
script = cmVS10EscapeQuotes(script);
inputs_s = cmVS10EscapeQuotes(inputs_s);
outputs_s = cmVS10EscapeQuotes(outputs_s);
this->WriteCustomRuleCSharp(*i, name, script, inputs_s, outputs_s,
comment);
} else {
this->WriteCustomRuleCpp(*i, script, inputs.str(), outputs.str(),
comment);
}
}
if (this->ProjectType != csproj) {
this->WriteString("</CustomBuild>\n", 2);
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
std::string const& config, std::string const& script,
std::string const& inputs, std::string const& outputs,
std::string const& comment)
{
this->WritePlatformConfigTag("Message", config, 3);
(*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
this->WritePlatformConfigTag("Command", config, 3);
(*this->BuildFileStream) << script << "</Command>\n";
this->WritePlatformConfigTag("AdditionalInputs", config, 3);
(*this->BuildFileStream) << inputs;
(*this->BuildFileStream) << ";%(AdditionalInputs)</AdditionalInputs>\n";
this->WritePlatformConfigTag("Outputs", config, 3);
(*this->BuildFileStream) << outputs << "</Outputs>\n";
if (this->LocalGenerator->GetVersion() >
cmGlobalVisualStudioGenerator::VS10) {
// VS >= 11 let us turn off linking of custom command outputs.
this->WritePlatformConfigTag("LinkObjects", config, 3);
(*this->BuildFileStream) << "false</LinkObjects>\n";
}
}
void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
std::string const& config, std::string const& name,
std::string const& script, std::string const& inputs,
std::string const& outputs, std::string const& comment)
{
this->CSharpCustomCommandNames.insert(name);
std::stringstream attributes;
attributes << "\n Name=\"" << name << "\"";
attributes << "\n Inputs=\"" << inputs << "\"";
attributes << "\n Outputs=\"" << outputs << "\"";
this->WritePlatformConfigTag("Target", config, 1, attributes.str().c_str(),
"\n");
if (!comment.empty()) {
this->WriteString("<Exec Command=\"", 2);
(*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment)
<< "\" />\n";
}
this->WriteString("<Exec Command=\"", 2);
(*this->BuildFileStream) << script << "\" />\n";
this->WriteString("</Target>\n", 1);
}
std::string cmVisualStudio10TargetGenerator::ConvertPath(
std::string const& path, bool forceRelative)
{
return forceRelative
? cmSystemTools::RelativePath(
this->LocalGenerator->GetCurrentBinaryDirectory(), path.c_str())
: path.c_str();
}
void cmVisualStudio10TargetGenerator::ConvertToWindowsSlash(std::string& s)
{
// first convert all of the slashes
std::string::size_type pos = 0;
while ((pos = s.find('/', pos)) != std::string::npos) {
s[pos] = '\\';
pos++;
}
}
void cmVisualStudio10TargetGenerator::WriteGroups()
{
if (this->ProjectType == csproj) {
return;
}
// collect up group information
std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
this->GeneratorTarget->GetAllConfigSources();
std::set<cmSourceGroup*> groupsUsed;
for (std::vector<cmGeneratorTarget::AllConfigSource>::const_iterator si =
sources.begin();
si != sources.end(); ++si) {
std::string const& source = si->Source->GetFullPath();
cmSourceGroup* sourceGroup =
this->Makefile->FindSourceGroup(source.c_str(), sourceGroups);
groupsUsed.insert(sourceGroup);
}
this->AddMissingSourceGroups(groupsUsed, sourceGroups);
// Write out group file
std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
path += "/";
path += this->Name;
path += computeProjectFileExtension(this->GeneratorTarget);
path += ".filters";
cmGeneratedFileStream fout(path.c_str());
fout.SetCopyIfDifferent(true);
char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
fout.write(magic, 3);
cmGeneratedFileStream* save = this->BuildFileStream;
this->BuildFileStream = &fout;
// get the tools version to use
const std::string toolsVer(this->GlobalGenerator->GetToolsVersion());
std::string project_defaults = "<?xml version=\"1.0\" encoding=\"" +
this->GlobalGenerator->Encoding() + "\"?>\n";
project_defaults.append("<Project ToolsVersion=\"");
project_defaults.append(toolsVer + "\" ");
project_defaults.append(
"xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n");
this->WriteString(project_defaults.c_str(), 0);
for (ToolSourceMap::const_iterator ti = this->Tools.begin();
ti != this->Tools.end(); ++ti) {
this->WriteGroupSources(ti->first.c_str(), ti->second, sourceGroups);
}
// Added files are images and the manifest.
if (!this->AddedFiles.empty()) {
this->WriteString("<ItemGroup>\n", 1);
for (std::vector<std::string>::const_iterator oi =
this->AddedFiles.begin();
oi != this->AddedFiles.end(); ++oi) {
std::string fileName =
cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(*oi));
if (fileName == "wmappmanifest.xml") {
this->WriteString("<XML Include=\"", 2);
(*this->BuildFileStream) << *oi << "\">\n";
this->WriteString("<Filter>Resource Files</Filter>\n", 3);
this->WriteString("</XML>\n", 2);
} else if (cmSystemTools::GetFilenameExtension(fileName) ==
".appxmanifest") {
this->WriteString("<AppxManifest Include=\"", 2);
(*this->BuildFileStream) << *oi << "\">\n";
this->WriteString("<Filter>Resource Files</Filter>\n", 3);
this->WriteString("</AppxManifest>\n", 2);
} else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx") {
this->WriteString("<None Include=\"", 2);
(*this->BuildFileStream) << *oi << "\">\n";
this->WriteString("<Filter>Resource Files</Filter>\n", 3);
this->WriteString("</None>\n", 2);
} else {
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << *oi << "\">\n";
this->WriteString("<Filter>Resource Files</Filter>\n", 3);
this->WriteString("</Image>\n", 2);
}
}
this->WriteString("</ItemGroup>\n", 1);
}
std::vector<cmSourceFile const*> resxObjs;
this->GeneratorTarget->GetResxSources(resxObjs, "");
if (!resxObjs.empty()) {
this->WriteString("<ItemGroup>\n", 1);
for (std::vector<cmSourceFile const*>::const_iterator oi =
resxObjs.begin();
oi != resxObjs.end(); ++oi) {
std::string obj = (*oi)->GetFullPath();
this->WriteString("<EmbeddedResource Include=\"", 2);
this->ConvertToWindowsSlash(obj);
(*this->BuildFileStream) << cmVS10EscapeXML(obj) << "\">\n";
this->WriteString("<Filter>Resource Files</Filter>\n", 3);
this->WriteString("</EmbeddedResource>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
}
this->WriteString("<ItemGroup>\n", 1);
for (std::set<cmSourceGroup*>::iterator g = groupsUsed.begin();
g != groupsUsed.end(); ++g) {
cmSourceGroup* sg = *g;
const char* name = sg->GetFullName();
if (strlen(name) != 0) {
this->WriteString("<Filter Include=\"", 2);
(*this->BuildFileStream) << name << "\">\n";
std::string guidName = "SG_Filter_";
guidName += name;
this->WriteString("<UniqueIdentifier>", 3);
std::string guid = this->GlobalGenerator->GetGUID(guidName);
(*this->BuildFileStream) << "{" << guid << "}"
<< "</UniqueIdentifier>\n";
this->WriteString("</Filter>\n", 2);
}
}
if (!resxObjs.empty() || !this->AddedFiles.empty()) {
this->WriteString("<Filter Include=\"Resource Files\">\n", 2);
std::string guidName = "SG_Filter_Resource Files";
this->WriteString("<UniqueIdentifier>", 3);
std::string guid = this->GlobalGenerator->GetGUID(guidName);
(*this->BuildFileStream) << "{" << guid << "}"
<< "</UniqueIdentifier>\n";
this->WriteString("<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;", 3);
(*this->BuildFileStream) << "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;";
(*this->BuildFileStream) << "mfcribbon-ms</Extensions>\n";
this->WriteString("</Filter>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
this->WriteString("</Project>\n", 0);
// restore stream pointer
this->BuildFileStream = save;
if (fout.Close()) {
this->GlobalGenerator->FileReplacedDuringGenerate(path);
}
}
// Add to groupsUsed empty source groups that have non-empty children.
void cmVisualStudio10TargetGenerator::AddMissingSourceGroups(
std::set<cmSourceGroup*>& groupsUsed,
const std::vector<cmSourceGroup>& allGroups)
{
for (std::vector<cmSourceGroup>::const_iterator current = allGroups.begin();
current != allGroups.end(); ++current) {
std::vector<cmSourceGroup> const& children = current->GetGroupChildren();
if (children.empty()) {
continue; // the group is really empty
}
this->AddMissingSourceGroups(groupsUsed, children);
cmSourceGroup* current_ptr = const_cast<cmSourceGroup*>(&(*current));
if (groupsUsed.find(current_ptr) != groupsUsed.end()) {
continue; // group has already been added to set
}
// check if it least one of the group's descendants is not empty
// (at least one child must already have been added)
std::vector<cmSourceGroup>::const_iterator child_it = children.begin();
while (child_it != children.end()) {
cmSourceGroup* child_ptr = const_cast<cmSourceGroup*>(&(*child_it));
if (groupsUsed.find(child_ptr) != groupsUsed.end()) {
break; // found a child that was already added => add current group too
}
child_it++;
}
if (child_it == children.end()) {
continue; // no descendants have source files => ignore this group
}
groupsUsed.insert(current_ptr);
}
}
void cmVisualStudio10TargetGenerator::WriteGroupSources(
const char* name, ToolSources const& sources,
std::vector<cmSourceGroup>& sourceGroups)
{
this->WriteString("<ItemGroup>\n", 1);
for (ToolSources::const_iterator s = sources.begin(); s != sources.end();
++s) {
cmSourceFile const* sf = s->SourceFile;
std::string const& source = sf->GetFullPath();
cmSourceGroup* sourceGroup =
this->Makefile->FindSourceGroup(source.c_str(), sourceGroups);
const char* filter = sourceGroup->GetFullName();
this->WriteString("<", 2);
std::string path = this->ConvertPath(source, s->RelativePath);
this->ConvertToWindowsSlash(path);
(*this->BuildFileStream) << name << " Include=\"" << cmVS10EscapeXML(path);
if (strlen(filter)) {
(*this->BuildFileStream) << "\">\n";
this->WriteString("<Filter>", 3);
(*this->BuildFileStream) << filter << "</Filter>\n";
this->WriteString("</", 2);
(*this->BuildFileStream) << name << ">\n";
} else {
(*this->BuildFileStream) << "\" />\n";
}
}
this->WriteString("</ItemGroup>\n", 1);
}
void cmVisualStudio10TargetGenerator::WriteHeaderSource(cmSourceFile const* sf)
{
std::string const& fileName = sf->GetFullPath();
if (this->IsResxHeader(fileName)) {
this->WriteSource("ClInclude", sf, ">\n");
this->WriteString("<FileType>CppForm</FileType>\n", 3);
this->WriteString("</ClInclude>\n", 2);
} else if (this->IsXamlHeader(fileName)) {
this->WriteSource("ClInclude", sf, ">\n");
this->WriteString("<DependentUpon>", 3);
std::string xamlFileName = fileName.substr(0, fileName.find_last_of("."));
(*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n";
this->WriteString("</ClInclude>\n", 2);
} else {
this->WriteSource("ClInclude", sf);
}
}
void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
{
bool toolHasSettings = false;
std::string tool = "None";
std::string shaderType;
std::string shaderEntryPoint;
std::string shaderModel;
std::string shaderAdditionalFlags;
std::string outputHeaderFile;
std::string variableName;
std::string settingsGenerator;
std::string settingsLastGenOutput;
std::string sourceLink;
std::string subType;
std::string copyToOutDir;
std::string includeInVsix;
std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
if (this->ProjectType == csproj) {
// EVERY extra source file must have a <Link>, otherwise it might not
// be visible in Visual Studio at all. The path relative to current
// source- or binary-dir is used within the link, if the file is
// in none of these paths, it is added with the plain filename without
// any path. This means the file will show up at root-level of the csproj
// (where CMakeLists.txt etc. are).
if (!this->InSourceBuild) {
toolHasSettings = true;
std::string fullFileName = sf->GetFullPath();
std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
if (fullFileName.find(binDir) != std::string::npos) {
sourceLink.clear();
} else if (fullFileName.find(srcDir) != std::string::npos) {
sourceLink = fullFileName.substr(srcDir.length() + 1);
} else {
// fallback: add plain filename without any path
sourceLink = cmsys::SystemTools::GetFilenameName(fullFileName);
}
if (!sourceLink.empty()) {
this->ConvertToWindowsSlash(sourceLink);
}
}
}
if (ext == "hlsl") {
tool = "FXCompile";
// Figure out the type of shader compiler to use.
if (const char* st = sf->GetProperty("VS_SHADER_TYPE")) {
shaderType = st;
toolHasSettings = true;
}
// Figure out which entry point to use if any
if (const char* se = sf->GetProperty("VS_SHADER_ENTRYPOINT")) {
shaderEntryPoint = se;
toolHasSettings = true;
}
// Figure out which shader model to use if any
if (const char* sm = sf->GetProperty("VS_SHADER_MODEL")) {
shaderModel = sm;
toolHasSettings = true;
}
// Figure out which output header file to use if any
if (const char* ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
outputHeaderFile = ohf;
toolHasSettings = true;
}
// Figure out which variable name to use if any
if (const char* vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
variableName = vn;
toolHasSettings = true;
}
// Figure out if there's any additional flags to use
if (const char* saf = sf->GetProperty("VS_SHADER_FLAGS")) {
shaderAdditionalFlags = saf;
toolHasSettings = true;
}
} else if (ext == "jpg" || ext == "png") {
tool = "Image";
} else if (ext == "resw") {
tool = "PRIResource";
} else if (ext == "xml") {
tool = "XML";
} else if (ext == "natvis") {
tool = "Natvis";
} else if (ext == "settings") {
// remove path to current source dir (if files are in current source dir)
if (!sourceLink.empty()) {
settingsLastGenOutput = sourceLink;
} else {
settingsLastGenOutput = sf->GetFullPath();
}
std::size_t pos = settingsLastGenOutput.find(".settings");
settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
settingsGenerator = "SettingsSingleFileGenerator";
toolHasSettings = true;
} else if (ext == "vsixmanifest") {
subType = "Designer";
}
if (const char* c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
copyToOutDir = c;
toolHasSettings = true;
}
if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
includeInVsix = "True";
tool = "Content";
toolHasSettings = true;
}
// Collect VS_CSHARP_* property values (if some are set)
std::map<std::string, std::string> sourceFileTags;
this->GetCSharpSourceProperties(sf, sourceFileTags);
if (this->NsightTegra) {
// Nsight Tegra needs specific file types to check up-to-dateness.
std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
if (name == "androidmanifest.xml" || name == "build.xml" ||
name == "proguard.cfg" || name == "proguard-project.txt" ||
ext == "properties") {
tool = "AndroidBuild";
} else if (ext == "java") {
tool = "JCompile";
} else if (ext == "asm" || ext == "s") {
tool = "ClCompile";
}
}
const char* toolOverride = sf->GetProperty("VS_TOOL_OVERRIDE");
if (toolOverride && *toolOverride) {
tool = toolOverride;
}
std::string deployContent;
std::string deployLocation;
if (this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore()) {
const char* content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
if (content && *content) {
toolHasSettings = true;
deployContent = content;
const char* location = sf->GetProperty("VS_DEPLOYMENT_LOCATION");
if (location && *location) {
deployLocation = location;
}
}
}
if (toolHasSettings) {
this->WriteSource(tool, sf, ">\n");
if (!deployContent.empty()) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(deployContent);
// Deployment location cannot be set on a configuration basis
if (!deployLocation.empty()) {
this->WriteString("<Link>", 3);
(*this->BuildFileStream) << deployLocation
<< "\\%(FileName)%(Extension)";
this->WriteString("</Link>\n", 0);
}
for (size_t i = 0; i != this->Configurations.size(); ++i) {
if (0 == strcmp(cge->Evaluate(this->LocalGenerator,
this->Configurations[i]),
"1")) {
this->WriteString("<DeploymentContent Condition=\""
"'$(Configuration)|$(Platform)'=='",
3);
(*this->BuildFileStream) << this->Configurations[i] << "|"
<< this->Platform << "'\">true";
this->WriteString("</DeploymentContent>\n", 0);
} else {
this->WriteString("<ExcludedFromBuild Condition=\""
"'$(Configuration)|$(Platform)'=='",
3);
(*this->BuildFileStream) << this->Configurations[i] << "|"
<< this->Platform << "'\">true";
this->WriteString("</ExcludedFromBuild>\n", 0);
}
}
}
if (!shaderType.empty()) {
this->WriteString("<ShaderType>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(shaderType)
<< "</ShaderType>\n";
}
if (!shaderEntryPoint.empty()) {
this->WriteString("<EntryPointName>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(shaderEntryPoint)
<< "</EntryPointName>\n";
}
if (!shaderModel.empty()) {
this->WriteString("<ShaderModel>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(shaderModel)
<< "</ShaderModel>\n";
}
if (!outputHeaderFile.empty()) {
for (size_t i = 0; i != this->Configurations.size(); ++i) {
this->WriteString("<HeaderFileOutput Condition=\""
"'$(Configuration)|$(Platform)'=='",
3);
(*this->BuildFileStream) << this->Configurations[i] << "|"
<< this->Platform << "'\">"
<< cmVS10EscapeXML(outputHeaderFile);
this->WriteString("</HeaderFileOutput>\n", 0);
}
}
if (!variableName.empty()) {
for (size_t i = 0; i != this->Configurations.size(); ++i) {
this->WriteString("<VariableName Condition=\""
"'$(Configuration)|$(Platform)'=='",
3);
(*this->BuildFileStream) << this->Configurations[i] << "|"
<< this->Platform << "'\">"
<< cmVS10EscapeXML(variableName);
this->WriteString("</VariableName>\n", 0);
}
}
if (!shaderAdditionalFlags.empty()) {
this->WriteString("<AdditionalOptions>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(shaderAdditionalFlags)
<< "</AdditionalOptions>\n";
}
if (!settingsGenerator.empty()) {
this->WriteString("<Generator>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(settingsGenerator)
<< "</Generator>\n";
}
if (!settingsLastGenOutput.empty()) {
this->WriteString("<LastGenOutput>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(settingsLastGenOutput)
<< "</LastGenOutput>\n";
}
if (!sourceLink.empty()) {
this->WriteString("<Link>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(sourceLink) << "</Link>\n";
}
if (!subType.empty()) {
this->WriteString("<SubType>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(subType) << "</SubType>\n";
}
if (!copyToOutDir.empty()) {
this->WriteString("<CopyToOutputDirectory>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(copyToOutDir)
<< "</CopyToOutputDirectory>\n";
}
if (!includeInVsix.empty()) {
this->WriteString("<IncludeInVSIX>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(includeInVsix)
<< "</IncludeInVSIX>\n";
}
// write source file specific tags
this->WriteCSharpSourceProperties(sourceFileTags);
this->WriteString("</", 2);
(*this->BuildFileStream) << tool << ">\n";
} else {
this->WriteSource(tool, sf);
}
}
void cmVisualStudio10TargetGenerator::WriteSource(std::string const& tool,
cmSourceFile const* sf,
const char* end)
{
// Visual Studio tools append relative paths to the current dir, as in:
//
// c:\path\to\current\dir\..\..\..\relative\path\to\source.c
//
// and fail if this exceeds the maximum allowed path length. Our path
// conversion uses full paths when possible to allow deeper trees.
// However, CUDA 8.0 msbuild rules fail on absolute paths so for CUDA
// we must use relative paths.
bool forceRelative = sf->GetLanguage() == "CUDA";
std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative);
if (this->LocalGenerator->GetVersion() ==
cmGlobalVisualStudioGenerator::VS10 &&
cmSystemTools::FileIsFullPath(sourceFile.c_str())) {
// Normal path conversion resulted in a full path. VS 10 (but not 11)
// refuses to show the property page in the IDE for a source file with a
// full path (not starting in a '.' or '/' AFAICT). CMake <= 2.8.4 used a
// relative path but to allow deeper build trees CMake 2.8.[5678] used a
// full path except for custom commands. Custom commands do not work
// without a relative path, but they do not seem to be involved in tools
// with the above behavior. For other sources we now use a relative path
// when the combined path will not be too long so property pages appear.
std::string sourceRel = this->ConvertPath(sf->GetFullPath(), true);
size_t const maxLen = 250;
if (sf->GetCustomCommand() ||
((strlen(this->LocalGenerator->GetCurrentBinaryDirectory()) + 1 +
sourceRel.length()) <= maxLen)) {
forceRelative = true;
sourceFile = sourceRel;
} else {
this->GlobalGenerator->PathTooLong(this->GeneratorTarget, sf, sourceRel);
}
}
this->ConvertToWindowsSlash(sourceFile);
this->WriteString("<", 2);
(*this->BuildFileStream) << tool << " Include=\""
<< cmVS10EscapeXML(sourceFile) << "\""
<< (end ? end : " />\n");
ToolSource toolSource = { sf, forceRelative };
this->Tools[tool].push_back(toolSource);
}
void cmVisualStudio10TargetGenerator::WriteAllSources()
{
if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
return;
}
this->WriteString("<ItemGroup>\n", 1);
std::vector<size_t> all_configs;
for (size_t ci = 0; ci < this->Configurations.size(); ++ci) {
all_configs.push_back(ci);
}
std::vector<cmGeneratorTarget::AllConfigSource> const& sources =
this->GeneratorTarget->GetAllConfigSources();
for (std::vector<cmGeneratorTarget::AllConfigSource>::const_iterator si =
sources.begin();
si != sources.end(); ++si) {
std::string tool;
switch (si->Kind) {
case cmGeneratorTarget::SourceKindAppManifest:
tool = "AppxManifest";
break;
case cmGeneratorTarget::SourceKindCertificate:
tool = "None";
break;
case cmGeneratorTarget::SourceKindCustomCommand:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindExternalObject:
tool = "Object";
if (this->LocalGenerator->GetVersion() <
cmGlobalVisualStudioGenerator::VS11) {
// For VS == 10 we cannot use LinkObjects to avoid linking custom
// command outputs. If an object file is generated in this target,
// then vs10 will use it in the build, and we have to list it as
// None instead of Object.
std::vector<cmSourceFile*> const* d =
this->GeneratorTarget->GetSourceDepends(si->Source);
if (d && !d->empty()) {
tool = "None";
}
}
break;
case cmGeneratorTarget::SourceKindExtra:
this->WriteExtraSource(si->Source);
break;
case cmGeneratorTarget::SourceKindHeader:
this->WriteHeaderSource(si->Source);
break;
case cmGeneratorTarget::SourceKindIDL:
tool = "Midl";
break;
case cmGeneratorTarget::SourceKindManifest:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindModuleDefinition:
tool = "None";
break;
case cmGeneratorTarget::SourceKindObjectSource: {
const std::string& lang = si->Source->GetLanguage();
if (lang == "C" || lang == "CXX") {
tool = "ClCompile";
} else if (lang == "ASM_MASM" &&
this->GlobalGenerator->IsMasmEnabled()) {
tool = "MASM";
} else if (lang == "ASM_NASM" &&
this->GlobalGenerator->IsNasmEnabled()) {
tool = "NASM";
} else if (lang == "RC") {
tool = "ResourceCompile";
} else if (lang == "CSharp") {
tool = "Compile";
} else if (lang == "CUDA" && this->GlobalGenerator->IsCudaEnabled()) {
tool = "CudaCompile";
} else {
tool = "None";
}
} break;
case cmGeneratorTarget::SourceKindResx:
// Handled elsewhere.
break;
case cmGeneratorTarget::SourceKindXaml:
// Handled elsewhere.
break;
}
if (!tool.empty()) {
// Compute set of configurations to exclude, if any.
std::vector<size_t> const& include_configs = si->Configs;
std::vector<size_t> exclude_configs;
std::set_difference(all_configs.begin(), all_configs.end(),
include_configs.begin(), include_configs.end(),
std::back_inserter(exclude_configs));
if (si->Kind == cmGeneratorTarget::SourceKindObjectSource) {
// FIXME: refactor generation to avoid tracking XML syntax state.
this->WriteSource(tool, si->Source, " ");
bool have_nested = this->OutputSourceSpecificFlags(si->Source);
if (!exclude_configs.empty()) {
if (!have_nested) {
(*this->BuildFileStream) << ">\n";
}
this->WriteExcludeFromBuild(exclude_configs);
have_nested = true;
}
if (have_nested) {
this->WriteString("</", 2);
(*this->BuildFileStream) << tool << ">\n";
} else {
(*this->BuildFileStream) << " />\n";
}
} else if (!exclude_configs.empty()) {
this->WriteSource(tool, si->Source, ">\n");
this->WriteExcludeFromBuild(exclude_configs);
this->WriteString("</", 2);
(*this->BuildFileStream) << tool << ">\n";
} else {
this->WriteSource(tool, si->Source);
}
}
}
if (this->IsMissingFiles) {
this->WriteMissingFiles();
}
this->WriteString("</ItemGroup>\n", 1);
}
bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
cmSourceFile const* source)
{
cmSourceFile const& sf = *source;
std::string objectName;
if (this->GeneratorTarget->HasExplicitObjectName(&sf)) {
objectName = this->GeneratorTarget->GetObjectName(&sf);
}
std::string flags;
bool configDependentFlags = false;
std::string defines;
if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) {
if (cmGeneratorExpression::Find(cflags) != std::string::npos) {
configDependentFlags = true;
}
flags += cflags;
}
if (const char* cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
defines += cdefs;
}
std::string lang =
this->GlobalGenerator->GetLanguageFromExtension(sf.GetExtension().c_str());
std::string sourceLang = this->LocalGenerator->GetSourceFileLanguage(sf);
const std::string& linkLanguage =
this->GeneratorTarget->GetLinkerLanguage("");
bool needForceLang = false;
// source file does not match its extension language
if (lang != sourceLang) {
needForceLang = true;
lang = sourceLang;
}
// if the source file does not match the linker language
// then force c or c++
const char* compileAs = 0;
if (needForceLang || (linkLanguage != lang)) {
if (lang == "CXX") {
// force a C++ file type
compileAs = "CompileAsCpp";
} else if (lang == "C") {
// force to c
compileAs = "CompileAsC";
}
}
bool noWinRT = this->TargetCompileAsWinRT && lang == "C";
bool hasFlags = false;
// for the first time we need a new line if there is something
// produced here.
const char* firstString = ">\n";
if (!objectName.empty()) {
(*this->BuildFileStream) << firstString;
firstString = "";
hasFlags = true;
this->WriteString("<ObjectFileName>", 3);
(*this->BuildFileStream) << "$(IntDir)/" << objectName
<< "</ObjectFileName>\n";
}
for (std::vector<std::string>::const_iterator config =
this->Configurations.begin();
config != this->Configurations.end(); ++config) {
std::string configUpper = cmSystemTools::UpperCase(*config);
std::string configDefines = defines;
std::string defPropName = "COMPILE_DEFINITIONS_";
defPropName += configUpper;
if (const char* ccdefs = sf.GetProperty(defPropName)) {
if (!configDefines.empty()) {
configDefines += ";";
}
configDefines += ccdefs;
}
// if we have flags or defines for this config then
// use them
if (!flags.empty() || configDependentFlags || !configDefines.empty() ||
compileAs || noWinRT) {
(*this->BuildFileStream) << firstString;
firstString = ""; // only do firstString once
hasFlags = true;
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
cmIDEFlagTable const* flagtable = nullptr;
const std::string& srclang = source->GetLanguage();
if (srclang == "C" || srclang == "CXX") {
flagtable = gg->GetClFlagTable();
} else if (srclang == "ASM_MASM" &&
this->GlobalGenerator->IsMasmEnabled()) {
flagtable = gg->GetMasmFlagTable();
} else if (lang == "ASM_NASM" &&
this->GlobalGenerator->IsNasmEnabled()) {
flagtable = gg->GetNasmFlagTable();
} else if (srclang == "RC") {
flagtable = gg->GetRcFlagTable();
} else if (srclang == "CSharp") {
flagtable = gg->GetCSharpFlagTable();
}
cmVisualStudioGeneratorOptions clOptions(
this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
flagtable, 0, this);
if (compileAs) {
clOptions.AddFlag("CompileAs", compileAs);
}
if (noWinRT) {
clOptions.AddFlag("CompileAsWinRT", "false");
}
if (configDependentFlags) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(flags);
std::string evaluatedFlags = cge->Evaluate(
this->LocalGenerator, *config, false, this->GeneratorTarget);
clOptions.Parse(evaluatedFlags.c_str());
} else {
clOptions.Parse(flags.c_str());
}
if (clOptions.HasFlag("AdditionalIncludeDirectories")) {
clOptions.AppendFlag("AdditionalIncludeDirectories",
"%(AdditionalIncludeDirectories)");
}
if (clOptions.HasFlag("DisableSpecificWarnings")) {
clOptions.AppendFlag("DisableSpecificWarnings",
"%(DisableSpecificWarnings)");
}
clOptions.AddDefines(configDefines.c_str());
clOptions.SetConfiguration((*config).c_str());
clOptions.PrependInheritedString("AdditionalOptions");
clOptions.OutputFlagMap(*this->BuildFileStream, " ");
clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", lang);
}
}
if (this->IsXamlSource(source->GetFullPath())) {
(*this->BuildFileStream) << firstString;
firstString = ""; // only do firstString once
hasFlags = true;
this->WriteString("<DependentUpon>", 3);
const std::string& fileName = source->GetFullPath();
std::string xamlFileName = fileName.substr(0, fileName.find_last_of("."));
(*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n";
}
if (this->ProjectType == csproj) {
std::string f = source->GetFullPath();
typedef std::map<std::string, std::string> CsPropMap;
CsPropMap sourceFileTags;
// set <Link> tag if necessary
std::string link;
this->GetCSharpSourceLink(source, link);
if (!link.empty()) {
sourceFileTags["Link"] = link;
}
this->GetCSharpSourceProperties(&sf, sourceFileTags);
// write source file specific tags
if (!sourceFileTags.empty()) {
hasFlags = true;
(*this->BuildFileStream) << firstString;
firstString = "";
this->WriteCSharpSourceProperties(sourceFileTags);
}
}
return hasFlags;
}
void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild(
std::vector<size_t> const& exclude_configs)
{
for (std::vector<size_t>::const_iterator ci = exclude_configs.begin();
ci != exclude_configs.end(); ++ci) {
this->WriteString("", 3);
(*this->BuildFileStream)
<< "<ExcludedFromBuild Condition=\"'$(Configuration)|$(Platform)'=='"
<< cmVS10EscapeXML(this->Configurations[*ci]) << "|"
<< cmVS10EscapeXML(this->Platform) << "'\">true</ExcludedFromBuild>\n";
}
}
void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
{
cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
if (ttype > cmStateEnums::GLOBAL_TARGET) {
return;
}
if (this->ProjectType == csproj) {
return;
}
this->WriteString("<PropertyGroup>\n", 1);
this->WriteString("<_ProjectFileVersion>10.0.20506.1"
"</_ProjectFileVersion>\n",
2);
for (std::vector<std::string>::const_iterator config =
this->Configurations.begin();
config != this->Configurations.end(); ++config) {
if (ttype >= cmStateEnums::UTILITY) {
this->WritePlatformConfigTag("IntDir", *config, 2);
*this->BuildFileStream
<< "$(Platform)\\$(Configuration)\\$(ProjectName)\\"
<< "</IntDir>\n";
} else {
std::string intermediateDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
intermediateDir += "/";
intermediateDir += *config;
intermediateDir += "/";
std::string outDir;
std::string targetNameFull;
if (ttype == cmStateEnums::OBJECT_LIBRARY) {
outDir = intermediateDir;
targetNameFull = this->GeneratorTarget->GetName();
targetNameFull += ".lib";
} else {
outDir = this->GeneratorTarget->GetDirectory(*config) + "/";
targetNameFull = this->GeneratorTarget->GetFullName(*config);
}
this->ConvertToWindowsSlash(intermediateDir);
this->ConvertToWindowsSlash(outDir);
this->WritePlatformConfigTag("OutDir", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(outDir) << "</OutDir>\n";
this->WritePlatformConfigTag("IntDir", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(intermediateDir)
<< "</IntDir>\n";
if (const char* workingDir = this->GeneratorTarget->GetProperty(
"VS_DEBUGGER_WORKING_DIRECTORY")) {
this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory", *config,
2);
*this->BuildFileStream << cmVS10EscapeXML(workingDir)
<< "</LocalDebuggerWorkingDirectory>\n";
}
std::string name =
cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
this->WritePlatformConfigTag("TargetName", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(name) << "</TargetName>\n";
std::string ext =
cmSystemTools::GetFilenameLastExtension(targetNameFull);
if (ext.empty()) {
// An empty TargetExt causes a default extension to be used.
// A single "." appears to be treated as an empty extension.
ext = ".";
}
this->WritePlatformConfigTag("TargetExt", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(ext) << "</TargetExt>\n";
this->OutputLinkIncremental(*config);
}
}
this->WriteString("</PropertyGroup>\n", 1);
}
void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
std::string const& configName)
{
if (!this->MSTools) {
return;
}
if (this->ProjectType == csproj) {
return;
}
// static libraries and things greater than modules do not need
// to set this option
if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
return;
}
Options& linkOptions = *(this->LinkOptions[configName]);
const char* incremental = linkOptions.GetFlag("LinkIncremental");
this->WritePlatformConfigTag("LinkIncremental", configName, 2);
*this->BuildFileStream << (incremental ? incremental : "true")
<< "</LinkIncremental>\n";
linkOptions.RemoveFlag("LinkIncremental");
const char* manifest = linkOptions.GetFlag("GenerateManifest");
this->WritePlatformConfigTag("GenerateManifest", configName, 2);
*this->BuildFileStream << (manifest ? manifest : "true")
<< "</GenerateManifest>\n";
linkOptions.RemoveFlag("GenerateManifest");
// Some link options belong here. Use them now and remove them so that
// WriteLinkOptions does not use them.
const char* flags[] = { "LinkDelaySign", "LinkKeyFile", 0 };
for (const char** f = flags; *f; ++f) {
const char* flag = *f;
if (const char* value = linkOptions.GetFlag(flag)) {
this->WritePlatformConfigTag(flag, configName, 2);
*this->BuildFileStream << value << "</" << flag << ">\n";
linkOptions.RemoveFlag(flag);
}
}
}
bool cmVisualStudio10TargetGenerator::ComputeClOptions()
{
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeClOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeClOptions(
std::string const& configName)
{
// much of this was copied from here:
// copied from cmLocalVisualStudio7Generator.cxx 805
// TODO: Integrate code below with cmLocalVisualStudio7Generator.
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
std::unique_ptr<Options> pOptions;
switch (this->ProjectType) {
case vcxproj:
pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
break;
case csproj:
pOptions =
cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
gg->GetCSharpFlagTable());
break;
}
Options& clOptions = *pOptions;
std::string flags;
const std::string& linkLanguage =
this->GeneratorTarget->GetLinkerLanguage(configName);
if (linkLanguage.empty()) {
cmSystemTools::Error(
"CMake can not determine linker language for target: ",
this->Name.c_str());
return false;
}
// Choose a language whose flags to use for ClCompile.
static const char* clLangs[] = { "CXX", "C", "Fortran", "CSharp" };
std::string langForClCompile;
if (std::find(cmArrayBegin(clLangs), cmArrayEnd(clLangs), linkLanguage) !=
cmArrayEnd(clLangs)) {
langForClCompile = linkLanguage;
} else {
std::set<std::string> languages;
this->GeneratorTarget->GetLanguages(languages, configName);
for (const char* const* l = cmArrayBegin(clLangs);
l != cmArrayEnd(clLangs); ++l) {
if (languages.find(*l) != languages.end()) {
langForClCompile = *l;
break;
}
}
}
if (!langForClCompile.empty()) {
std::string baseFlagVar = "CMAKE_";
baseFlagVar += langForClCompile;
baseFlagVar += "_FLAGS";
flags =
this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
baseFlagVar);
std::string flagVar =
baseFlagVar + std::string("_") + cmSystemTools::UpperCase(configName);
flags += " ";
flags +=
this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
flagVar);
this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
langForClCompile, configName);
}
// set the correct language
if (linkLanguage == "C") {
clOptions.AddFlag("CompileAs", "CompileAsC");
}
if (linkLanguage == "CXX") {
clOptions.AddFlag("CompileAs", "CompileAsCpp");
}
// Check IPO related warning/error.
this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName);
// Get preprocessor definitions for this directory.
std::string defineFlags =
this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags();
if (this->MSTools) {
if (this->ProjectType == vcxproj) {
clOptions.FixExceptionHandlingDefault();
clOptions.AddFlag("PrecompiledHeader", "NotUsing");
std::string asmLocation = configName + "/";
clOptions.AddFlag("AssemblerListingLocation", asmLocation.c_str());
}
}
clOptions.Parse(flags.c_str());
clOptions.Parse(defineFlags.c_str());
std::vector<std::string> targetDefines;
switch (this->ProjectType) {
case vcxproj:
this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
"CXX");
break;
case csproj:
this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
"CSharp");
break;
}
clOptions.AddDefines(targetDefines);
if (this->MSTools) {
clOptions.SetVerboseMakefile(
this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
}
// Add a definition for the configuration name.
std::string configDefine = "CMAKE_INTDIR=\"";
configDefine += configName;
configDefine += "\"";
clOptions.AddDefine(configDefine);
if (const char* exportMacro = this->GeneratorTarget->GetExportMacro()) {
clOptions.AddDefine(exportMacro);
}
if (this->MSTools) {
// If we have the VS_WINRT_COMPONENT set then force Compile as WinRT.
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
clOptions.AddFlag("CompileAsWinRT", "true");
// For WinRT components, add the _WINRT_DLL define to produce a lib
if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
clOptions.AddDefine("_WINRT_DLL");
}
} else if (this->GlobalGenerator->TargetsWindowsStore() ||
this->GlobalGenerator->TargetsWindowsPhone()) {
if (!clOptions.IsWinRt()) {
clOptions.AddFlag("CompileAsWinRT", "false");
}
}
if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) {
if (cmSystemTools::IsOn(winRT)) {
this->TargetCompileAsWinRT = true;
}
}
}
if (this->ProjectType != csproj && clOptions.IsManaged()) {
this->Managed = true;
std::string managedType = clOptions.GetFlag("CompileAsManaged");
if (managedType == "Safe") {
// force empty calling convention if safe clr is used
clOptions.AddFlag("CallingConvention", "");
}
}
if (this->ProjectType == csproj) {
// /nowin32manifest overrides /win32manifest: parameter
if (clOptions.HasFlag("NoWin32Manifest")) {
clOptions.RemoveFlag("ApplicationManifest");
}
}
this->ClOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteClOptions(
std::string const& configName, std::vector<std::string> const& includes)
{
Options& clOptions = *(this->ClOptions[configName]);
if (this->ProjectType == csproj) {
return;
}
this->WriteString("<ClCompile>\n", 2);
clOptions.PrependInheritedString("AdditionalOptions");
clOptions.AppendFlag("AdditionalIncludeDirectories", includes);
clOptions.AppendFlag("AdditionalIncludeDirectories",
"%(AdditionalIncludeDirectories)");
clOptions.OutputFlagMap(*this->BuildFileStream, " ");
clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "CXX");
if (this->NsightTegra) {
if (const char* processMax =
this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) {
this->WriteString("<ProcessMax>", 3);
*this->BuildFileStream << cmVS10EscapeXML(processMax)
<< "</ProcessMax>\n";
}
}
if (this->MSTools) {
cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
const char* toolset = this->GlobalGenerator->GetPlatformToolset();
if (toolset && clangToolset.find(toolset)) {
this->WriteString("<ObjectFileName>"
"$(IntDir)%(filename).obj"
"</ObjectFileName>\n",
3);
} else {
this->WriteString("<ObjectFileName>$(IntDir)</ObjectFileName>\n", 3);
}
// If not in debug mode, write the DebugInformationFormat field
// without value so PDBs don't get generated uselessly.
if (!clOptions.IsDebug()) {
this->WriteString("<DebugInformationFormat>"
"</DebugInformationFormat>\n",
3);
}
// Specify the compiler program database file if configured.
std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
if (!pdb.empty()) {
this->ConvertToWindowsSlash(pdb);
this->WriteString("<ProgramDataBaseFileName>", 3);
*this->BuildFileStream << cmVS10EscapeXML(pdb)
<< "</ProgramDataBaseFileName>\n";
}
}
this->WriteString("</ClCompile>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
{
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeRcOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
std::string const& configName)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
Options& rcOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
std::string rcConfigFlagsVar = std::string("CMAKE_RC_FLAGS_") + CONFIG;
std::string flags =
std::string(this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS")) +
std::string(" ") +
std::string(this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
rcOptions.Parse(flags.c_str());
// For historical reasons, add the C preprocessor defines to RC.
Options& clOptions = *(this->ClOptions[configName]);
rcOptions.AddDefines(clOptions.GetDefines());
this->RcOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteRCOptions(
std::string const& configName, std::vector<std::string> const& includes)
{
if (!this->MSTools) {
return;
}
this->WriteString("<ResourceCompile>\n", 2);
Options& rcOptions = *(this->RcOptions[configName]);
rcOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "RC");
rcOptions.AppendFlag("AdditionalIncludeDirectories", includes);
rcOptions.AppendFlag("AdditionalIncludeDirectories",
"%(AdditionalIncludeDirectories)");
rcOptions.PrependInheritedString("AdditionalOptions");
rcOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</ResourceCompile>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeCudaOptions()
{
if (!this->GlobalGenerator->IsCudaEnabled()) {
return true;
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeCudaOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
std::string const& configName)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
Options& cudaOptions = *pOptions;
// Get compile flags for CUDA in this directory.
std::string CONFIG = cmSystemTools::UpperCase(configName);
std::string configFlagsVar = std::string("CMAKE_CUDA_FLAGS_") + CONFIG;
std::string flags =
std::string(this->Makefile->GetSafeDefinition("CMAKE_CUDA_FLAGS")) +
std::string(" ") +
std::string(this->Makefile->GetSafeDefinition(configFlagsVar));
this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, "CUDA",
configName);
// Get preprocessor definitions for this directory.
std::string defineFlags =
this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags();
cudaOptions.Parse(flags.c_str());
cudaOptions.Parse(defineFlags.c_str());
cudaOptions.ParseFinish();
if (this->GeneratorTarget->GetPropertyAsBool("CUDA_SEPARABLE_COMPILATION")) {
cudaOptions.AddFlag("GenerateRelocatableDeviceCode", "true");
} else if (this->GeneratorTarget->GetPropertyAsBool(
"CUDA_PTX_COMPILATION")) {
cudaOptions.AddFlag("NvccCompilation", "ptx");
// We drop the %(Extension) component as CMake expects all PTX files
// to not have the source file extension at all
cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
}
// CUDA automatically passes the proper '--machine' flag to nvcc
// for the current architecture, but does not reflect this default
// in the user-visible IDE settings. Set it explicitly.
if (this->Platform == "x64") {
cudaOptions.AddFlag("TargetMachinePlatform", "64");
}
// Convert the host compiler options to the toolset's abstractions
// using a secondary flag table.
cudaOptions.ClearTables();
cudaOptions.AddTable(gg->GetCudaHostFlagTable());
cudaOptions.Reparse("AdditionalCompilerOptions");
// `CUDA 8.0.targets` places AdditionalCompilerOptions before nvcc!
// Pass them through -Xcompiler in AdditionalOptions instead.
if (const char* acoPtr = cudaOptions.GetFlag("AdditionalCompilerOptions")) {
std::string aco = acoPtr;
cudaOptions.RemoveFlag("AdditionalCompilerOptions");
if (!aco.empty()) {
aco = this->LocalGenerator->EscapeForShell(aco, false);
cudaOptions.AppendFlagString("AdditionalOptions", "-Xcompiler=" + aco);
}
}
cudaOptions.FixCudaCodeGeneration();
std::vector<std::string> targetDefines;
this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
"CUDA");
cudaOptions.AddDefines(targetDefines);
// Add a definition for the configuration name.
std::string configDefine = "CMAKE_INTDIR=\"";
configDefine += configName;
configDefine += "\"";
cudaOptions.AddDefine(configDefine);
if (const char* exportMacro = this->GeneratorTarget->GetExportMacro()) {
cudaOptions.AddDefine(exportMacro);
}
this->CudaOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteCudaOptions(
std::string const& configName, std::vector<std::string> const& includes)
{
if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
return;
}
this->WriteString("<CudaCompile>\n", 2);
Options& cudaOptions = *(this->CudaOptions[configName]);
cudaOptions.AppendFlag("Include", includes);
cudaOptions.AppendFlag("Include", "%(Include)");
cudaOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "CUDA");
cudaOptions.PrependInheritedString("AdditionalOptions");
cudaOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</CudaCompile>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions()
{
if (!this->GlobalGenerator->IsCudaEnabled()) {
return true;
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeCudaLinkOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
std::string const& configName)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
Options& cudaLinkOptions = *pOptions;
// Determine if we need to do a device link
bool doDeviceLinking = false;
switch (this->GeneratorTarget->GetType()) {
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::EXECUTABLE:
doDeviceLinking = true;
break;
case cmStateEnums::STATIC_LIBRARY:
doDeviceLinking = this->GeneratorTarget->GetPropertyAsBool(
"CUDA_RESOLVE_DEVICE_SYMBOLS");
break;
default:
break;
}
cudaLinkOptions.AddFlag("PerformDeviceLink",
doDeviceLinking ? "true" : "false");
// Suppress deprecation warnings for default GPU targets during device link.
if (cmSystemTools::VersionCompareGreaterEq(
this->GlobalGenerator->GetPlatformToolsetCudaString(), "8.0")) {
cudaLinkOptions.AppendFlagString("AdditionalOptions",
"-Wno-deprecated-gpu-targets");
}
this->CudaLinkOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions(
std::string const& configName)
{
if (this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
return;
}
if (!this->MSTools || !this->GlobalGenerator->IsCudaEnabled()) {
return;
}
this->WriteString("<CudaLink>\n", 2);
Options& cudaLinkOptions = *(this->CudaLinkOptions[configName]);
cudaLinkOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</CudaLink>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
{
if (!this->GlobalGenerator->IsMasmEnabled()) {
return true;
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeMasmOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
std::string const& configName)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
Options& masmOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
std::string configFlagsVar = std::string("CMAKE_ASM_MASM_FLAGS_") + CONFIG;
std::string flags =
std::string(this->Makefile->GetSafeDefinition("CMAKE_ASM_MASM_FLAGS")) +
std::string(" ") +
std::string(this->Makefile->GetSafeDefinition(configFlagsVar));
masmOptions.Parse(flags.c_str());
this->MasmOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteMasmOptions(
std::string const& configName, std::vector<std::string> const& includes)
{
if (!this->MSTools || !this->GlobalGenerator->IsMasmEnabled()) {
return;
}
this->WriteString("<MASM>\n", 2);
// Preprocessor definitions and includes are shared with clOptions.
Options& clOptions = *(this->ClOptions[configName]);
clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "ASM_MASM");
Options& masmOptions = *(this->MasmOptions[configName]);
masmOptions.AppendFlag("IncludePaths", includes);
masmOptions.AppendFlag("IncludePaths", "%(IncludePaths)");
masmOptions.PrependInheritedString("AdditionalOptions");
masmOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</MASM>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeNasmOptions()
{
if (!this->GlobalGenerator->IsNasmEnabled()) {
return true;
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeNasmOptions(*i)) {
return false;
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
std::string const& configName)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions = cm::make_unique<Options>(
this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
Options& nasmOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
std::string configFlagsVar = std::string("CMAKE_ASM_NASM_FLAGS_") + CONFIG;
std::string flags =
std::string(this->Makefile->GetSafeDefinition("CMAKE_ASM_NASM_FLAGS")) +
std::string(" -f") + std::string(this->Makefile->GetSafeDefinition(
"CMAKE_ASM_NASM_OBJECT_FORMAT")) +
std::string(" ") +
std::string(this->Makefile->GetSafeDefinition(configFlagsVar));
nasmOptions.Parse(flags.c_str());
this->NasmOptions[configName] = pOptions.release();
return true;
}
void cmVisualStudio10TargetGenerator::WriteNasmOptions(
std::string const& configName, std::vector<std::string> includes)
{
if (!this->GlobalGenerator->IsNasmEnabled()) {
return;
}
this->WriteString("<NASM>\n", 2);
Options& nasmOptions = *(this->NasmOptions[configName]);
for (size_t i = 0; i < includes.size(); i++) {
includes[i] += "\\";
}
nasmOptions.AppendFlag("IncludePaths", includes);
nasmOptions.AppendFlag("IncludePaths", "%(IncludePaths)");
nasmOptions.OutputFlagMap(*this->BuildFileStream, " ");
nasmOptions.PrependInheritedString("AdditionalOptions");
nasmOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "ASM_NASM");
// Preprocessor definitions and includes are shared with clOptions.
Options& clOptions = *(this->ClOptions[configName]);
clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ",
"\n", "ASM_NASM");
this->WriteString("</NASM>\n", 2);
}
void cmVisualStudio10TargetGenerator::WriteLibOptions(
std::string const& config)
{
if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
return;
}
std::string libflags;
this->LocalGenerator->GetStaticLibraryFlags(
libflags, cmSystemTools::UpperCase(config), this->GeneratorTarget);
if (!libflags.empty()) {
this->WriteString("<Lib>\n", 2);
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
cmVisualStudioGeneratorOptions libOptions(
this->LocalGenerator, cmVisualStudioGeneratorOptions::Linker,
gg->GetLibFlagTable(), 0, this);
libOptions.Parse(libflags.c_str());
libOptions.PrependInheritedString("AdditionalOptions");
libOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</Lib>\n", 2);
}
// We cannot generate metadata for static libraries. WindowsPhone
// and WindowsStore tools look at GenerateWindowsMetadata in the
// Link tool options even for static libraries.
if (this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore()) {
this->WriteString("<Link>\n", 2);
this->WriteString("<GenerateWindowsMetadata>false"
"</GenerateWindowsMetadata>\n",
3);
this->WriteString("</Link>\n", 2);
}
}
void cmVisualStudio10TargetGenerator::WriteManifestOptions(
std::string const& config)
{
if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
return;
}
std::vector<cmSourceFile const*> manifest_srcs;
this->GeneratorTarget->GetManifests(manifest_srcs, config);
if (!manifest_srcs.empty()) {
this->WriteString("<Manifest>\n", 2);
this->WriteString("<AdditionalManifestFiles>", 3);
for (std::vector<cmSourceFile const*>::const_iterator mi =
manifest_srcs.begin();
mi != manifest_srcs.end(); ++mi) {
std::string m = this->ConvertPath((*mi)->GetFullPath(), false);
this->ConvertToWindowsSlash(m);
(*this->BuildFileStream) << m << ";";
}
(*this->BuildFileStream) << "</AdditionalManifestFiles>\n";
this->WriteString("</Manifest>\n", 2);
}
}
void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
std::string const& configName)
{
// Look through the sources for AndroidManifest.xml and use
// its location as the root source directory.
std::string rootDir = this->LocalGenerator->GetCurrentSourceDirectory();
{
std::vector<cmSourceFile const*> extraSources;
this->GeneratorTarget->GetExtraSources(extraSources, "");
for (std::vector<cmSourceFile const*>::const_iterator si =
extraSources.begin();
si != extraSources.end(); ++si) {
if ("androidmanifest.xml" ==
cmSystemTools::LowerCase((*si)->GetLocation().GetName())) {
rootDir = (*si)->GetLocation().GetDirectory();
break;
}
}
}
// Tell MSBuild to launch Ant.
{
std::string antBuildPath = rootDir;
this->WriteString("<AntBuild>\n", 2);
this->WriteString("<AntBuildPath>", 3);
this->ConvertToWindowsSlash(antBuildPath);
(*this->BuildFileStream) << cmVS10EscapeXML(antBuildPath)
<< "</AntBuildPath>\n";
}
if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) {
this->WriteString("<SkipAntStep>true</SkipAntStep>\n", 3);
}
if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) {
this->WriteString("<EnableProGuard>true</EnableProGuard>\n", 3);
}
if (const char* proGuardConfigLocation =
this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) {
this->WriteString("<ProGuardConfigLocation>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(proGuardConfigLocation)
<< "</ProGuardConfigLocation>\n";
}
if (const char* securePropertiesLocation =
this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) {
this->WriteString("<SecurePropertiesLocation>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(securePropertiesLocation)
<< "</SecurePropertiesLocation>\n";
}
if (const char* nativeLibDirectoriesExpression =
this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(nativeLibDirectoriesExpression);
std::string nativeLibDirs =
cge->Evaluate(this->LocalGenerator, configName);
this->WriteString("<NativeLibDirectories>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(nativeLibDirs)
<< "</NativeLibDirectories>\n";
}
if (const char* nativeLibDependenciesExpression =
this->GeneratorTarget->GetProperty(
"ANDROID_NATIVE_LIB_DEPENDENCIES")) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(nativeLibDependenciesExpression);
std::string nativeLibDeps =
cge->Evaluate(this->LocalGenerator, configName);
this->WriteString("<NativeLibDependencies>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(nativeLibDeps)
<< "</NativeLibDependencies>\n";
}
if (const char* javaSourceDir =
this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) {
this->WriteString("<JavaSourceDir>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(javaSourceDir)
<< "</JavaSourceDir>\n";
}
if (const char* jarDirectoriesExpression =
this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
cmGeneratorExpression ge;
std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(jarDirectoriesExpression);
std::string jarDirectories =
cge->Evaluate(this->LocalGenerator, configName);
this->WriteString("<JarDirectories>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(jarDirectories)
<< "</JarDirectories>\n";
}
if (const char* jarDeps =
this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) {
this->WriteString("<JarDependencies>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(jarDeps)
<< "</JarDependencies>\n";
}
if (const char* assetsDirectories =
this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) {
this->WriteString("<AssetsDirectories>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(assetsDirectories)
<< "</AssetsDirectories>\n";
}
{
std::string manifest_xml = rootDir + "/AndroidManifest.xml";
this->ConvertToWindowsSlash(manifest_xml);
this->WriteString("<AndroidManifestLocation>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(manifest_xml)
<< "</AndroidManifestLocation>\n";
}
if (const char* antAdditionalOptions =
this->GeneratorTarget->GetProperty("ANDROID_ANT_ADDITIONAL_OPTIONS")) {
this->WriteString("<AdditionalOptions>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(antAdditionalOptions)
<< " %(AdditionalOptions)</AdditionalOptions>\n";
}
this->WriteString("</AntBuild>\n", 2);
}
bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
{
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeLinkOptions(*i)) {
return false;
}
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
std::string const& config)
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
auto pOptions =
cm::make_unique<Options>(this->LocalGenerator, Options::Linker,
gg->GetLinkFlagTable(), nullptr, this);
Options& linkOptions = *pOptions;
cmGeneratorTarget::LinkClosure const* linkClosure =
this->GeneratorTarget->GetLinkClosure(config);
const std::string& linkLanguage = linkClosure->LinkerLanguage;
if (linkLanguage.empty()) {
cmSystemTools::Error(
"CMake can not determine linker language for target: ",
this->Name.c_str());
return false;
}
std::string CONFIG = cmSystemTools::UpperCase(config);
const char* linkType = "SHARED";
if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
linkType = "MODULE";
}
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
linkType = "EXE";
}
std::string flags;
std::string linkFlagVarBase = "CMAKE_";
linkFlagVarBase += linkType;
linkFlagVarBase += "_LINKER_FLAGS";
flags += " ";
flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
linkFlagVarBase);
std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG;
flags += " ";
flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
linkFlagVar);
const char* targetLinkFlags =
this->GeneratorTarget->GetProperty("LINK_FLAGS");
if (targetLinkFlags) {
flags += " ";
flags += targetLinkFlags;
}
std::string flagsProp = "LINK_FLAGS_";
flagsProp += CONFIG;
if (const char* flagsConfig =
this->GeneratorTarget->GetProperty(flagsProp)) {
flags += " ";
flags += flagsConfig;
}
cmComputeLinkInformation* pcli =
this->GeneratorTarget->GetLinkInformation(config);
if (!pcli) {
cmSystemTools::Error(
"CMake can not compute cmComputeLinkInformation for target: ",
this->Name.c_str());
return false;
}
cmComputeLinkInformation& cli = *pcli;
std::vector<std::string> libVec;
std::vector<std::string> vsTargetVec;
this->AddLibraries(cli, libVec, vsTargetVec);
if (std::find(linkClosure->Languages.begin(), linkClosure->Languages.end(),
"CUDA") != linkClosure->Languages.end()) {
switch (this->CudaOptions[config]->GetCudaRuntime()) {
case cmVisualStudioGeneratorOptions::CudaRuntimeStatic:
libVec.push_back("cudart_static.lib");
break;
case cmVisualStudioGeneratorOptions::CudaRuntimeShared:
libVec.push_back("cudart.lib");
break;
case cmVisualStudioGeneratorOptions::CudaRuntimeNone:
break;
}
}
std::string standardLibsVar = "CMAKE_";
standardLibsVar += linkLanguage;
standardLibsVar += "_STANDARD_LIBRARIES";
std::string const libs = this->Makefile->GetSafeDefinition(standardLibsVar);
cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
linkOptions.AddFlag("AdditionalDependencies", libVec);
// Populate TargetsFileAndConfigsVec
for (std::vector<std::string>::iterator ti = vsTargetVec.begin();
ti != vsTargetVec.end(); ++ti) {
this->AddTargetsFileAndConfigPair(*ti, config);
}
std::vector<std::string> const& ldirs = cli.GetDirectories();
std::vector<std::string> linkDirs;
for (std::vector<std::string>::const_iterator d = ldirs.begin();
d != ldirs.end(); ++d) {
// first just full path
linkDirs.push_back(*d);
// next path with configuration type Debug, Release, etc
linkDirs.push_back(*d + "/$(Configuration)");
}
linkDirs.push_back("%(AdditionalLibraryDirectories)");
linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
std::string targetName;
std::string targetNameSO;
std::string targetNameFull;
std::string targetNameImport;
std::string targetNamePDB;
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
this->GeneratorTarget->GetExecutableNames(
targetName, targetNameFull, targetNameImport, targetNamePDB, config);
} else {
this->GeneratorTarget->GetLibraryNames(targetName, targetNameSO,
targetNameFull, targetNameImport,
targetNamePDB, config);
}
if (this->MSTools) {
if (this->GeneratorTarget->GetPropertyAsBool("WIN32_EXECUTABLE")) {
if (this->GlobalGenerator->TargetsWindowsCE()) {
linkOptions.AddFlag("SubSystem", "WindowsCE");
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
if (this->ClOptions[config]->UsingUnicode()) {
linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
} else {
linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
}
}
} else {
linkOptions.AddFlag("SubSystem", "Windows");
}
} else {
if (this->GlobalGenerator->TargetsWindowsCE()) {
linkOptions.AddFlag("SubSystem", "WindowsCE");
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
if (this->ClOptions[config]->UsingUnicode()) {
linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
} else {
linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
}
}
} else {
linkOptions.AddFlag("SubSystem", "Console");
};
}
if (const char* stackVal = this->Makefile->GetDefinition(
"CMAKE_" + linkLanguage + "_STACK_SIZE")) {
linkOptions.AddFlag("StackReserveSize", stackVal);
}
linkOptions.AddFlag("GenerateDebugInformation", "false");
std::string pdb = this->GeneratorTarget->GetPDBDirectory(config);
pdb += "/";
pdb += targetNamePDB;
std::string imLib = this->GeneratorTarget->GetDirectory(
config, cmStateEnums::ImportLibraryArtifact);
imLib += "/";
imLib += targetNameImport;
linkOptions.AddFlag("ImportLibrary", imLib.c_str());
linkOptions.AddFlag("ProgramDataBaseFile", pdb.c_str());
// A Windows Runtime component uses internal .NET metadata,
// so does not have an import library.
if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
linkOptions.AddFlag("GenerateWindowsMetadata", "true");
} else if (this->GlobalGenerator->TargetsWindowsPhone() ||
this->GlobalGenerator->TargetsWindowsStore()) {
// WindowsPhone and WindowsStore components are in an app container
// and produce WindowsMetadata. If we are not producing a WINRT
// component, then do not generate the metadata here.
linkOptions.AddFlag("GenerateWindowsMetadata", "false");
}
if (this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0") {
// WindowsPhone 8.0 does not have ole32.
linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
}
} else if (this->NsightTegra) {
linkOptions.AddFlag("SoName", targetNameSO.c_str());
}
linkOptions.Parse(flags.c_str());
linkOptions.FixManifestUACFlags();
if (this->MSTools) {
cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
this->GeneratorTarget->GetModuleDefinitionInfo(config);
if (mdi && !mdi->DefFile.empty()) {
linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile.c_str());
}
linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
"%(IgnoreSpecificDefaultLibraries)");
}
// VS 2015 without all updates has a v140 toolset whose
// GenerateDebugInformation expects No/Debug instead of false/true.
if (gg->GetPlatformToolsetNeedsDebugEnum()) {
if (const char* debug = linkOptions.GetFlag("GenerateDebugInformation")) {
if (strcmp(debug, "false") == 0) {
linkOptions.AddFlag("GenerateDebugInformation", "No");
} else if (strcmp(debug, "true") == 0) {
linkOptions.AddFlag("GenerateDebugInformation", "Debug");
}
}
}
this->LinkOptions[config] = pOptions.release();
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
{
if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
if (!this->ComputeLibOptions(*i)) {
return false;
}
}
}
return true;
}
bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
std::string const& config)
{
cmComputeLinkInformation* pcli =
this->GeneratorTarget->GetLinkInformation(config);
if (!pcli) {
cmSystemTools::Error(
"CMake can not compute cmComputeLinkInformation for target: ",
this->Name.c_str());
return false;
}
cmComputeLinkInformation& cli = *pcli;
typedef cmComputeLinkInformation::ItemVector ItemVector;
const ItemVector& libs = cli.GetItems();
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
if (l->IsPath && cmVS10IsTargetsFile(l->Value)) {
std::string path =
this->LocalGenerator->ConvertToRelativePath(currentBinDir, l->Value);
this->ConvertToWindowsSlash(path);
this->AddTargetsFileAndConfigPair(path, config);
}
}
return true;
}
void cmVisualStudio10TargetGenerator::WriteLinkOptions(
std::string const& config)
{
if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
return;
}
if (this->ProjectType == csproj) {
return;
}
Options& linkOptions = *(this->LinkOptions[config]);
this->WriteString("<Link>\n", 2);
linkOptions.PrependInheritedString("AdditionalOptions");
linkOptions.OutputFlagMap(*this->BuildFileStream, " ");
this->WriteString("</Link>\n", 2);
if (!this->GlobalGenerator->NeedLinkLibraryDependencies(
this->GeneratorTarget)) {
this->WriteString("<ProjectReference>\n", 2);
this->WriteString(
"<LinkLibraryDependencies>false</LinkLibraryDependencies>\n", 3);
this->WriteString("</ProjectReference>\n", 2);
}
}
void cmVisualStudio10TargetGenerator::AddLibraries(
cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
std::vector<std::string>& vsTargetVec)
{
typedef cmComputeLinkInformation::ItemVector ItemVector;
ItemVector const& libs = cli.GetItems();
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
if (l->IsPath) {
std::string path =
this->LocalGenerator->ConvertToRelativePath(currentBinDir, l->Value);
this->ConvertToWindowsSlash(path);
if (cmVS10IsTargetsFile(l->Value)) {
vsTargetVec.push_back(path);
} else {
libVec.push_back(path);
}
} else if (!l->Target ||
l->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
libVec.push_back(l->Value);
}
}
}
void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
std::string const& targetsFile, std::string const& config)
{
for (std::vector<TargetsFileAndConfigs>::iterator i =
this->TargetsFileAndConfigsVec.begin();
i != this->TargetsFileAndConfigsVec.end(); ++i) {
if (cmSystemTools::ComparePath(targetsFile, i->File)) {
if (std::find(i->Configs.begin(), i->Configs.end(), config) ==
i->Configs.end()) {
i->Configs.push_back(config);
}
return;
}
}
TargetsFileAndConfigs entry;
entry.File = targetsFile;
entry.Configs.push_back(config);
this->TargetsFileAndConfigsVec.push_back(entry);
}
void cmVisualStudio10TargetGenerator::WriteMidlOptions(
std::string const& /*config*/, std::vector<std::string> const& includes)
{
if (!this->MSTools) {
return;
}
if (this->ProjectType == csproj) {
return;
}
// This processes *any* of the .idl files specified in the project's file
// list (and passed as the item metadata %(Filename) expressing the rule
// input filename) into output files at the per-config *build* dir
// ($(IntDir)) each.
//
// IOW, this MIDL section is intended to provide a fully generic syntax
// content suitable for most cases (read: if you get errors, then it's quite
// probable that the error is on your side of the .idl setup).
//
// Also, note that the marked-as-generated _i.c file in the Visual Studio
// generator case needs to be referred to as $(IntDir)\foo_i.c at the
// project's file list, otherwise the compiler-side processing won't pick it
// up (for non-directory form, it ends up looking in project binary dir
// only). Perhaps there's something to be done to make this more automatic
// on the CMake side?
this->WriteString("<Midl>\n", 2);
this->WriteString("<AdditionalIncludeDirectories>", 3);
for (std::vector<std::string>::const_iterator i = includes.begin();
i != includes.end(); ++i) {
*this->BuildFileStream << cmVS10EscapeXML(*i) << ";";
}
this->WriteString("%(AdditionalIncludeDirectories)"
"</AdditionalIncludeDirectories>\n",
0);
this->WriteString("<OutputDirectory>$(ProjectDir)/$(IntDir)"
"</OutputDirectory>\n",
3);
this->WriteString("<HeaderFileName>%(Filename).h</HeaderFileName>\n", 3);
this->WriteString("<TypeLibraryName>%(Filename).tlb</TypeLibraryName>\n", 3);
this->WriteString("<InterfaceIdentifierFileName>"
"%(Filename)_i.c</InterfaceIdentifierFileName>\n",
3);
this->WriteString("<ProxyFileName>%(Filename)_p.c</ProxyFileName>\n", 3);
this->WriteString("</Midl>\n", 2);
}
void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
{
if (this->ProjectType == csproj) {
return;
}
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
std::vector<std::string> includes;
this->LocalGenerator->GetIncludeDirectories(
includes, this->GeneratorTarget, "C", *i);
for (std::vector<std::string>::iterator ii = includes.begin();
ii != includes.end(); ++ii) {
this->ConvertToWindowsSlash(*ii);
}
this->WritePlatformConfigTag("ItemDefinitionGroup", *i, 1);
*this->BuildFileStream << "\n";
// output cl compile flags <ClCompile></ClCompile>
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
this->WriteClOptions(*i, includes);
// output rc compile flags <ResourceCompile></ResourceCompile>
this->WriteRCOptions(*i, includes);
this->WriteCudaOptions(*i, includes);
this->WriteMasmOptions(*i, includes);
this->WriteNasmOptions(*i, includes);
}
// output midl flags <Midl></Midl>
this->WriteMidlOptions(*i, includes);
// write events
if (this->ProjectType != csproj) {
this->WriteEvents(*i);
}
// output link flags <Link></Link>
this->WriteLinkOptions(*i);
this->WriteCudaLinkOptions(*i);
// output lib flags <Lib></Lib>
this->WriteLibOptions(*i);
// output manifest flags <Manifest></Manifest>
this->WriteManifestOptions(*i);
if (this->NsightTegra &&
this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
this->WriteAntBuildOptions(*i);
}
this->WriteString("</ItemDefinitionGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteEvents(
std::string const& configName)
{
bool addedPrelink = false;
cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
this->GeneratorTarget->GetModuleDefinitionInfo(configName);
if (mdi && mdi->DefFileGenerated) {
addedPrelink = true;
std::vector<cmCustomCommand> commands =
this->GeneratorTarget->GetPreLinkCommands();
this->GlobalGenerator->AddSymbolExportCommand(this->GeneratorTarget,
commands, configName);
this->WriteEvent("PreLinkEvent", commands, configName);
}
if (!addedPrelink) {
this->WriteEvent("PreLinkEvent",
this->GeneratorTarget->GetPreLinkCommands(), configName);
}
this->WriteEvent("PreBuildEvent",
this->GeneratorTarget->GetPreBuildCommands(), configName);
this->WriteEvent("PostBuildEvent",
this->GeneratorTarget->GetPostBuildCommands(), configName);
}
void cmVisualStudio10TargetGenerator::WriteEvent(
const char* name, std::vector<cmCustomCommand> const& commands,
std::string const& configName)
{
if (commands.empty()) {
return;
}
this->WriteString("<", 2);
(*this->BuildFileStream) << name << ">\n";
cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
std::string script;
const char* pre = "";
std::string comment;
for (std::vector<cmCustomCommand>::const_iterator i = commands.begin();
i != commands.end(); ++i) {
cmCustomCommandGenerator ccg(*i, configName, this->LocalGenerator);
if (!ccg.HasOnlyEmptyCommandLines()) {
comment += pre;
comment += lg->ConstructComment(ccg);
script += pre;
pre = "\n";
script += cmVS10EscapeXML(lg->ConstructScript(ccg));
}
}
comment = cmVS10EscapeComment(comment);
if (this->ProjectType != csproj) {
this->WriteString("<Message>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
this->WriteString("<Command>", 3);
} else {
std::string strippedComment = comment;
strippedComment.erase(
std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
strippedComment.end());
if (!comment.empty() && !strippedComment.empty()) {
(*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment) << "\n";
}
}
(*this->BuildFileStream) << script;
if (this->ProjectType != csproj) {
(*this->BuildFileStream) << "</Command>";
}
(*this->BuildFileStream) << "\n";
this->WriteString("</", 2);
(*this->BuildFileStream) << name << ">\n";
}
void cmVisualStudio10TargetGenerator::WriteProjectReferences()
{
cmGlobalGenerator::TargetDependSet const& unordered =
this->GlobalGenerator->GetTargetDirectDepends(this->GeneratorTarget);
typedef cmGlobalVisualStudioGenerator::OrderedTargetDependSet
OrderedTargetDependSet;
OrderedTargetDependSet depends(unordered, CMAKE_CHECK_BUILD_SYSTEM_TARGET);
this->WriteString("<ItemGroup>\n", 1);
for (OrderedTargetDependSet::const_iterator i = depends.begin();
i != depends.end(); ++i) {
cmGeneratorTarget const* dt = *i;
if (dt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
// skip fortran targets as they can not be processed by MSBuild
// the only reference will be in the .sln file
if (static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator)
->TargetIsFortranOnly(dt)) {
continue;
}
this->WriteString("<ProjectReference Include=\"", 2);
cmLocalGenerator* lg = dt->GetLocalGenerator();
std::string name = dt->GetName();
std::string path;
const char* p = dt->GetProperty("EXTERNAL_MSPROJECT");
if (p) {
path = p;
} else {
path = lg->GetCurrentBinaryDirectory();
path += "/";
path += dt->GetName();
path += computeProjectFileExtension(dt);
}
this->ConvertToWindowsSlash(path);
(*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n";
this->WriteString("<Project>", 3);
(*this->BuildFileStream) << "{" << this->GlobalGenerator->GetGUID(name)
<< "}";
(*this->BuildFileStream) << "</Project>\n";
this->WriteString("<Name>", 3);
(*this->BuildFileStream) << name << "</Name>\n";
this->WriteDotNetReferenceCustomTags(name);
if (csproj == this->ProjectType) {
if (!static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator)
->TargetCanBeReferenced(dt)) {
this->WriteString(
"<ReferenceOutputAssembly>false</ReferenceOutputAssembly>\n", 3);
}
}
this->WriteString("</ProjectReference>\n", 2);
}
this->WriteString("</ItemGroup>\n", 1);
}
void cmVisualStudio10TargetGenerator::WritePlatformExtensions()
{
// This only applies to Windows 10 apps
if (this->GlobalGenerator->TargetsWindowsStore() &&
cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
const char* desktopExtensionsVersion =
this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
if (desktopExtensionsVersion) {
this->WriteSinglePlatformExtension("WindowsDesktop",
desktopExtensionsVersion);
}
const char* mobileExtensionsVersion =
this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
if (mobileExtensionsVersion) {
this->WriteSinglePlatformExtension("WindowsMobile",
mobileExtensionsVersion);
}
}
}
void cmVisualStudio10TargetGenerator::WriteSinglePlatformExtension(
std::string const& extension, std::string const& version)
{
this->WriteString("<Import Project=", 2);
(*this->BuildFileStream)
<< "\"$([Microsoft.Build.Utilities.ToolLocationHelper]"
<< "::GetPlatformExtensionSDKLocation(`" << extension
<< ", Version=" << version
<< "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
<< "$(ExtensionSDKDirectoryRoot), null))"
<< "\\DesignTime\\CommonConfiguration\\Neutral\\" << extension
<< ".props\" "
<< "Condition=\"exists('$("
<< "[Microsoft.Build.Utilities.ToolLocationHelper]"
<< "::GetPlatformExtensionSDKLocation(`" << extension
<< ", Version=" << version
<< "`, $(TargetPlatformIdentifier), $(TargetPlatformVersion), null, "
<< "$(ExtensionSDKDirectoryRoot), null))"
<< "\\DesignTime\\CommonConfiguration\\Neutral\\" << extension
<< ".props')\" />\n";
}
void cmVisualStudio10TargetGenerator::WriteSDKReferences()
{
std::vector<std::string> sdkReferences;
bool hasWrittenItemGroup = false;
if (const char* vsSDKReferences =
this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) {
cmSystemTools::ExpandListArgument(vsSDKReferences, sdkReferences);
this->WriteString("<ItemGroup>\n", 1);
hasWrittenItemGroup = true;
for (std::vector<std::string>::iterator ri = sdkReferences.begin();
ri != sdkReferences.end(); ++ri) {
this->WriteString("<SDKReference Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(*ri) << "\"/>\n";
}
}
// This only applies to Windows 10 apps
if (this->GlobalGenerator->TargetsWindowsStore() &&
cmHasLiteralPrefix(this->GlobalGenerator->GetSystemVersion(), "10.0")) {
const char* desktopExtensionsVersion =
this->GeneratorTarget->GetProperty("VS_DESKTOP_EXTENSIONS_VERSION");
const char* mobileExtensionsVersion =
this->GeneratorTarget->GetProperty("VS_MOBILE_EXTENSIONS_VERSION");
const char* iotExtensionsVersion =
this->GeneratorTarget->GetProperty("VS_IOT_EXTENSIONS_VERSION");
if (desktopExtensionsVersion || mobileExtensionsVersion ||
iotExtensionsVersion) {
if (!hasWrittenItemGroup) {
this->WriteString("<ItemGroup>\n", 1);
hasWrittenItemGroup = true;
}
if (desktopExtensionsVersion) {
this->WriteSingleSDKReference("WindowsDesktop",
desktopExtensionsVersion);
}
if (mobileExtensionsVersion) {
this->WriteSingleSDKReference("WindowsMobile",
mobileExtensionsVersion);
}
if (iotExtensionsVersion) {
this->WriteSingleSDKReference("WindowsIoT", iotExtensionsVersion);
}
}
}
if (hasWrittenItemGroup) {
this->WriteString("</ItemGroup>\n", 1);
}
}
void cmVisualStudio10TargetGenerator::WriteSingleSDKReference(
std::string const& extension, std::string const& version)
{
this->WriteString("<SDKReference Include=\"", 2);
(*this->BuildFileStream) << extension << ", Version=" << version
<< "\" />\n";
}
void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile()
{
if ((this->GlobalGenerator->TargetsWindowsStore() ||
this->GlobalGenerator->TargetsWindowsPhone()) &&
(cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
std::string pfxFile;
std::vector<cmSourceFile const*> certificates;
this->GeneratorTarget->GetCertificates(certificates, "");
for (std::vector<cmSourceFile const*>::const_iterator si =
certificates.begin();
si != certificates.end(); ++si) {
pfxFile = this->ConvertPath((*si)->GetFullPath(), false);
this->ConvertToWindowsSlash(pfxFile);
break;
}
if (this->IsMissingFiles &&
!(this->GlobalGenerator->TargetsWindowsPhone() &&
this->GlobalGenerator->GetSystemVersion() == "8.0")) {
// Move the manifest to a project directory to avoid clashes
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
this->WriteString("<PropertyGroup>\n", 1);
this->WriteString("<AppxPackageArtifactsDir>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(artifactDir)
<< "\\</AppxPackageArtifactsDir>\n";
this->WriteString("<ProjectPriFullPath>", 2);
std::string resourcePriFile =
this->DefaultArtifactDir + "/resources.pri";
this->ConvertToWindowsSlash(resourcePriFile);
(*this->BuildFileStream) << resourcePriFile << "</ProjectPriFullPath>\n";
// If we are missing files and we don't have a certificate and
// aren't targeting WP8.0, add a default certificate
if (pfxFile.empty()) {
std::string templateFolder =
cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
pfxFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
cmSystemTools::CopyAFile(templateFolder + "/Windows_TemporaryKey.pfx",
pfxFile, false);
this->ConvertToWindowsSlash(pfxFile);
this->AddedFiles.push_back(pfxFile);
}
this->WriteString("<", 2);
(*this->BuildFileStream) << "PackageCertificateKeyFile>" << pfxFile
<< "</PackageCertificateKeyFile>\n";
std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
if (!thumb.empty()) {
this->WriteString("<PackageCertificateThumbprint>", 2);
(*this->BuildFileStream) << thumb
<< "</PackageCertificateThumbprint>\n";
}
this->WriteString("</PropertyGroup>\n", 1);
} else if (!pfxFile.empty()) {
this->WriteString("<PropertyGroup>\n", 1);
this->WriteString("<", 2);
(*this->BuildFileStream) << "PackageCertificateKeyFile>" << pfxFile
<< "</PackageCertificateKeyFile>\n";
std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile);
if (!thumb.empty()) {
this->WriteString("<PackageCertificateThumbprint>", 2);
(*this->BuildFileStream) << thumb
<< "</PackageCertificateThumbprint>\n";
}
this->WriteString("</PropertyGroup>\n", 1);
}
}
}
bool cmVisualStudio10TargetGenerator::IsResxHeader(
const std::string& headerFile)
{
std::set<std::string> expectedResxHeaders;
this->GeneratorTarget->GetExpectedResxHeaders(expectedResxHeaders, "");
std::set<std::string>::const_iterator it =
expectedResxHeaders.find(headerFile);
return it != expectedResxHeaders.end();
}
bool cmVisualStudio10TargetGenerator::IsXamlHeader(
const std::string& headerFile)
{
std::set<std::string> expectedXamlHeaders;
this->GeneratorTarget->GetExpectedXamlHeaders(expectedXamlHeaders, "");
std::set<std::string>::const_iterator it =
expectedXamlHeaders.find(headerFile);
return it != expectedXamlHeaders.end();
}
bool cmVisualStudio10TargetGenerator::IsXamlSource(
const std::string& sourceFile)
{
std::set<std::string> expectedXamlSources;
this->GeneratorTarget->GetExpectedXamlSources(expectedXamlSources, "");
std::set<std::string>::const_iterator it =
expectedXamlSources.find(sourceFile);
return it != expectedXamlSources.end();
}
void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
bool isAppContainer = false;
bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
std::string const& v = this->GlobalGenerator->GetSystemVersion();
if (isWindowsPhone || isWindowsStore) {
this->WriteString("<ApplicationType>", 2);
(*this->BuildFileStream)
<< (isWindowsPhone ? "Windows Phone" : "Windows Store")
<< "</ApplicationType>\n";
this->WriteString("<DefaultLanguage>en-US"
"</DefaultLanguage>\n",
2);
if (cmHasLiteralPrefix(v, "10.0")) {
this->WriteString("<ApplicationTypeRevision>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML("10.0")
<< "</ApplicationTypeRevision>\n";
// Visual Studio 14.0 is necessary for building 10.0 apps
this->WriteString("<MinimumVisualStudioVersion>14.0"
"</MinimumVisualStudioVersion>\n",
2);
if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
isAppContainer = true;
}
} else if (v == "8.1") {
this->WriteString("<ApplicationTypeRevision>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(v)
<< "</ApplicationTypeRevision>\n";
// Visual Studio 12.0 is necessary for building 8.1 apps
this->WriteString("<MinimumVisualStudioVersion>12.0"
"</MinimumVisualStudioVersion>\n",
2);
if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
isAppContainer = true;
}
} else if (v == "8.0") {
this->WriteString("<ApplicationTypeRevision>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(v)
<< "</ApplicationTypeRevision>\n";
// Visual Studio 11.0 is necessary for building 8.0 apps
this->WriteString("<MinimumVisualStudioVersion>11.0"
"</MinimumVisualStudioVersion>\n",
2);
if (isWindowsStore &&
this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
isAppContainer = true;
} else if (isWindowsPhone &&
this->GeneratorTarget->GetType() ==
cmStateEnums::EXECUTABLE) {
this->WriteString("<XapOutputs>true</XapOutputs>\n", 2);
this->WriteString("<XapFilename>", 2);
(*this->BuildFileStream)
<< cmVS10EscapeXML(this->Name)
<< "_$(Configuration)_$(Platform).xap</XapFilename>\n";
}
}
}
if (isAppContainer) {
this->WriteString("<AppContainerApplication>true"
"</AppContainerApplication>\n",
2);
} else if (this->Platform == "ARM64") {
this->WriteString("<WindowsSDKDesktopARM64Support>true"
"</WindowsSDKDesktopARM64Support>\n",
2);
} else if (this->Platform == "ARM") {
this->WriteString("<WindowsSDKDesktopARMSupport>true"
"</WindowsSDKDesktopARMSupport>\n",
2);
}
std::string const& targetPlatformVersion =
gg->GetWindowsTargetPlatformVersion();
if (!targetPlatformVersion.empty()) {
this->WriteString("<WindowsTargetPlatformVersion>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformVersion)
<< "</WindowsTargetPlatformVersion>\n";
}
const char* targetPlatformMinVersion = this->GeneratorTarget->GetProperty(
"VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION");
if (targetPlatformMinVersion) {
this->WriteString("<WindowsTargetPlatformMinVersion>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformMinVersion)
<< "</WindowsTargetPlatformMinVersion>\n";
} else if (isWindowsStore && cmHasLiteralPrefix(v, "10.0")) {
// If the min version is not set, then use the TargetPlatformVersion
if (!targetPlatformVersion.empty()) {
this->WriteString("<WindowsTargetPlatformMinVersion>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformVersion)
<< "</WindowsTargetPlatformMinVersion>\n";
}
}
// Added IoT Startup Task support
if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) {
this->WriteString("<ContainsStartupTask>true</ContainsStartupTask>\n", 2);
}
}
void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
{
// For Windows and Windows Phone executables, we will assume that if a
// manifest is not present that we need to add all the necessary files
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
std::vector<cmSourceFile const*> manifestSources;
this->GeneratorTarget->GetAppManifest(manifestSources, "");
{
std::string const& v = this->GlobalGenerator->GetSystemVersion();
if (this->GlobalGenerator->TargetsWindowsPhone()) {
if (v == "8.0") {
// Look through the sources for WMAppManifest.xml
std::vector<cmSourceFile const*> extraSources;
this->GeneratorTarget->GetExtraSources(extraSources, "");
bool foundManifest = false;
for (std::vector<cmSourceFile const*>::const_iterator si =
extraSources.begin();
si != extraSources.end(); ++si) {
// Need to do a lowercase comparison on the filename
if ("wmappmanifest.xml" ==
cmSystemTools::LowerCase((*si)->GetLocation().GetName())) {
foundManifest = true;
break;
}
}
if (!foundManifest) {
this->IsMissingFiles = true;
}
} else if (v == "8.1") {
if (manifestSources.empty()) {
this->IsMissingFiles = true;
}
}
} else if (this->GlobalGenerator->TargetsWindowsStore()) {
if (manifestSources.empty()) {
if (v == "8.0") {
this->IsMissingFiles = true;
} else if (v == "8.1" || cmHasLiteralPrefix(v, "10.0")) {
this->IsMissingFiles = true;
}
}
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteMissingFiles()
{
std::string const& v = this->GlobalGenerator->GetSystemVersion();
if (this->GlobalGenerator->TargetsWindowsPhone()) {
if (v == "8.0") {
this->WriteMissingFilesWP80();
} else if (v == "8.1") {
this->WriteMissingFilesWP81();
}
} else if (this->GlobalGenerator->TargetsWindowsStore()) {
if (v == "8.0") {
this->WriteMissingFilesWS80();
} else if (v == "8.1") {
this->WriteMissingFilesWS81();
} else if (cmHasLiteralPrefix(v, "10.0")) {
this->WriteMissingFilesWS10_0();
}
}
}
void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80()
{
std::string templateFolder =
cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
// For WP80, the manifest needs to be in the same folder as the project
// this can cause an overwrite problem if projects aren't organized in
// folders
std::string manifestFile =
this->LocalGenerator->GetCurrentBinaryDirectory() +
std::string("/WMAppManifest.xml");
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
std::string targetNameXML =
cmVS10EscapeXML(this->GeneratorTarget->GetName());
cmGeneratedFileStream fout(manifestFile.c_str());
fout.SetCopyIfDifferent(true);
/* clang-format off */
fout <<
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Deployment"
" xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
" AppPlatformVersion=\"8.0\">\n"
"\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
"\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
" Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
" Version=\"1.0.0.0\" Genre=\"apps.normal\" Author=\"CMake\""
" Description=\"Default CMake App\" Publisher=\"CMake\""
" PublisherID=\"{" << this->GUID << "}\">\n"
"\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
<< artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
"\t\t<Capabilities/>\n"
"\t\t<Tasks>\n"
"\t\t\t<DefaultTask Name=\"_default\""
" ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
"\t\t</Tasks>\n"
"\t\t<Tokens>\n"
"\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
" TaskName=\"_default\">\n"
"\t\t\t\t<TemplateFlip>\n"
"\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
<< artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
"\t\t\t\t\t<Count>0</Count>\n"
"\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
<< artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
"\t\t\t\t</TemplateFlip>\n"
"\t\t\t</PrimaryToken>\n"
"\t\t</Tokens>\n"
"\t\t<ScreenResolutions>\n"
"\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
"\t\t</ScreenResolutions>\n"
"\t</App>\n"
"</Deployment>\n";
/* clang-format on */
std::string sourceFile = this->ConvertPath(manifestFile, false);
this->ConvertToWindowsSlash(sourceFile);
this->WriteString("<Xml Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n";
this->WriteString("<SubType>Designer</SubType>\n", 3);
this->WriteString("</Xml>\n", 2);
this->AddedFiles.push_back(sourceFile);
std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
false);
this->ConvertToWindowsSlash(smallLogo);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n";
this->AddedFiles.push_back(smallLogo);
std::string logo = this->DefaultArtifactDir + "/Logo.png";
cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
this->ConvertToWindowsSlash(logo);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n";
this->AddedFiles.push_back(logo);
std::string applicationIcon =
this->DefaultArtifactDir + "/ApplicationIcon.png";
cmSystemTools::CopyAFile(templateFolder + "/ApplicationIcon.png",
applicationIcon, false);
this->ConvertToWindowsSlash(applicationIcon);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(applicationIcon) << "\" />\n";
this->AddedFiles.push_back(applicationIcon);
}
void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81()
{
std::string manifestFile =
this->DefaultArtifactDir + "/package.appxManifest";
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
std::string targetNameXML =
cmVS10EscapeXML(this->GeneratorTarget->GetName());
cmGeneratedFileStream fout(manifestFile.c_str());
fout.SetCopyIfDifferent(true);
/* clang-format off */
fout <<
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
" xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
" xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
"\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
" Version=\"1.0.0.0\" />\n"
"\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
"\t<Properties>\n"
"\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
"\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
"\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
"\t</Properties>\n"
"\t<Prerequisites>\n"
"\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
"\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
"\t</Prerequisites>\n"
"\t<Resources>\n"
"\t\t<Resource Language=\"x-generate\" />\n"
"\t</Resources>\n"
"\t<Applications>\n"
"\t\t<Application Id=\"App\""
" Executable=\"" << targetNameXML << ".exe\""
" EntryPoint=\"" << targetNameXML << ".App\">\n"
"\t\t\t<m2:VisualElements\n"
"\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
"\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
"\t\t\t\tBackgroundColor=\"#336699\"\n"
"\t\t\t\tForegroundText=\"light\"\n"
"\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
"\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
"\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
"\t\t\t\t\t<m2:ShowNameOnTiles>\n"
"\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
"\t\t\t\t\t</m2:ShowNameOnTiles>\n"
"\t\t\t\t</m2:DefaultTile>\n"
"\t\t\t\t<m2:SplashScreen"
" Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
"\t\t\t</m2:VisualElements>\n"
"\t\t</Application>\n"
"\t</Applications>\n"
"</Package>\n";
/* clang-format on */
this->WriteCommonMissingFiles(manifestFile);
}
void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80()
{
std::string manifestFile =
this->DefaultArtifactDir + "/package.appxManifest";
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
std::string targetNameXML =
cmVS10EscapeXML(this->GeneratorTarget->GetName());
cmGeneratedFileStream fout(manifestFile.c_str());
fout.SetCopyIfDifferent(true);
/* clang-format off */
fout <<
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
"\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
" Version=\"1.0.0.0\" />\n"
"\t<Properties>\n"
"\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
"\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
"\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
"\t</Properties>\n"
"\t<Prerequisites>\n"
"\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
"\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
"\t</Prerequisites>\n"
"\t<Resources>\n"
"\t\t<Resource Language=\"x-generate\" />\n"
"\t</Resources>\n"
"\t<Applications>\n"
"\t\t<Application Id=\"App\""
" Executable=\"" << targetNameXML << ".exe\""
" EntryPoint=\"" << targetNameXML << ".App\">\n"
"\t\t\t<VisualElements"
" DisplayName=\"" << targetNameXML << "\""
" Description=\"" << targetNameXML << "\""
" BackgroundColor=\"#336699\" ForegroundText=\"light\""
" Logo=\"" << artifactDirXML << "\\Logo.png\""
" SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
"\t\t\t\t<DefaultTile ShowName=\"allLogos\""
" ShortName=\"" << targetNameXML << "\" />\n"
"\t\t\t\t<SplashScreen"
" Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
"\t\t\t</VisualElements>\n"
"\t\t</Application>\n"
"\t</Applications>\n"
"</Package>\n";
/* clang-format on */
this->WriteCommonMissingFiles(manifestFile);
}
void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81()
{
std::string manifestFile =
this->DefaultArtifactDir + "/package.appxManifest";
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
std::string targetNameXML =
cmVS10EscapeXML(this->GeneratorTarget->GetName());
cmGeneratedFileStream fout(manifestFile.c_str());
fout.SetCopyIfDifferent(true);
/* clang-format off */
fout <<
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
" xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
"\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
" Version=\"1.0.0.0\" />\n"
"\t<Properties>\n"
"\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
"\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
"\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
"\t</Properties>\n"
"\t<Prerequisites>\n"
"\t\t<OSMinVersion>6.3</OSMinVersion>\n"
"\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
"\t</Prerequisites>\n"
"\t<Resources>\n"
"\t\t<Resource Language=\"x-generate\" />\n"
"\t</Resources>\n"
"\t<Applications>\n"
"\t\t<Application Id=\"App\""
" Executable=\"" << targetNameXML << ".exe\""
" EntryPoint=\"" << targetNameXML << ".App\">\n"
"\t\t\t<m2:VisualElements\n"
"\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
"\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
"\t\t\t\tBackgroundColor=\"#336699\"\n"
"\t\t\t\tForegroundText=\"light\"\n"
"\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
"\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
"\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
"\t\t\t\t\t<m2:ShowNameOnTiles>\n"
"\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
"\t\t\t\t\t</m2:ShowNameOnTiles>\n"
"\t\t\t\t</m2:DefaultTile>\n"
"\t\t\t\t<m2:SplashScreen"
" Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
"\t\t\t</m2:VisualElements>\n"
"\t\t</Application>\n"
"\t</Applications>\n"
"</Package>\n";
/* clang-format on */
this->WriteCommonMissingFiles(manifestFile);
}
void cmVisualStudio10TargetGenerator::WriteMissingFilesWS10_0()
{
std::string manifestFile =
this->DefaultArtifactDir + "/package.appxManifest";
std::string artifactDir =
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
this->ConvertToWindowsSlash(artifactDir);
std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
std::string targetNameXML =
cmVS10EscapeXML(this->GeneratorTarget->GetName());
cmGeneratedFileStream fout(manifestFile.c_str());
fout.SetCopyIfDifferent(true);
/* clang-format off */
fout <<
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Package\n\t"
"xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\""
"\txmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"\n"
"\txmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\""
"\n\tIgnorableNamespaces=\"uap mp\">\n\n"
"\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
" Version=\"1.0.0.0\" />\n"
"\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID <<
"\" PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
"\t<Properties>\n"
"\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
"\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
"\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
"\t</Properties>\n"
"\t<Dependencies>\n"
"\t\t<TargetDeviceFamily Name=\"Windows.Universal\" "
"MinVersion=\"10.0.0.0\" MaxVersionTested=\"10.0.0.0\" />\n"
"\t</Dependencies>\n"
"\t<Resources>\n"
"\t\t<Resource Language=\"x-generate\" />\n"
"\t</Resources>\n"
"\t<Applications>\n"
"\t\t<Application Id=\"App\""
" Executable=\"" << targetNameXML << ".exe\""
" EntryPoint=\"" << targetNameXML << ".App\">\n"
"\t\t\t<uap:VisualElements\n"
"\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
"\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
"\t\t\t\tBackgroundColor=\"#336699\"\n"
"\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
"\t\t\t\tSquare44x44Logo=\"" << artifactDirXML <<
"\\SmallLogo44x44.png\">\n"
"\t\t\t\t<uap:SplashScreen"
" Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
"\t\t\t</uap:VisualElements>\n"
"\t\t</Application>\n"
"\t</Applications>\n"
"</Package>\n";
/* clang-format on */
this->WriteCommonMissingFiles(manifestFile);
}
void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles(
const std::string& manifestFile)
{
std::string templateFolder =
cmSystemTools::GetCMakeRoot() + "/Templates/Windows";
std::string sourceFile = this->ConvertPath(manifestFile, false);
this->ConvertToWindowsSlash(sourceFile);
this->WriteString("<AppxManifest Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n";
this->WriteString("<SubType>Designer</SubType>\n", 3);
this->WriteString("</AppxManifest>\n", 2);
this->AddedFiles.push_back(sourceFile);
std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png", smallLogo,
false);
this->ConvertToWindowsSlash(smallLogo);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n";
this->AddedFiles.push_back(smallLogo);
std::string smallLogo44 = this->DefaultArtifactDir + "/SmallLogo44x44.png";
cmSystemTools::CopyAFile(templateFolder + "/SmallLogo44x44.png", smallLogo44,
false);
this->ConvertToWindowsSlash(smallLogo44);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(smallLogo44) << "\" />\n";
this->AddedFiles.push_back(smallLogo44);
std::string logo = this->DefaultArtifactDir + "/Logo.png";
cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false);
this->ConvertToWindowsSlash(logo);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n";
this->AddedFiles.push_back(logo);
std::string storeLogo = this->DefaultArtifactDir + "/StoreLogo.png";
cmSystemTools::CopyAFile(templateFolder + "/StoreLogo.png", storeLogo,
false);
this->ConvertToWindowsSlash(storeLogo);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(storeLogo) << "\" />\n";
this->AddedFiles.push_back(storeLogo);
std::string splashScreen = this->DefaultArtifactDir + "/SplashScreen.png";
cmSystemTools::CopyAFile(templateFolder + "/SplashScreen.png", splashScreen,
false);
this->ConvertToWindowsSlash(splashScreen);
this->WriteString("<Image Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(splashScreen) << "\" />\n";
this->AddedFiles.push_back(splashScreen);
// This file has already been added to the build so don't copy it
std::string keyFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
this->ConvertToWindowsSlash(keyFile);
this->WriteString("<None Include=\"", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(keyFile) << "\" />\n";
}
bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
{
HANDLE h =
CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(source).c_str(),
FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, 0);
if (!h) {
return false;
}
FILETIME const ftime_20010101 = { 3365781504u, 29389701u };
if (!SetFileTime(h, &ftime_20010101, &ftime_20010101, &ftime_20010101)) {
CloseHandle(h);
return false;
}
CloseHandle(h);
return true;
}
void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
cmSourceFile const* sf, std::map<std::string, std::string>& tags)
{
if (this->ProjectType == csproj) {
const cmPropertyMap& props = sf->GetProperties();
for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
++p) {
static const std::string propNamePrefix = "VS_CSHARP_";
if (p->first.find(propNamePrefix) == 0) {
std::string tagName = p->first.substr(propNamePrefix.length());
if (!tagName.empty()) {
const std::string val = props.GetPropertyValue(p->first);
if (!val.empty()) {
tags[tagName] = val;
} else {
tags.erase(tagName);
}
}
}
}
}
}
void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
const std::map<std::string, std::string>& tags)
{
if (!tags.empty()) {
for (std::map<std::string, std::string>::const_iterator i = tags.begin();
i != tags.end(); ++i) {
this->WriteString("<", 3);
(*this->BuildFileStream) << i->first << ">" << cmVS10EscapeXML(i->second)
<< "</" << i->first << ">\n";
}
}
}
void cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
cmSourceFile const* sf, std::string& link)
{
std::string f = sf->GetFullPath();
if (!this->InSourceBuild) {
const std::string stripFromPath =
this->Makefile->GetCurrentSourceDirectory();
if (f.find(stripFromPath) != std::string::npos) {
link = f.substr(stripFromPath.length() + 1);
if (const char* l = sf->GetProperty("VS_CSHARP_Link")) {
link = l;
}
this->ConvertToWindowsSlash(link);
}
}
}
std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
const char* relativeFilePath) const
{
// Always search in the standard modules location.
std::string path = cmSystemTools::GetCMakeRoot() + "/";
path += relativeFilePath;
this->ConvertToWindowsSlash(path);
return path;
}
| [
"dna2gle@gmail.com"
] | dna2gle@gmail.com |
5cd27b4260b8d369bb267cb8628417dd8884f3e3 | 6ec7728f8eb7f50317f00835a8e46876b5f5d38b | /P04/bonus/main.cpp | c0a09e041c77358e7939e629f595ecb056159aed | [] | no_license | cole111197/CSE1325 | 2c6fe73443e8b1ffe1993f3d8dbf82761eec5b0f | a84971e9b2a891ca9e8ad03216a94e840d179a10 | refs/heads/master | 2022-03-21T05:05:01.407667 | 2019-12-03T09:19:20 | 2019-12-03T09:19:20 | 204,408,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,966 | cpp | #include "coach.h"
#include "locomotive.h"
#include "stock.h"
#include "train.h"
#include <iostream>
#include <iomanip>
void printSpeed(double speed);
int main(){
Train train;
int command;
std::string prompt = "Command?";
while(command != 0){
std::cout << "==================\n====CS Express====\n==================\n\n";
std::cout << train;
std::cout << "#########################################################################\n";
std::cout << "Minutes | 1 | 5 | 15 | 30 | 60 |\n";
std::cout << "----------|----------|----------|----------|----------|----------|\n";
std::cout << " m/s |";
printSpeed(train.speed(1));
printSpeed(train.speed(5));
printSpeed(train.speed(15));
printSpeed(train.speed(30));
printSpeed(train.speed(60));
std::cout << "\n km/h |";
printSpeed(3.6*train.speed(1));
printSpeed(3.6*train.speed(5));
printSpeed(3.6*train.speed(15));
printSpeed(3.6*train.speed(30));
printSpeed(3.6*train.speed(60));
std::cout << "\n mp/h |";
printSpeed(2.237*train.speed(1));
printSpeed(2.237*train.speed(5));
printSpeed(2.237*train.speed(15));
printSpeed(2.237*train.speed(30));
printSpeed(2.237*train.speed(60));
std::cout << "\n\n1 - Add a standard locomotive 11 - Add a custom locomotive\n2 - Add an empty coach 12 - Add a custom coach\n9 - Clear the train\n0 - Exit\n\n" << prompt << "\n";
prompt = "Command?";
std::cin >> command;
if(command == 1){
Locomotive* temp = new Locomotive();
train += *temp;
} else if(command == 2){
Coach* temp = new Coach();
train += *temp;
} else if(command == 9){
train = Train();
} else if(command == 11){
bool valid = false;
int weight;
int power;
while(!valid){
std::cout << "Enter weight (default 80000 kg): ";
std::cin >> weight;
if(weight < 0 || std::cin.fail()){
std::cout << "Please enter a valid weight\n";
std::cin.clear();
std::cin.ignore(256, '\n');
} else {
while(!valid){
std::cout << "Enter power (default 13500 kW): ";
std::cin >> power;
if(power < 0 || std::cin.fail()){
std::cout << "Please enter a valid power\n";
std::cin.clear();
std::cin.ignore(256, '\n');
} else {
Locomotive* temp = new Locomotive(weight, power);
train += *temp;
valid = true;
}
}
}
}
} else if(command == 12){
bool valid = false;
int weight;
int passengers;
while(!valid){
std::cout << "Enter weight (default 28000 kg): ";
std::cin >> weight;
if(weight < 0 || std::cin.fail()){
std::cout << "Please enter a valid weight\n";
std::cin.clear();
std::cin.ignore(256, '\n');
} else {
while(!valid){
std::cout << "Enter number of passengers (0-120): ";
std::cin >> passengers;
if(passengers < 0 || std::cin.fail()){
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "Please enter a valid number of passengers\n";
} else {
Coach* temp = new Coach(weight);
try{
(*temp).add_passengers(passengers);
train += *temp;
valid = true;
}
catch(std::runtime_error e){
std::cerr << e.what() << std::endl;
}
}
}
}
}
} else if(std::cin.fail()){
command = -1;
prompt = "Please enter an integer";
std::cin.clear();
std::cin.ignore(256, '\n');
} else if(command == 0){
std::cout << "Exiting" << std::endl;
} else {
prompt = "Please enter a valid command";
}
}
}
void printSpeed(double speed){
std::cout << std::left << std::setw(10) << std::setfill(' ') << std::to_string(speed);
std::cout << "|";
} | [
"cole.montgomery@mavs.uta.edu"
] | cole.montgomery@mavs.uta.edu |
cfe5881a0ac8e5d0f4cbd910f9aaa139471df673 | 583e614741a633a427e80e68db1a62698d3607d1 | /CISP 360/Chapter 9/pointer arrays.cpp | 73c9ebb8cabcf189fdac191d985ef9e891a6425b | [] | no_license | Justin-Singh125125/CISP-360 | c7f9e06fd25bbe1d28d211da2c9f8695bc26a9f5 | 754de232a958d7b5a699374a3965e49fa69a1abe | refs/heads/master | 2020-04-08T14:34:02.294634 | 2018-11-28T04:17:26 | 2018-11-28T04:17:26 | 159,442,525 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | cpp | #include <iostream>
using namespace std;
int main()
{
const int SIZE = 5;
int *pointer[SIZE];
int array[SIZE] = {1,2,3,4,5};
int count;
for (count = 0; count < SIZE; count ++)
{
pointer[count] = &array[count];
}
*pointer[2] = 7;
for (count = 0; count < SIZE; count ++)
{
cout << *pointer[count] << endl;
}
return 0;
}
| [
"justin.singh125125@gmail.com"
] | justin.singh125125@gmail.com |
70e57b5664b84464bd896209b010d92fa0ee0826 | 6848723448cc22474863f6506f30bdbac2b6293e | /tools/mosesdecoder-master/util/mmap.cc | cdf92c73183014e7afdab5483710cd22d1d1efe1 | [
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | Pangeamt/nectm | 74b3052ba51f227cd508b89d3c565feccc0d2f4f | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | refs/heads/master | 2022-04-09T11:21:56.646469 | 2020-03-30T07:37:41 | 2020-03-30T07:37:41 | 250,306,101 | 1 | 0 | Apache-2.0 | 2020-03-26T16:05:11 | 2020-03-26T16:05:10 | null | UTF-8 | C++ | false | false | 13,085 | cc | /* Memory mapping wrappers.
* ARM and MinGW ports contributed by Hideo Okuma and Tomoyuki Yoshimura at
* NICT.
*/
#include "util/mmap.hh"
#include "util/exception.hh"
#include "util/file.hh"
#include "util/parallel_read.hh"
#include "util/scoped.hh"
#include <iostream>
#include <cassert>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#include <io.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
namespace util {
std::size_t SizePage() {
#if defined(_WIN32) || defined(_WIN64)
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwAllocationGranularity;
#else
return sysconf(_SC_PAGE_SIZE);
#endif
}
scoped_mmap::~scoped_mmap() {
if (data_ != (void*)-1) {
try {
// Thanks Denis Filimonov for pointing out NFS likes msync first.
SyncOrThrow(data_, size_);
UnmapOrThrow(data_, size_);
} catch (const util::ErrnoException &e) {
std::cerr << e.what();
abort();
}
}
}
namespace {
template <class T> T RoundUpPow2(T value, T mult) {
return ((value - 1) & ~(mult - 1)) + mult;
}
} // namespace
scoped_memory::scoped_memory(std::size_t size, bool zeroed) : data_(NULL), size_(0), source_(NONE_ALLOCATED) {
HugeMalloc(size, zeroed, *this);
}
void scoped_memory::reset(void *data, std::size_t size, Alloc source) {
switch(source_) {
case MMAP_ROUND_UP_ALLOCATED:
scoped_mmap(data_, RoundUpPow2(size_, (std::size_t)SizePage()));
break;
case MMAP_ALLOCATED:
scoped_mmap(data_, size_);
break;
case MALLOC_ALLOCATED:
free(data_);
break;
case NONE_ALLOCATED:
break;
}
data_ = data;
size_ = size;
source_ = source;
}
/*void scoped_memory::call_realloc(std::size_t size) {
assert(source_ == MALLOC_ALLOCATED || source_ == NONE_ALLOCATED);
void *new_data = realloc(data_, size);
if (!new_data) {
reset();
} else {
data_ = new_data;
size_ = size;
source_ = MALLOC_ALLOCATED;
}
}*/
const int kFileFlags =
#if defined(_WIN32) || defined(_WIN64)
0 // MapOrThrow ignores flags on windows
#elif defined(MAP_FILE)
MAP_FILE | MAP_SHARED
#else
MAP_SHARED
#endif
;
void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset) {
#ifdef MAP_POPULATE // Linux specific
if (prefault) {
flags |= MAP_POPULATE;
}
#endif
#if defined(_WIN32) || defined(_WIN64)
int protectC = for_write ? PAGE_READWRITE : PAGE_READONLY;
int protectM = for_write ? FILE_MAP_WRITE : FILE_MAP_READ;
uint64_t total_size = size + offset;
HANDLE hMapping = CreateFileMapping((HANDLE)_get_osfhandle(fd), NULL, protectC, total_size >> 32, static_cast<DWORD>(total_size), NULL);
UTIL_THROW_IF(!hMapping, ErrnoException, "CreateFileMapping failed");
LPVOID ret = MapViewOfFile(hMapping, protectM, offset >> 32, offset, size);
CloseHandle(hMapping);
UTIL_THROW_IF(!ret, ErrnoException, "MapViewOfFile failed");
#else
int protect = for_write ? (PROT_READ | PROT_WRITE) : PROT_READ;
void *ret;
UTIL_THROW_IF((ret = mmap(NULL, size, protect, flags, fd, offset)) == MAP_FAILED, ErrnoException, "mmap failed for size " << size << " at offset " << offset);
# ifdef MADV_HUGEPAGE
/* We like huge pages but it's fine if we can't have them. Note that huge
* pages are not supported for file-backed mmap on linux.
*/
madvise(ret, size, MADV_HUGEPAGE);
# endif
#endif
return ret;
}
void SyncOrThrow(void *start, size_t length) {
#if defined(_WIN32) || defined(_WIN64)
UTIL_THROW_IF(!::FlushViewOfFile(start, length), ErrnoException, "Failed to sync mmap");
#else
UTIL_THROW_IF(length && msync(start, length, MS_SYNC), ErrnoException, "Failed to sync mmap");
#endif
}
void UnmapOrThrow(void *start, size_t length) {
#if defined(_WIN32) || defined(_WIN64)
UTIL_THROW_IF(!::UnmapViewOfFile(start), ErrnoException, "Failed to unmap a file");
#else
UTIL_THROW_IF(munmap(start, length), ErrnoException, "munmap failed");
#endif
}
// Linux huge pages.
#ifdef __linux__
namespace {
bool AnonymousMap(std::size_t size, int flags, bool populate, util::scoped_memory &to) {
if (populate) flags |= MAP_POPULATE;
void *ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | flags, -1, 0);
if (ret == MAP_FAILED) return false;
to.reset(ret, size, scoped_memory::MMAP_ALLOCATED);
return true;
}
bool TryHuge(std::size_t size, uint8_t alignment_bits, bool populate, util::scoped_memory &to) {
// Don't bother with these cases.
if (size < (1ULL << alignment_bits) || (1ULL << alignment_bits) < SizePage())
return false;
// First try: Linux >= 3.8 with manually configured hugetlb pages available.
#ifdef MAP_HUGE_SHIFT
if (AnonymousMap(size, MAP_HUGETLB | (alignment_bits << MAP_HUGE_SHIFT), populate, to))
return true;
#endif
// Second try: manually configured hugetlb pages exist, but kernel too old to
// pick size or not available. This might pick the wrong size huge pages,
// but the sysadmin must have made them available in the first place.
#ifdef MAP_HUGETLB
if (AnonymousMap(size, MAP_HUGETLB, populate, to))
return true;
#endif
// Third try: align to a multiple of the huge page size by overallocating.
// I feel bad about doing this, but it's also how posix_memalign is
// implemented. And the memory is virtual.
// Round up requested size to multiple of page size. This will allow the pages after to be munmapped.
std::size_t size_up = RoundUpPow2(size, SizePage());
std::size_t ask = size_up + (1 << alignment_bits) - SizePage();
// Don't populate because this is asking for more than we will use.
scoped_mmap larger(mmap(NULL, ask, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0), ask);
if (larger.get() == MAP_FAILED) return false;
// Throw out pages before the alignment point.
uintptr_t base = reinterpret_cast<uintptr_t>(larger.get());
// Round up to next multiple of alignment.
uintptr_t rounded_up = RoundUpPow2(base, static_cast<uintptr_t>(1) << alignment_bits);
if (base != rounded_up) {
// If this throws an exception (which it shouldn't) then we want to unmap the whole thing by keeping it in larger.
UnmapOrThrow(larger.get(), rounded_up - base);
larger.steal();
larger.reset(reinterpret_cast<void*>(rounded_up), ask - (rounded_up - base));
}
// Throw out pages after the requested size.
assert(larger.size() >= size_up);
if (larger.size() > size_up) {
// This is where we assume size_up is a multiple of page size.
UnmapOrThrow(static_cast<uint8_t*>(larger.get()) + size_up, larger.size() - size_up);
larger.reset(larger.steal(), size_up);
}
#ifdef MADV_HUGEPAGE
madvise(larger.get(), size_up, MADV_HUGEPAGE);
#endif
to.reset(larger.steal(), size, scoped_memory::MMAP_ROUND_UP_ALLOCATED);
return true;
}
} // namespace
#endif
void HugeMalloc(std::size_t size, bool zeroed, scoped_memory &to) {
to.reset();
#ifdef __linux__
// TODO: architectures/page sizes other than 2^21 and 2^30.
// Attempt 1 GB pages.
// If the user asked for zeroed memory, assume they want it populated.
if (size >= (1ULL << 30) && TryHuge(size, 30, zeroed, to))
return;
// Attempt 2 MB pages.
if (size >= (1ULL << 21) && TryHuge(size, 21, zeroed, to))
return;
#endif // __linux__
// Non-linux will always do this, as will small allocations on Linux.
to.reset(zeroed ? calloc(1, size) : malloc(size), size, scoped_memory::MALLOC_ALLOCATED);
UTIL_THROW_IF(!to.get(), ErrnoException, "Failed to allocate " << size << " bytes");
}
#ifdef __linux__
const std::size_t kTransitionHuge = std::max<std::size_t>(1ULL << 21, SizePage());
#endif // __linux__
void HugeRealloc(std::size_t to, bool zero_new, scoped_memory &mem) {
if (!to) {
mem.reset();
return;
}
std::size_t from_size = mem.size();
switch (mem.source()) {
case scoped_memory::NONE_ALLOCATED:
HugeMalloc(to, zero_new, mem);
return;
#ifdef __linux__
case scoped_memory::MMAP_ROUND_UP_ALLOCATED:
// for mremap's benefit.
from_size = RoundUpPow2(from_size, SizePage());
case scoped_memory::MMAP_ALLOCATED:
// Downsizing below barrier?
if (to <= SizePage()) {
scoped_malloc replacement(malloc(to));
memcpy(replacement.get(), mem.get(), std::min(to, mem.size()));
if (zero_new && to > mem.size())
memset(static_cast<uint8_t*>(replacement.get()) + mem.size(), 0, to - mem.size());
mem.reset(replacement.release(), to, scoped_memory::MALLOC_ALLOCATED);
} else {
void *new_addr = mremap(mem.get(), from_size, to, MREMAP_MAYMOVE);
UTIL_THROW_IF(!new_addr, ErrnoException, "Failed to mremap from " << from_size << " to " << to);
mem.steal();
mem.reset(new_addr, to, scoped_memory::MMAP_ALLOCATED);
}
return;
#endif // __linux__
case scoped_memory::MALLOC_ALLOCATED:
#ifdef __linux__
// Transition larger allocations to huge pages, but don't keep trying if we're still malloc allocated.
if (to >= kTransitionHuge && mem.size() < kTransitionHuge) {
scoped_memory replacement;
HugeMalloc(to, zero_new, replacement);
memcpy(replacement.get(), mem.get(), mem.size());
// This can't throw.
mem.reset(replacement.get(), replacement.size(), replacement.source());
replacement.steal();
return;
}
#endif // __linux__
{
void *new_addr = std::realloc(mem.get(), to);
UTIL_THROW_IF(!new_addr, ErrnoException, "realloc to " << to << " bytes failed.");
if (zero_new && to > mem.size())
memset(static_cast<uint8_t*>(new_addr) + mem.size(), 0, to - mem.size());
mem.steal();
mem.reset(new_addr, to, scoped_memory::MALLOC_ALLOCATED);
}
return;
default:
UTIL_THROW(Exception, "HugeRealloc called with type " << mem.source());
}
}
void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out) {
switch (method) {
case LAZY:
out.reset(MapOrThrow(size, false, kFileFlags, false, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
break;
case POPULATE_OR_LAZY:
#ifdef MAP_POPULATE
case POPULATE_OR_READ:
#endif
out.reset(MapOrThrow(size, false, kFileFlags, true, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
break;
#ifndef MAP_POPULATE
case POPULATE_OR_READ:
#endif
case READ:
HugeMalloc(size, false, out);
SeekOrThrow(fd, offset);
ReadOrThrow(fd, out.get(), size);
break;
case PARALLEL_READ:
HugeMalloc(size, false, out);
ParallelRead(fd, out.get(), size, offset);
break;
}
}
void *MapZeroedWrite(int fd, std::size_t size) {
ResizeOrThrow(fd, 0);
ResizeOrThrow(fd, size);
return MapOrThrow(size, true, kFileFlags, false, fd, 0);
}
void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file) {
file.reset(CreateOrThrow(name));
try {
return MapZeroedWrite(file.get(), size);
} catch (ErrnoException &e) {
e << " in file " << name;
throw;
}
}
Rolling::Rolling(const Rolling ©_from, uint64_t increase) {
*this = copy_from;
IncreaseBase(increase);
}
Rolling &Rolling::operator=(const Rolling ©_from) {
fd_ = copy_from.fd_;
file_begin_ = copy_from.file_begin_;
file_end_ = copy_from.file_end_;
for_write_ = copy_from.for_write_;
block_ = copy_from.block_;
read_bound_ = copy_from.read_bound_;
current_begin_ = 0;
if (copy_from.IsPassthrough()) {
current_end_ = copy_from.current_end_;
ptr_ = copy_from.ptr_;
} else {
// Force call on next mmap.
current_end_ = 0;
ptr_ = NULL;
}
return *this;
}
Rolling::Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount) {
current_begin_ = 0;
current_end_ = 0;
fd_ = fd;
file_begin_ = offset;
file_end_ = offset + amount;
for_write_ = for_write;
block_ = block;
read_bound_ = read_bound;
}
void *Rolling::ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size) {
out.reset();
if (IsPassthrough()) return static_cast<uint8_t*>(get()) + index;
uint64_t offset = index + file_begin_;
// Round down to multiple of page size.
uint64_t cruft = offset % static_cast<uint64_t>(SizePage());
std::size_t map_size = static_cast<std::size_t>(size + cruft);
out.reset(MapOrThrow(map_size, for_write_, kFileFlags, true, fd_, offset - cruft), map_size, scoped_memory::MMAP_ALLOCATED);
return static_cast<uint8_t*>(out.get()) + static_cast<std::size_t>(cruft);
}
void Rolling::Roll(uint64_t index) {
assert(!IsPassthrough());
std::size_t amount;
if (file_end_ - (index + file_begin_) > static_cast<uint64_t>(block_)) {
amount = block_;
current_end_ = index + amount - read_bound_;
} else {
amount = file_end_ - (index + file_begin_);
current_end_ = index + amount;
}
ptr_ = static_cast<uint8_t*>(ExtractNonRolling(mem_, index, amount)) - index;
current_begin_ = index;
}
} // namespace util
| [
"alexander.raginsky@gmail.com"
] | alexander.raginsky@gmail.com |
cb91f7a56a1970daa9d242daa5ac71a980eb36d9 | 5d8068348be2eb408758f9aa44b9c882f283b4ee | /Firebird 1.07 VS - eventColliders/Firebird/EntityMngr.cpp | d8b21921e6d46a5a823c902efff7576f64cbce27 | [] | no_license | Losapioj/Firebird | 6dacd7689871b605c775a96f73719f6753627138 | a4ab06f3b4b7f765de3db1696ba1616370d8f40e | refs/heads/master | 2020-04-08T12:22:17.039002 | 2015-02-01T18:49:58 | 2015-02-01T18:49:58 | 30,155,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,455 | cpp | #include "Debug.h"
#include "EventMngr.h"
#include "EntityMngr.h"
/////////////////////////////////////////////////
cEntityMngr::cEntityMngr()
: LoadEntity("ENTITY_LOAD_EVENT"),
MoveEntity("ENTITY_POSITION_EVENT"),
OrientEntity("ENTITY_ROTATE_EVENT"),
ScaleEntity("ENTITY_SCALE_EVENT"),
AttachModel("ENTITY_ATTACH_MODEL_EVENT"),
AttachHeightmap("ENTITY_ATTACH_HEIGHTMAP_EVENT"),
AttachCollider("ENTITY_ATTACH_COLLIDABLE_EVENT"),
LoadCollidable("ENTITY_LOAD_COLLIDABLE_EVENT")
{
g_eventMngr.RegisterListener(LoadEntity, this);
g_eventMngr.RegisterListener(MoveEntity, this);
g_eventMngr.RegisterListener(OrientEntity, this);
g_eventMngr.RegisterListener(ScaleEntity, this);
g_eventMngr.RegisterListener(AttachModel, this);
g_eventMngr.RegisterListener(AttachHeightmap, this);
g_eventMngr.RegisterListener(LoadCollidable, this);
}
/////////////////////////////////////////////////
cEntityMngr::~cEntityMngr()
{
#ifdef MY_DEBUG
debug << "~cEntityMngr start" << endl;
#endif
// Delete all entity objects
while(!m_entities.empty())
{
EntityIter it = m_entities.begin();
delete it->second;
it->second = NULL;
m_entities.erase (it);
}
#ifdef MY_DEBUG
debug << "~cEntityMngr end" << endl;
#endif
}
/////////////////////////////////////////////////
void cEntityMngr::HandleEvent(cEvent* e)
{
//debug << "Begin cEntityMngr::HandleEvent("
// << e->GetEventID().GetStr() << ")\n";
EntityID id;
id.SetID(e->GetParam(0).m_asPointer);
EventID eid = e->GetEventID();
if(eid == LoadEntity)
CreateEntity(id, e->GetParam(1).m_asString);
else if(eid == MoveEntity)
{
sVector3d pos(e->GetParam(1).m_asFloat,
e->GetParam(2).m_asFloat,
e->GetParam(3).m_asFloat);
#ifdef MY_DEBUG
debug << "pos = " << pos.m_x << ", "
<< pos.m_y << ", "
<< pos.m_z << endl;
#endif
SetEntityPosition(id, pos);
}
else if(eid== OrientEntity)
{
sVector3d rot( DegToRad(e->GetParam(1).m_asFloat),
DegToRad(e->GetParam(2).m_asFloat),
DegToRad(e->GetParam(3).m_asFloat) );
SetEntityRotation(id, rot);
}
else if(eid == ScaleEntity)
{
sVector3d scl(e->GetParam(1).m_asFloat,
e->GetParam(2).m_asFloat,
e->GetParam(3).m_asFloat);
SetEntityScale(id, scl);
}
else if(eid == AttachModel)
{
GraphicID model;
model.SetID(e->GetParam(1).m_asPointer);
SetEntityModel(id, model);
}
else if(eid == AttachHeightmap)
{
#ifdef MY_DEBUG
debug << "Attach Heightmap event caught" << endl;
#endif
const char* filename = (const char*)e->GetParam(1).m_asPointer;
SetEntityHeightmap(id, filename);
}
else if(eid == LoadCollidable)
{
#ifdef MY_DEBUG
debug << "cEntityMngr: Attaching colider Call" << endl;
#endif
SetEntityCollider(id, e->GetParam(1).m_asString,
*(sVector3d*)(e->GetParam(2).m_asPointer),
*(sVector3d*)(e->GetParam(3).m_asPointer));
}
//debug << "End cEntityMngr::HandleEvent()\n";
}
/////////////////////////////////////////////////
bool cEntityMngr::CreateEntity(const EntityID& id, const char* type)
{
//debug << "Begin cEntityMngr::CreateEntity ("
// << id.GetStr() << ", " << type << ")"
// << endl;
EntityIter it = m_entities.find(id);
if (it != m_entities.end())
return false;
if(strcmp(type, "Terrain") == 0)
{
cTerrainEntity* temp = new cTerrainEntity(id);
m_entities[id] = temp;
}
else if (strcmp(type, "Avatar") == 0)
{
cAvatarEntity* temp = new cAvatarEntity(id);
m_entities[id] = temp;
//m_moveList[id] = temp;
}
else if (strcmp(type, "Actor") == 0)
{
cActorEntity* temp = new cActorEntity(id);
m_entities[id] = temp;
//m_moveList[id] = temp;
//m_drawList[id] = temp;
}
else
ErrorMsg("Unknown entity type");
//debug << "End cEntityMngr::CreateEntity ()"
// << endl;
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityPosition(const EntityID& id, const sVector3d& pos)
{
//debug << "Begin cEntityMngr::SetEntityPosition ("
// << id.GetStr() << " => " << pos.m_x << ", "
// << pos.m_y << ", " << pos.m_z << ")" << endl;
EntityIter it = m_entities.find(id);
if (it == m_entities.end())
return false;
m_entities[id]->SetPosition(pos);
//debug << "End cEntityMngr::SetEntityPosition ()" << endl;
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityRotation(const EntityID& id, const sVector3d& rot)
{
//debug << "Begin cEntityMngr::SetEntityRotation ("
// << id.GetStr() << " => " << rot.m_x << ", "
// << rot.m_y << ", " << rot.m_z << ")" << endl;
EntityIter it = m_entities.find(id);
if (it == m_entities.end())
return false;
m_entities[id]->SetRotation(rot);
//debug << "End cEntityMngr::SetEntityRotation ()" << endl;
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityScale(const EntityID& id, const sVector3d& scl)
{
//debug << "Begin cEntityMngr::SetEntityScale("
// << id.GetStr() << " => " << scl.m_x << ", "
// << scl.m_y << ", " << scl.m_z << ")" << endl;
EntityIter it = m_entities.find(id);
if (it == m_entities.end())
return false;
m_entities[id]->SetScale(scl);
//debug << "End cEntityMngr::SetEntityScale()" << endl;
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityModel(const EntityID& id, const GraphicID& model)
{
//debug << "Begin cEntityMngr::SetEntityModel("
// << id.GetStr() << ", " << model.GetStr() << ")" << endl;
EntityIter it = m_entities.find(id);
if(it == m_entities.end())
return false;
iRenderable* entity =
dynamic_cast<iRenderable*>(it->second);
entity->SetModel(model);
//debug << "End cEntityMngr::SetEntityModel()" << endl;
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityHeightmap(const EntityID& id,
const char* filename)
{
#ifdef MY_DEBUG
debug << "cEntityMngr::SetEntityHeightmap started" << endl;
#endif
EntityIter it = m_entities.find(id);
if (it == m_entities.end())
{
ErrorMsg("HM setting, entity not found");
return false;
}
cTerrainEntity* entity = dynamic_cast<cTerrainEntity*>(m_entities[id]);
entity->ReadCustomHMFile(filename);
ifstream fin(filename);
fin.close();
return true;
}
/////////////////////////////////////////////////
bool cEntityMngr::SetEntityCollider(const EntityID& id,
const char* colType,
sVector3d& dataStart,
sVector3d& dataEnd)
{
string s = colType;
//debug << "cEntityMngr::SetEntityCollider colType = " << colType << endl;
EntityIter it = m_entities.find(id);
if (it == m_entities.end())
{
ErrorMsg("Collider setting, entity not found");
return false;
}
dataStart *= m_entities[id]->GetScale();
dataEnd *= m_entities[id]->GetScale();
if (s == "Cylinder")
{
//debug << "Attaching colider to: " << id.GetStr() << endl;
cBoundingCylinder* cyl = new cBoundingCylinder(dataStart.m_x,
dataStart.m_y,
&(m_entities[id]->GetPhysPointer()));
g_eventMngr.PostEvent(new cEvent(AttachCollider, id.GetID(), cyl));
}
else if (s == "AABox")
{
//debug << "Attaching colider to: " << id.GetStr() << endl;
cBoundingBox* box = new cBoundingBox(dataStart,
dataEnd,
&(m_entities[id]->GetPhysPointer()));
g_eventMngr.PostEvent(new cEvent(AttachCollider, id.GetID(), box));
}
else if (s == "Sphere")
{
//debug << "Attaching colider to: " << id.GetStr() << endl;
cBoundingSphere* sphere = new cBoundingSphere(dataStart.m_x,
&(m_entities[id]->GetPhysPointer()));
g_eventMngr.PostEvent(new cEvent(AttachCollider, id.GetID(), sphere));
}
return true;
}
/////////////////////////////////////////////////
void cEntityMngr::UpdateEntities(float dt)
{
//debug << "Begin cEntityMngr::UpdateEntities(" << dt << ")" << endl;
for(EntityIter it = m_entities.begin();
it != m_entities.end(); ++it)
{
iMoveable* entity =
dynamic_cast<iMoveable*>(it->second);
if(entity)
entity->Update(dt);
}
//debug << "End cEntityMngr::UpdateEntities()" << endl;
}
/////////////////////////////////////////////////
void cEntityMngr::DrawEntities()
{
//debug << "Begin cEntityMngr::DrawEntities()" << endl;
for(EntityIter it = m_entities.begin();
it != m_entities.end(); ++it)
{
iRenderable* entity =
dynamic_cast<iRenderable*>(it->second);
if(entity)
entity->Draw();
}
//debug << "End cEntityMngr::DrawEntities()" << endl;
}
| [
"Losapioj@gmail.com"
] | Losapioj@gmail.com |
d89861d1482ed7517f207a08f622287fe485c367 | d49847c5117a26cfe502812932d3ba103c34c0d7 | /Engine/Object Manager/Object.cpp | 067083136b49da09dc4b8644f3df0efb6720a8cd | [] | no_license | hryshko17/BasicGameEngine | c548e9d4e7b103a08d27fd23f30343fb983a27f8 | d9710a8699fad38a6c85ac3b6d0c60f9b86f84c9 | refs/heads/master | 2021-01-20T13:03:19.302636 | 2016-06-08T00:24:16 | 2016-06-08T00:24:16 | 60,655,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,118 | cpp |
#include "Object.h"
#include "../Renderer/RenderMesh.h"
#include "../Utilities/Time.h"
CObject::CObject()
{
m_szTag = "Nameless Object";
m_cpRenderMesh = nullptr;
m_mWorldMatrix.MatrixIdentity();
m_vVelocity.ZeroOut();
}
CObject::CObject(std::string szTag)
{
m_szTag = szTag;
m_cpRenderMesh = nullptr;
m_mWorldMatrix.MatrixIdentity();
m_vVelocity.ZeroOut();
}
CObject::CObject(std::string szTag, CRenderMesh* cpRenderMesh, Matrix4x4 mWorldMatrix, Vector3D vVelocity)
{
m_szTag = szTag;
m_cpRenderMesh = cpRenderMesh;
m_mWorldMatrix = mWorldMatrix;
m_vVelocity = vVelocity;
}
CObject::~CObject()
{
//SAFE_DELETE(m_cpRenderMesh);
}
CObject::CObject(const CObject& cObject)
{
m_szTag = cObject.m_szTag;
m_cpRenderMesh = cObject.m_cpRenderMesh;
m_mWorldMatrix = cObject.m_mWorldMatrix;
}
CObject& CObject::operator=(const CObject& cObject)
{
if (this != &cObject)
{
m_szTag = cObject.m_szTag;
m_cpRenderMesh = cObject.m_cpRenderMesh;
m_mWorldMatrix = cObject.m_mWorldMatrix;
}
return *this;
}
bool CObject::UpdatePosition()
{
CTime* cpTime = CTime::GetInstance();
//update the world matix
Matrix4x4 mOldWorld = m_mWorldMatrix;
XMMATRIX mTranslate = XMMatrixTranslation(m_vVelocity.x * cpTime->DeltaTime(), m_vVelocity.y * cpTime->DeltaTime(), m_vVelocity.z * cpTime->DeltaTime());
XMStoreFloat4x4(&CMathLib::MatrixConvert4x4(m_mWorldMatrix), XMMatrixMultiply(mTranslate, XMLoadFloat4x4(&CMathLib::MatrixConvert4x4(m_mWorldMatrix))));
//update the rendermesh
if (m_cpRenderMesh != nullptr)
m_cpRenderMesh->SetWorldMatrix(m_mWorldMatrix);
//update velocity
Vector3D vVelocity = GetWorldVelocity();
return true;
}
Vector3D CObject::GetWorldVelocity()
{
Matrix4x4 mOldWorld = m_mWorldMatrix;
Matrix4x4 mNewWorld; mNewWorld.MatrixIdentity();
//get local velocity as world velocity
XMMATRIX mTranslate = XMMatrixTranslation(m_vVelocity.x, m_vVelocity.y, m_vVelocity.z);
XMStoreFloat4x4(&CMathLib::MatrixConvert4x4(mNewWorld),
XMMatrixMultiply(mTranslate, XMLoadFloat4x4(&CMathLib::MatrixConvert4x4(m_mWorldMatrix))));
//update velocity
Vector3D vVelocity;
vVelocity.Set(mNewWorld.e41 - mOldWorld.e41, mNewWorld.e42 - mOldWorld.e42, mNewWorld.e43 - mOldWorld.e43, 0.0f);
return vVelocity;
}
void CObject::SetWorldVelocity(Vector3D vVelocity)
{
XMMATRIX mWorld = XMLoadFloat4x4(&CMathLib::MatrixConvert4x4(m_mWorldMatrix));
mWorld.r[0].m128_f32[3] = 0.0f;
mWorld.r[1].m128_f32[3] = 0.0f;
mWorld.r[2].m128_f32[3] = 0.0f;
mWorld.r[3].m128_f32[0] = 0.0f;
mWorld.r[3].m128_f32[1] = 0.0f;
mWorld.r[3].m128_f32[2] = 0.0f;
mWorld = XMMatrixInverse(&XMMatrixDeterminant(mWorld), mWorld);
Matrix4x4 mLocal; mLocal.MatrixIdentity();
XMMATRIX mTranslate = XMMatrixTranslation(vVelocity.x, vVelocity.y, vVelocity.z);
XMStoreFloat4x4(&CMathLib::MatrixConvert4x4(mLocal), XMMatrixMultiply(mTranslate, mWorld));
//update velocity
Vector3D vLocalVelocity;
vLocalVelocity.Set(mLocal.e41, mLocal.e42, mLocal.e43, 0.0f);
m_vVelocity = vLocalVelocity;
}
| [
"hryshko17@users.noreply.github.com"
] | hryshko17@users.noreply.github.com |
66945dadb44728c7ada56f9f4dc0c00abe25aefa | 4016e385eaf332ab5dbe73691211785f6516c15c | /singleProject/TBCRay.h | 32cca223c9617200970704dd7040ae9323bb44aa | [] | no_license | afreakk/TBC | be65ef1742fec4130f373d4d35000442bc9f34f7 | 468c96d88ad5c2c345b62ba28977d88810714904 | refs/heads/master | 2016-08-06T18:26:44.223744 | 2014-06-04T13:28:10 | 2014-06-04T13:28:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,455 | h | #pragma once
#include "OgreSingleton.h"
#include "ManualLine.h"
class BehaviourObject;
class TBCRay : public Ogre::Singleton<TBCRay>
{
private:
Ogre::RaySceneQuery* m_raySceneQuery;//!< Ray query
public:
TBCRay(Ogre::SceneManager* sceneMgr);
bool raycast(const Ogre::Vector3& point, const Ogre::Vector3& normal, const BehaviourObject* gameObjectt);
bool RaycastFromPoint(const Ogre::Vector3& point, const Ogre::Vector3& normal, Ogre::Vector3& result);
private:
static void GetMeshInformation(const Ogre::MeshPtr mesh, size_t &vertex_count, Ogre::Vector3*& vertices, size_t& index_count, unsigned long*& indices, const Ogre::Vector3& position, const Ogre::Quaternion& orient, const Ogre::Vector3& scale);
static void GetMeshInformation(const Ogre::Entity* entity, size_t& vertex_count, Ogre::Vector3*& vertices, size_t& index_count, unsigned long*& indices, const Ogre::Vector3& position, const Ogre::Quaternion& orient, const Ogre::Vector3& scale);
void debugRay(const Ogre::Vector3& point, const Ogre::Vector3& normal);
void debugHit(const Ogre::Vector3& point, const Ogre::Vector3& endPoint);
bool checkVertex(Ogre::RaySceneQueryResultEntry& rayResult, Vector3& closest_result, Ogre::Ray& ray, Ogre::Real& closest_distance);
bool checkVertexLevel(Ogre::Real& closest_distance, Vector3* vertices,unsigned long* indices, size_t vertex_count, size_t index_count, Ogre::Ray& ray);
ManualLine m_hitLine;
ManualLine m_line;
Ogre::Ray ray;
};
| [
"laderud@hotmail.com"
] | laderud@hotmail.com |
791d622676e5a4f8a44f3ec27c14b7858a33f53d | 3f17bef125d4032f65d296ec1f416f69a5b298e1 | /src/cutfacewidget.h | 223a32ffeed1e39075d8110cdcdb2ede4011e28a | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | xphillyx/dust3d | 2a8ef9b0df84dce36b50997926d25a5478ac43ae | 7c43ac49167d50ddc45e6df0f5c3ad87bc6aefb3 | refs/heads/master | 2023-04-01T00:37:37.477528 | 2020-11-29T02:12:09 | 2020-11-29T02:12:09 | 317,751,319 | 0 | 0 | MIT | 2021-04-01T06:56:42 | 2020-12-02T04:40:06 | null | UTF-8 | C++ | false | false | 656 | h | #ifndef DUST3D_CUT_FACE_WIDGET_H
#define DUST3D_CUT_FACE_WIDGET_H
#include <QFrame>
#include <QLabel>
#include <QIcon>
#include "document.h"
#include "modelwidget.h"
class CutFaceWidget : public QFrame
{
Q_OBJECT
public:
CutFaceWidget(const Document *document, QUuid partId);
static int preferredHeight();
ModelWidget *previewWidget();
protected:
void resizeEvent(QResizeEvent *event) override;
public slots:
void reload();
void updatePreview(QUuid partId);
void updateCheckedState(bool checked);
private:
QUuid m_partId;
const Document *m_document = nullptr;
ModelWidget *m_previewWidget = nullptr;
};
#endif
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
ceb2510f33dd02ba5cb2bdb9ef0238e8c347c50d | 3b3c7c6e8eab8e5b9308d5c5a01e239187592736 | /Mesh/MeshTools.cpp | 86e20f46a9f3a8e0843673975f4526a9723212c4 | [] | no_license | xuyinghui8888/FakePic | 5190dabb5f31ede4713f2248de24d61a137baa93 | 773133b98f39766e879c21ac522ccca9e974cd29 | refs/heads/master | 2023-06-25T22:22:56.927266 | 2021-07-30T07:28:41 | 2021-07-30T07:28:41 | 390,925,055 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,370 | cpp | #include "MeshTools.h"
#include "../FileIO/FileIO.h"
#include "../RT/RT.h"
#include "../CalcFunction/CalcHelper.h"
#include "../Mapping/Mapping.h"
using namespace CGP;
intVec MeshTools::getSrcToDstMatch(const MeshCompress& mesh, const intVec& src, const intVec& dst, double match_thres)
{
int n_src = src.size();
int n_dst = dst.size();
intVec map_src_dst(2*n_src, -1);
intVec dst_visited(n_dst, 0);
for (size_t i = 0; i < n_src; i++)
{
int src_id = src[i];
//matching pos is not valid
floatVec match_dis(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
int dst_id = dst[j];
if (dst_visited[dst_id])
{
}
else
{
match_dis[j] = (mesh.pos_[dst_id] - mesh.pos_[src_id]).norm();
}
}
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
int dst_id = dst[match_id];
if (match_dis[match_id] < match_thres)
{
dst_visited[match_id] = 1;
map_src_dst[2 * i] = src_id;
map_src_dst[2 * i + 1] = dst_id;
}
}
return map_src_dst;
}
intVec MeshTools::getSrcToDstMatchKeepSign(const MeshCompress& mesh, const intVec& src, const intVec& dst, double match_thres, bool match_same)
{
int n_src = src.size();
int n_dst = dst.size();
intVec map_src_dst(2 * n_src, -1);
intVec dst_visited(n_dst, 0);
for (size_t i = 0; i < n_src; i++)
{
int src_id = src[i];
//matching pos is not valid
floatVec match_dis(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
int dst_id = dst[j];
if (dst_visited[j])
{
}
else
{
if ((mesh.pos_[src_id] - mesh.pos_[dst_id]).y() > 0)
{
match_dis[j] = (mesh.pos_[dst_id] - mesh.pos_[src_id]).norm();
}
else
{
match_dis[j] = (mesh.pos_[dst_id] - mesh.pos_[src_id]).norm()+10;
}
}
}
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
int dst_id = dst[match_id];
if (match_dis[match_id] < match_thres)
{
if (match_same == false)
{
dst_visited[match_id] = 1;
}
map_src_dst[2 * i] = src_id;
map_src_dst[2 * i + 1] = dst_id;
}
}
return map_src_dst;
}
intVec MeshTools::getSrcToDstMatchKeepSignTopN(const MeshCompress& mesh, const intVec& src, int top_n, const intVec& dst, double match_thres, bool match_same)
{
int n_src = src.size();
int n_dst = dst.size();
intVec map_src_dst;
intVec dst_visited(n_dst, 0);
for (size_t i = 0; i < n_src; i++)
{
int src_id = src[i];
//matching pos is not valid
floatVec match_dis(n_dst, INT_MAX);
for (int j = 0; j < n_dst; j++)
{
int dst_id = dst[j];
if (dst_visited[j])
{
}
else
{
if ((mesh.pos_[src_id] - mesh.pos_[dst_id]).y() > 0)
{
match_dis[j] = (mesh.pos_[dst_id] - mesh.pos_[src_id]).norm();
}
else
{
match_dis[j] = (mesh.pos_[dst_id] - mesh.pos_[src_id]).norm() + 10;
}
}
}
for (int iter_top = 0; iter_top < top_n; iter_top++)
{
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
int dst_id = dst[match_id];
if (match_dis[match_id] < match_thres)
{
if (match_same == false)
{
dst_visited[match_id] = 1;
}
map_src_dst.push_back(src_id);
map_src_dst.push_back(dst_id);
}
match_dis[match_id] = INTMAX_MAX;
}
}
return map_src_dst;
}
intVec MeshTools::getMoveIdx(const MeshCompress& src, const MeshCompress& dst, double thres)
{
floatVec dis(src.pos_.size(), -1);
#pragma omp parallel for
for (int i = 0; i < src.pos_.size(); i++)
{
dis[i] = (src.pos_[i] - dst.pos_[i]).norm();
}
intVec move;
for (int i = 0; i < src.n_vertex_; i++)
{
if (dis[i] > thres)
{
move.push_back(i);
}
}
return move;
}
intVec MeshTools::getFixIdx(const MeshCompress& src, const MeshCompress& dst, double thres)
{
floatVec dis(src.pos_.size(), -1);
#pragma omp parallel for
for (int i = 0; i < src.pos_.size(); i++)
{
dis[i] = (src.pos_[i] - dst.pos_[i]).norm();
}
intVec fix;
for (int i = 0; i < src.n_vertex_; i++)
{
if (dis[i] < thres)
{
fix.push_back(i);
}
}
return fix;
}
void MeshTools::getNormal(const float3Vec& pos, vecD& normal)
{
if (pos.empty())
{
LOG(INFO) << "pos is empty." << std::endl;
return;
}
int n_pos = pos.size();
matD A(n_pos*(n_pos+1)/2 + 1, 3);
A.setConstant(0);
int count = 0;
for (int i = 0; i < n_pos; i++)
{
for (int j = i; j < n_pos; j++)
{
float3E line = pos[i] - pos[j];
for (int iter_dim = 0; iter_dim < 3; iter_dim++)
{
A(count, iter_dim) = line(iter_dim);
}
count++;
}
}
double weight = 1e6;
vecD B(count+1);
B.setConstant(0);
A(count, 2) = weight;
B(count) = weight;
DenseSolver dense_solver;
dense_solver.compute(A);
normal = dense_solver.solve(B);
}
void MeshTools::getBoundingBox(const std::vector<float3Vec>& xyz, doubleVec& xyz_min, doubleVec& xyz_max)
{
if (xyz.empty())
{
LOG(WARNING) << "xyz empty." << std::endl;
xyz_min = doubleVec{ 0.0,0.0,0.0 };
xyz_max = doubleVec{ 0.0,0.0,0.0 };
}
else
{
getBoundingBox(xyz[0], xyz_min, xyz_max);
for (int i = 1; i < xyz.size(); i++)
{
doubleVec xyz_min_iter, xyz_max_iter;
getBoundingBox(xyz[i], xyz_min_iter, xyz_max_iter);
xyz_min = CalcHelper::multiMin(xyz_min, xyz_min_iter);
xyz_max = CalcHelper::multiMax(xyz_max, xyz_max_iter);
}
}
}
void MeshTools::getBoundingBox(const float3Vec& xyz, doubleVec& xyz_min, doubleVec& xyz_max)
{
xyz_min = { 1.0 * INTMAX_MAX, 1.0 * INTMAX_MAX, 1.0 * INTMAX_MAX };
xyz_max = { -1.0 * INTMAX_MAX, -1.0 * INTMAX_MAX, -1.0 * INTMAX_MAX };
#pragma omp parallel for
for (int iter_dim = 0; iter_dim < 3; iter_dim++)
{
for (int iter_idx = 0; iter_idx < xyz.size(); iter_idx++)
{
float3E pos_i = xyz[iter_idx];
xyz_min[iter_dim] = DMIN(xyz_min[iter_dim], pos_i(iter_dim));
xyz_max[iter_dim] = DMAX(xyz_max[iter_dim], pos_i(iter_dim));
}
}
}
intVec MeshTools::getMatchBasedOnUVAndPos(const MeshCompress& src, const MeshCompress& dst,
double pos_thres, double uv_thres)
{
if (src.n_vertex_ < dst.n_vertex_)
{
LOG(ERROR) << "src && dst is switched." << std::endl;
}
if (src.n_uv_ < src.n_vertex_ || dst.n_uv_ < dst.n_vertex_)
{
LOG(ERROR) << "must have uv info." << std::endl;
}
if (src.tri_.size() != src.tri_uv_.size() || dst.tri_.size() != dst.tri_uv_.size())
{
LOG(ERROR) << "triangle is not the same with triangle based uv" << std::endl;
}
//get vertex to uv index
intSetVec src_uv_idx, dst_uv_idx;
src_uv_idx.resize(src.n_vertex_);
dst_uv_idx.resize(dst.n_vertex_);
for (int iter_vertex = 0; iter_vertex < src.n_tri_*3 ; iter_vertex++)
{
int vertex_idx = src.tri_[iter_vertex];
int uv_idx = src.tri_uv_[iter_vertex];
src_uv_idx[vertex_idx].insert(uv_idx);
}
for (int iter_vertex = 0; iter_vertex < dst.n_tri_*3; iter_vertex++)
{
int vertex_idx = dst.tri_[iter_vertex];
int uv_idx = dst.tri_uv_[iter_vertex];
dst_uv_idx[vertex_idx].insert(uv_idx);
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec match_src_dst(n_src, -1);
for (int i = 0; i < n_src; i++)
{
int src_id = i;
//matching pos is not valid
floatVec match_pos(n_dst, INT_MAX);
//save for match_uv minimal
floatVec match_uv(n_dst, INT_MAX);
floatVec match_dis(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
int dst_id = j;
match_pos[j] = (src.pos_[src_id] - dst.pos_[dst_id]).norm();
double min_uv_dis = INT_MAX;
for (int iter_i : src_uv_idx[i])
{
for (int iter_j : dst_uv_idx[j])
{
min_uv_dis = DMIN(min_uv_dis, (src.tex_cor_[iter_i] - dst.tex_cor_[iter_j]).norm());
}
}
match_uv[j] = min_uv_dis;
match_dis[j] = match_uv[j] + match_pos[j];
}
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
match_src_dst[i] = match_id;
if (*res.first > pos_thres * uv_thres)
{
LOG(INFO) << "*res.second: " << *res.first << std::endl;
LOG(ERROR) << "res dis larger than threshold." << std::endl;
}
}
return match_src_dst;
}
void MeshTools::getCenter(const float3Vec& xyz, float3E& center)
{
center = float3E(0, 0, 0);
if (xyz.empty())
{
return;
}
for (int i = 0; i < xyz.size(); i++)
{
center = center + xyz[i];
}
center = center * 1.0 / xyz.size();
}
void MeshTools::getCenter(const float3Vec& xyz, const intVec& roi, float3E& center)
{
center = float3E(0, 0, 0);
if (roi.empty())
{
return;
}
for (int i : roi)
{
center = center + xyz[i];
}
center = center * 1.0 / roi.size();
}
void MeshTools::putSrcToDst(const MeshCompress& src, const intVec& src_idx, const MeshCompress& dst,
const intVec& dst_idx, MeshCompress& res, const float3E& dir)
{
res = src;
float3Vec dst_pos, src_pos;
src.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
float scale = RT::getScale(src_pos, dst_pos);
//LOG(INFO) << "scale: " << scale << std::endl;
RT::scaleInPlace(scale, res.pos_);
//get slice for scaled pos
res.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
float3E translate;
RT::getTranslate(src_pos, dst_pos, translate);
translate = translate.cwiseProduct(dir);
//LOG(INFO) << "translate: " << translate.transpose() << std::endl;
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::putSrcWithScaleTranslate(const MeshCompress& src, const double& scale, const float3E& translate, MeshCompress& res)
{
res = src;
RT::scaleInPlace(scale, res.pos_);
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::putSrcToDst(const MeshCompress& src, const intVec& src_idx, const MeshCompress& dst,
const intVec& dst_idx, MeshCompress& res, double& scale, float3E& translate)
{
res = src;
float3Vec dst_pos, src_pos;
src.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
scale = RT::getScale(src_pos, dst_pos);
//LOG(INFO) << "scale: " << scale << std::endl;
RT::scaleInPlace(scale, res.pos_);
//get slice for scaled pos
res.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
RT::getTranslate(src_pos, dst_pos, translate);
//LOG(INFO) << "translate: " << translate.transpose() << std::endl;
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::putSrcToDst(const MeshCompress& src, const intVec& src_idx, const MeshCompress& dst,
const intVec& dst_idx, const float3E& dir, MeshCompress& res, double& scale, float3E& scale_center, float3E& translate)
{
res = src;
float3Vec dst_pos, src_pos;
src.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
scale = RT::getScale(src_pos, dst_pos);
//LOG(INFO) << "scale: " << scale << std::endl;
RT::scaleInPlace(scale, res.pos_, scale_center);
//get slice for scaled pos
res.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
RT::getTranslate(src_pos, dst_pos, translate);
translate = translate.cwiseProduct(dir);
//LOG(INFO) << "translate: " << translate.transpose() << std::endl;
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::putSrcToDst(const MeshCompress& src, const intVec& src_idx, const MeshCompress& dst,
const intVec& dst_idx, MeshCompress& res, double& scale, float3E& scale_center, float3E& translate)
{
res = src;
float3Vec dst_pos, src_pos;
src.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
scale = RT::getScale(src_pos, dst_pos);
//LOG(INFO) << "scale: " << scale << std::endl;
RT::scaleInPlace(scale, res.pos_, scale_center);
//get slice for scaled pos
res.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
RT::getTranslate(src_pos, dst_pos, translate);
//LOG(INFO) << "translate: " << translate.transpose() << std::endl;
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::putSrcToDstFixScale(const MeshCompress& src, const intVec& src_idx, const MeshCompress& dst,
const intVec& dst_idx, MeshCompress& res, const double& scale)
{
res = src;
float3Vec dst_pos, src_pos;
src.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
//LOG(INFO) << "scale: " << scale << std::endl;
RT::scaleInPlace(scale, res.pos_);
//get slice for scaled pos
res.getSlice(src_idx, src_pos);
dst.getSlice(dst_idx, dst_pos);
float3E translate;
RT::getTranslate(src_pos, dst_pos, translate);
//LOG(INFO) << "translate: " << translate.transpose() << std::endl;
RT::translateInPlace(translate, res.pos_);
}
void MeshTools::getScale3Dim(const float3Vec& src, const float3Vec& dst, const intVec& roi, float3E& scale)
{
float3Vec src_roi, dst_roi;
MeshTools::getSlice(src, roi, src_roi);
MeshTools::getSlice(dst, roi, dst_roi);
RT::getScale3Dim(src_roi, dst_roi, scale);
}
void MeshTools::replaceVertexInPlace(MeshCompress& src, const MeshCompress& dst, const intVec& roi)
{
#pragma omp parallel for
for (int i = 0; i < roi.size(); i++)
{
src.pos_[roi[i]] = dst.pos_[roi[i]];
}
}
intVec MeshTools::getMatchBasedOnPosDstToSrc(const MeshCompress& src, const MeshCompress& dst, double pos_thres,
bool hard_thres)
{
if (src.n_vertex_ < dst.n_vertex_)
{
LOG(ERROR) << "src && dst is switched." << std::endl;
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec match_dst_src(n_dst, -1);
for (int i = 0; i < n_dst; i++)
{
//matching pos is not valid
floatVec match_pos(n_src, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_src; j++)
{
match_pos[j] = (dst.pos_[i] - src.pos_[j]).norm();
}
auto res = std::minmax_element(match_pos.begin(), match_pos.end());
int match_id = res.first - match_pos.begin();
if (!hard_thres)
{
match_dst_src[i] = match_id;
if (*res.first > pos_thres)
{
LOG(INFO) << "*res.second: " << *res.first << std::endl;
LOG(ERROR) << "res dis larger than threshold." << std::endl;
}
}
else
{
if (*res.first < pos_thres)
{
match_dst_src[i] = match_id;
}
}
}
return match_dst_src;
}
intVec MeshTools::getMatchBasedOnPosSrcToDst(const MeshCompress& src, const MeshCompress& dst, double pos_thres,
bool hard_thres)
{
if (src.n_vertex_ > dst.n_vertex_)
{
intVec res = getMatchBasedOnPosDstToSrc(src, dst, pos_thres, hard_thres);
intVec inv_res = MAP::getReverseMapping(res);
return inv_res;
}
else
{
intVec res = getMatchBasedOnPosDstToSrc(dst, src, pos_thres, hard_thres);
return res;
}
}
intVec MeshTools::forceXMatch(const MeshCompress& src, const MeshCompress& dst, double pos_thres)
{
if (src.pos_.size() != dst.pos_.size())
{
LOG(ERROR) << "forceXMatch must have same size" << std::endl;
}
int n_size = src.n_vertex_;
doubleVec src_x(n_size, 0), dst_x(n_size, 0);
for (int i = 0; i < n_size; i++)
{
src_x[i] = src.pos_[i].x();
dst_x[i] = dst.pos_[i].x();
}
intVec src_order(n_size, -1), dst_order(n_size, -1);
CalcHelper::pairSort(src_x, src_order);
CalcHelper::pairSort(dst_x, dst_order);
intVec inv_src_order = MAP::getReverseMapping(src_order);
intVec inv_dst_order = MAP::getReverseMapping(dst_order);
intVec src_dst_match(n_size, 0);
for (int i = 0; i < n_size; i++)
{
src_dst_match[inv_src_order[i]] = inv_dst_order[i];
}
return src_dst_match;
}
intVec MeshTools::getMatchBasedOnPosRoi(const MeshCompress& src, const intVec& src_roi, const intVec& dst_roi, double pos_thres, bool hard_thres)
{
MeshCompress src_part = src;
intVec src_all_to_roi = src_part.keepRoi(src_roi);
MeshCompress dst_part = src;
intVec dst_all_to_roi = dst_part.keepRoi(dst_roi);
//intVec res = getMatchBasedOnPosSrcToDst(src_part, dst_part, pos_thres, hard_thres);
intVec res = forceXMatch(src_part, dst_part, pos_thres);
intVec match_src_dst(res.size()*2, 0);
intVec inv_src_all_to_roi = MAP::getReverseMapping(src_all_to_roi);
intVec inv_dst_all_to_roi = MAP::getReverseMapping(dst_all_to_roi);
int n_size = res.size();
for (int i = 0; i < n_size; i++)
{
int inv_map_src_idx = inv_src_all_to_roi[i];
int inv_map_dst_idx = inv_dst_all_to_roi[res[i]];
if (inv_map_src_idx<0 || inv_map_src_idx>src.n_vertex_ || inv_map_dst_idx<0 || inv_map_dst_idx>src.n_vertex_)
{
LOG(ERROR) << "safe check failed." << std::endl;
}
else
{
match_src_dst[2 * i + 0] = inv_map_src_idx;
match_src_dst[2 * i + 1] = inv_map_dst_idx;
}
}
return match_src_dst;
}
intVec MeshTools::getMatchBasedOnPosRoiSimX(const MeshCompress& src, const intVec& src_roi, const intVec& dst_roi, double pos_thres, bool hard_thres)
{
MeshCompress src_part = src;
intVec src_all_to_roi = src_part.keepRoi(src_roi);
MeshCompress dst_part = src;
intVec dst_all_to_roi = dst_part.keepRoi(dst_roi);
intVec res = getMatchBasedOnPosSrcToDst(src_part, dst_part, pos_thres, hard_thres);
intVec match_src_dst(res.size() * 2, 0);
intVec inv_src_all_to_roi = MAP::getReverseMapping(src_all_to_roi);
intVec inv_dst_all_to_roi = MAP::getReverseMapping(dst_all_to_roi);
int n_size = res.size();
for (int i = 0; i < n_size; i++)
{
int inv_map_src_idx = inv_src_all_to_roi[i];
int inv_map_dst_idx = inv_dst_all_to_roi[res[i]];
if (inv_map_src_idx<0 || inv_map_src_idx>src.n_vertex_ || inv_map_dst_idx<0 || inv_map_dst_idx>src.n_vertex_)
{
LOG(ERROR) << "safe check failed." << std::endl;
}
else
{
match_src_dst[2 * i + 0] = inv_map_src_idx;
match_src_dst[2 * i + 1] = inv_map_dst_idx;
}
}
return match_src_dst;
}
intVec MeshTools::getDoubleMatchBasedOnPos(const MeshCompress& src, const MeshCompress& dst, double pos_thres,
bool hard_thres)
{
if (src.pos_.empty() || dst.pos_.empty())
{
LOG(ERROR) << "src && dst is switched." << std::endl;
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec match_dst_src(n_dst, -1);
intVec match_src_dst(n_src, -1);
for (int i = 0; i < n_dst; i++)
{
//matching pos is not valid
floatVec match_pos(n_src, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_src; j++)
{
match_pos[j] = (dst.pos_[i] - src.pos_[j]).norm();
}
auto res = std::minmax_element(match_pos.begin(), match_pos.end());
int match_id = res.first - match_pos.begin();
if (match_id < 0 || match_id >= n_src)
{
LOG(ERROR) << "match error" << std::endl;
}
if (!hard_thres)
{
match_dst_src[i] = match_id;
if (*res.first > pos_thres)
{
LOG(INFO) << "*res.second: " << *res.first << std::endl;
LOG(ERROR) << "res dis larger than threshold." << std::endl;
}
}
else
{
if (*res.first < pos_thres)
{
match_dst_src[i] = match_id;
}
}
}
//map reverse
for (int i = 0; i < n_src; i++)
{
//matching pos is not valid
floatVec match_pos(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
match_pos[j] = (src.pos_[i] - dst.pos_[j]).norm();
}
auto res = std::minmax_element(match_pos.begin(), match_pos.end());
int match_id = res.first - match_pos.begin();
if (match_id < 0 || match_id >= n_dst)
{
LOG(ERROR) << "match error" << std::endl;
}
if (!hard_thres)
{
match_src_dst[i] = match_id;
if (*res.first > pos_thres)
{
LOG(INFO) << "*res.second: " << *res.first << std::endl;
LOG(ERROR) << "res dis larger than threshold." << std::endl;
}
}
else
{
if (*res.first < pos_thres)
{
match_src_dst[i] = match_id;
}
}
}
//filter
int match_count = 0;
intVec src_to_dst(n_src, -1);
for (int i = 0; i < n_src; i++)
{
int idx_dst = match_src_dst[i];
int idx_src = -1;
if (idx_dst >= 0 && idx_dst < n_dst)
{
idx_src = match_dst_src[idx_dst];
if (i == idx_src)
{
src_to_dst[i] = idx_dst;
match_count++;
}
}
}
LOG(INFO) << "double map: " << match_count << std::endl;
return src_to_dst;
}
intVec MeshTools::getMatchBasedOnUV(const MeshCompress& src, const MeshCompress& dst, double uv_thres)
{
if (src.n_vertex_ <= 0 || dst.n_vertex_ <= 0)
{
LOG(ERROR) << "vertex empty" << std::endl;
}
if (src.n_uv_ < src.n_vertex_ || dst.n_uv_ < dst.n_vertex_)
{
LOG(ERROR) << "must have uv info." << std::endl;
}
if (src.tri_.size() != src.tri_uv_.size() || dst.tri_.size() != dst.tri_uv_.size())
{
LOG(ERROR) << "triangle is not the same with triangle based uv" << std::endl;
}
//get vertex to uv index
intSetVec src_uv_idx, dst_uv_idx;
src_uv_idx.resize(src.n_vertex_);
dst_uv_idx.resize(dst.n_vertex_);
for (int iter_vertex = 0; iter_vertex < src.n_tri_ * 3; iter_vertex++)
{
int vertex_idx = src.tri_[iter_vertex];
int uv_idx = src.tri_uv_[iter_vertex];
src_uv_idx[vertex_idx].insert(uv_idx);
}
for (int iter_vertex = 0; iter_vertex < dst.n_tri_ * 3; iter_vertex++)
{
int vertex_idx = dst.tri_[iter_vertex];
int uv_idx = dst.tri_uv_[iter_vertex];
dst_uv_idx[vertex_idx].insert(uv_idx);
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec match_src_dst(n_src, -1);
for (int i = 0; i < n_src; i++)
{
int src_id = i;
//matching pos is not valid
//save for match_uv minimal
floatVec match_uv(n_dst, INT_MAX);
floatVec match_dis(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
int dst_id = j;
double min_uv_dis = INT_MAX;
for (int iter_i : src_uv_idx[i])
{
for (int iter_j : dst_uv_idx[j])
{
min_uv_dis = DMIN(min_uv_dis, (src.tex_cor_[iter_i] - dst.tex_cor_[iter_j]).norm());
}
}
match_uv[j] = min_uv_dis;
match_dis[j] = match_uv[j];
}
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
match_src_dst[i] = match_id;
if (*res.first > uv_thres)
{
LOG(INFO) << "*res.second: " << *res.first << std::endl;
LOG(ERROR) << "res dis larger than threshold." << std::endl;
}
}
return match_src_dst;
}
intVec MeshTools::getMatchRawUV(const MeshCompress& src, const MeshCompress& dst, double thres)
{
if (src.pos_.empty() || dst.pos_.empty() || src.tri_uv_.empty() || dst.tri_uv_.empty())
{
LOG(INFO) << "src.n_vertex_ :" << src.n_vertex_ << std::endl;
LOG(INFO) << "dst.n_vertex_ :" << dst.n_vertex_ << std::endl;
LOG(INFO) << "src.n_tri_uv_ :" << src.n_uv_ << std::endl;
LOG(INFO) << "dst.n_tri_uv_ :" << dst.n_uv_ << std::endl;
LOG(ERROR) << "data check failed." << std::endl;
return {};
}
//get vertex to uv index
intSetVec src_uv_idx, dst_uv_idx;
src_uv_idx.resize(src.n_vertex_);
dst_uv_idx.resize(dst.n_vertex_);
for (int iter_vertex = 0; iter_vertex < src.n_tri_ * 3; iter_vertex++)
{
int vertex_idx = src.tri_[iter_vertex];
int uv_idx = src.tri_uv_[iter_vertex];
src_uv_idx[vertex_idx].insert(uv_idx);
}
for (int iter_vertex = 0; iter_vertex < dst.n_tri_ * 3; iter_vertex++)
{
int vertex_idx = dst.tri_[iter_vertex];
int uv_idx = dst.tri_uv_[iter_vertex];
dst_uv_idx[vertex_idx].insert(uv_idx);
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec match_src_dst(n_src, -1);
for (int i = 0; i < n_src; i++)
{
int src_id = i;
//matching pos is not valid
//save for match_uv minimal
floatVec match_uv(n_dst, INT_MAX);
floatVec match_dis(n_dst, INT_MAX);
#pragma omp parallel for
for (int j = 0; j < n_dst; j++)
{
int dst_id = j;
double min_uv_dis = INT_MAX;
for (int iter_i : src_uv_idx[i])
{
for (int iter_j : dst_uv_idx[j])
{
//todo use same side
if (src.pos_[i].x()*dst.pos_[j].x() > -1e-5)
{
min_uv_dis = DMIN(min_uv_dis, (src.tex_cor_[iter_i] - dst.tex_cor_[iter_j]).norm());
}
}
}
match_uv[j] = min_uv_dis;
match_dis[j] = match_uv[j];
}
auto res = std::minmax_element(match_dis.begin(), match_dis.end());
int match_id = res.first - match_dis.begin();
match_src_dst[i] = match_id;
if (*res.first > thres)
{
//LOG(INFO) << "*res.second: " << *res.first << std::endl;
//(ERROR) << "res dis larger than threshold." << std::endl;
match_src_dst[i] = -1;
}
}
return match_src_dst;
}
intVec MeshTools::getMatchAnyUV(const MeshCompress& src, const MeshCompress& dst, double pos_thres,
bool hard_thres)
{
if (src.pos_.empty() || dst.pos_.empty() || src.tri_uv_.empty() || dst.tri_uv_.empty())
{
LOG(INFO) << "src.n_vertex_ :" << src.n_vertex_ << std::endl;
LOG(INFO) << "dst.n_vertex_ :" << dst.n_vertex_ << std::endl;
LOG(INFO) << "src.n_tri_uv_ :" << src.n_uv_ << std::endl;
LOG(INFO) << "dst.n_tri_uv_ :" << dst.n_uv_ << std::endl;
LOG(ERROR) << "data check failed." << std::endl;
return {};
}
//matching
int n_src = src.n_vertex_;
int n_dst = dst.n_vertex_;
intVec map_src_to_dst = getMatchRawUV(src, dst, pos_thres);
intVec map_dst_to_src = getMatchRawUV(dst, src, pos_thres);
intVec match_src_to_dst_bi(n_src, -1);
intSet discard_multi_matching;
//#pragma omp parallel for
for (int i = 0; i < n_src; i++)
{
int src_idx = i;
int dst_idx = map_src_to_dst[i];
if (dst_idx > -1 && dst_idx < n_dst && map_dst_to_src[dst_idx] == src_idx)
{
match_src_to_dst_bi[src_idx] = dst_idx;
}
else
{
discard_multi_matching.insert(src_idx);
}
}
LOG(INFO) << "discard size: " << discard_multi_matching.size() << std::endl;
return map_src_to_dst;
return match_src_to_dst_bi;
}
void MeshTools::scaleBSInPlace(const MeshCompress& src, double scale, MeshCompress& dst)
{
if (src.pos_.size() != dst.pos_.size())
{
LOG(ERROR) << "src && dst size not fit." << std::endl;
return;
}
int n_vertex = src.pos_.size();
#pragma omp parallel for
for (int i = 0; i < n_vertex; i++)
{
dst.pos_[i] = (dst.pos_[i] - src.pos_[i])*scale + src.pos_[i];
}
} | [
"renji.xyh@vip.163.com"
] | renji.xyh@vip.163.com |
900bfab3c29ca6a4e20c04300fd3a7d1a3630f4f | 23b81eaa336b814e99e3b5da71273ffad71a0836 | /frameworkD3D11/main.h | 8d516483c807feef697173c210bc741ec8930dbb | [
"MIT"
] | permissive | techmatt/d3d11-interceptor | 233b94f6559f1f59836de763db96e5a026d9e2f5 | fd49b8c60eb3b4c1b95f56ba9ce1cf76ab2aa6cf | refs/heads/master | 2016-08-05T08:20:46.361909 | 2015-10-14T23:27:25 | 2015-10-14T23:27:25 | 39,213,244 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 755 | h |
//#define USE_INTERCEPTOR_D3D11DLL
#include "mLibInclude.h"
#ifdef USE_INTERCEPTOR_D3D11DLL
#pragma warning ( disable : 4005)
#include <d3d11.h>
__declspec(dllimport) HRESULT WINAPI myD3D11CreateDeviceAndSwapChain(IDXGIAdapter* p0, D3D_DRIVER_TYPE p1, HMODULE p2, UINT p3, const D3D_FEATURE_LEVEL* p4, UINT p5, UINT p6, const DXGI_SWAP_CHAIN_DESC * p7, IDXGISwapChain ** p8, ID3D11Device** p9, D3D_FEATURE_LEVEL* p10, ID3D11DeviceContext ** p11);
__declspec(dllimport) HRESULT WINAPI myD3D11CreateDevice(IDXGIAdapter* p0, D3D_DRIVER_TYPE p1, HMODULE p2, UINT p3, const D3D_FEATURE_LEVEL* p4, UINT p5, UINT p6, ID3D11Device** p7, D3D_FEATURE_LEVEL* p8, ID3D11DeviceContext ** p9);
#endif
using namespace ml;
using namespace std;
#include "vizzer.h"
| [
"techmatt@gmail.com"
] | techmatt@gmail.com |
ca5f5e44cc30ffeb530e2ff053a0350f19815f8c | 0d0e78c6262417fb1dff53901c6087b29fe260a0 | /bda/include/tencentcloud/bda/v20200324/model/UpperBodyCloth.h | 817864b860e866e9387e7ffeb1e6e61c2c0f12ca | [
"Apache-2.0"
] | permissive | li5ch/tencentcloud-sdk-cpp | ae35ffb0c36773fd28e1b1a58d11755682ade2ee | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | refs/heads/master | 2022-12-04T15:33:08.729850 | 2020-07-20T00:52:24 | 2020-07-20T00:52:24 | 281,135,686 | 1 | 0 | Apache-2.0 | 2020-07-20T14:14:47 | 2020-07-20T14:14:46 | null | UTF-8 | C++ | false | false | 4,539 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_BDA_V20200324_MODEL_UPPERBODYCLOTH_H_
#define TENCENTCLOUD_BDA_V20200324_MODEL_UPPERBODYCLOTH_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/bda/v20200324/model/UpperBodyClothTexture.h>
#include <tencentcloud/bda/v20200324/model/UpperBodyClothColor.h>
#include <tencentcloud/bda/v20200324/model/UpperBodyClothSleeve.h>
namespace TencentCloud
{
namespace Bda
{
namespace V20200324
{
namespace Model
{
/**
* 上衣属性信息
*/
class UpperBodyCloth : public AbstractModel
{
public:
UpperBodyCloth();
~UpperBodyCloth() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取上衣纹理信息。
* @return Texture 上衣纹理信息。
*/
UpperBodyClothTexture GetTexture() const;
/**
* 设置上衣纹理信息。
* @param Texture 上衣纹理信息。
*/
void SetTexture(const UpperBodyClothTexture& _texture);
/**
* 判断参数 Texture 是否已赋值
* @return Texture 是否已赋值
*/
bool TextureHasBeenSet() const;
/**
* 获取上衣颜色信息。
* @return Color 上衣颜色信息。
*/
UpperBodyClothColor GetColor() const;
/**
* 设置上衣颜色信息。
* @param Color 上衣颜色信息。
*/
void SetColor(const UpperBodyClothColor& _color);
/**
* 判断参数 Color 是否已赋值
* @return Color 是否已赋值
*/
bool ColorHasBeenSet() const;
/**
* 获取上衣衣袖信息。
* @return Sleeve 上衣衣袖信息。
*/
UpperBodyClothSleeve GetSleeve() const;
/**
* 设置上衣衣袖信息。
* @param Sleeve 上衣衣袖信息。
*/
void SetSleeve(const UpperBodyClothSleeve& _sleeve);
/**
* 判断参数 Sleeve 是否已赋值
* @return Sleeve 是否已赋值
*/
bool SleeveHasBeenSet() const;
private:
/**
* 上衣纹理信息。
*/
UpperBodyClothTexture m_texture;
bool m_textureHasBeenSet;
/**
* 上衣颜色信息。
*/
UpperBodyClothColor m_color;
bool m_colorHasBeenSet;
/**
* 上衣衣袖信息。
*/
UpperBodyClothSleeve m_sleeve;
bool m_sleeveHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_BDA_V20200324_MODEL_UPPERBODYCLOTH_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
9c82e834c82e5f5d6410eb7c9209697692950021 | c42394103684fa1e6196e37f7637d34a6fa868a9 | /.history/main_20210401110018.cpp | 8a37f7cb746b88b6972dc6b59d3cca6d2deb30c1 | [] | no_license | csanshi/CodeCraft-2021 | ca802ee9ef9768940458b4eca8460c7cb0be80e9 | 3cf9c1ba0eb55eb9bee01c35dddec72b8490bb0c | refs/heads/main | 2023-04-05T05:11:08.573608 | 2021-04-17T08:56:49 | 2021-04-17T08:56:49 | 357,412,667 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,579 | cpp | #include<iostream>
#include<string>
#include<vector>
#include<unordered_map>
#include<sstream>
#include<cassert>
#include<cstring>
#include<algorithm>
#include<ctime>
using namespace std;
#define TEST
const int INF = 0x3f3f3f3f;
const char* AB[] = {"A", "B"};
const string inputFilePaths[3] = {" ","training-data/training-1.txt", "training-data/training-2.txt"};
int testedFile = 1;
string inputFilePath = inputFilePaths[testedFile];
const string outputFilePath = "output.txt";
// const double ratio1 = 1.5, ratio2 = 1.2;
const double ratio = 1;
// string serverModel = "hostDPJA1";
int purchaseVersion = 1; // 0-只买一种 1-买最便宜
int migrationVersion = 1; // 0-AB无选择地插入,1-AB有选择地插入
int deployVersion = 0; // 0-打分 1-排序
typedef pair<int, int>PII;
typedef pair<string, int>PSI;
struct Tuple{
int serverId, node, vmId;
};
struct ServerInfo{
int core, mem;
int cost_hardware, cost_power;
string model;
};
struct VirtualMachineInfo{
int core, mem, type;
};
struct Position{
int idx, node;
};
struct MigrateInfo{
int vm_id,server_id, node;
};
unordered_map<string, ServerInfo>serverDict;
vector<ServerInfo>sortedServerList;
unordered_map<string, VirtualMachineInfo>vmDict;
// vector<string, VirtualMachineInfo>sortedVmList;
unordered_map<int, Position>vmToServer;
unordered_map<string, string>vmToMinPowerCostServer;
struct Request{
char op;
string model;
int id;
};
class Server{
public:
int core[2], mem[2]; // left
int powerCost;
int id;
int capacity_core, capacity_mem;
unordered_map<int, VirtualMachineInfo>vms;
Server(const ServerInfo& serverInfo){
capacity_core = serverInfo.core;
capacity_mem = serverInfo.mem;
core[0] = core[1] = serverInfo.core/2;
mem[0] = mem[1] = serverInfo.mem/2;
this->powerCost = serverInfo.cost_power;
vms.clear();
}
double getTotalLeft(){
return (this->core[0] + this->core[1])*ratio +
(this->mem[0] + this->mem[1]);
}
/*
传入vm
返回:1. 对于单结点虚拟机: A、B节点中cost较小的那个cost,同时返回true. res = (node, cost)
2. 对于双节点虚拟机:返回true. res = (2, cost)
无法插入返回false
*/
bool getCost(VirtualMachineInfo& vm, PII& res){
if(vm.type == 0){ // 单结点虚拟机
int minCost = INF, minNode = -1;
for(int node = 0; node < 2; node++){
if(core[node] >= vm.core && mem[node] >= vm.mem){
int cost = abs(core[node] - vm.core - (mem[node] - vm.mem));
if(cost < minCost){
minCost = cost;
minNode = node;
}
}
}
if(minNode == -1) return false;
res = {minNode, minCost};
return true;
}else{ // 双节点虚拟机
for(int node = 0; node < 2; node++){
if(core[node] < vm.core/2 || mem[node] < vm.mem/2) return false;
}
int cost = abs(core[0] - vm.core/2 + core[1] - vm.core/2 -
(mem[0] - vm.mem/2 + mem[1] - vm.mem/2));
res = {2, cost};
return true;
}
return false;
}
// A B节点无区别插
int addVm(VirtualMachineInfo& vm, int id){
if(vm.type == 0){ // 单结点虚拟机
for(int node = 0; node < 2; node++){
if(core[node] >= vm.core && mem[node] >= vm.mem){
core[node] -= vm.core;
mem[node] -= vm.mem;
vms[id] = vm;
return node;
}
}
}else{ // 双节点虚拟机
for(int node = 0; node < 2; node++){
if(core[node] < vm.core/2 || mem[node] < vm.mem/2) return -1;
}
core[0] -= vm.core/2; core[1] -= vm.core/2;
mem[0] -= vm.mem/2; mem[1] -= vm.mem/2;
vms[id] = vm;
return 2;
}
return -1;
}
// A B节点有选择地插
int addVm2(VirtualMachineInfo& vm, int id){
PII res;
int ok = this->getCost(vm, res);
if(!ok) return -1;
this->addVm(vm, id, res.first);
return res.first;
}
int addVm(string model, int id){
VirtualMachineInfo vm = vmDict[model];
if(vm.type == 0){ // 单结点虚拟机
for(int node = 0; node < 2; node++){
if(core[node] >= vm.core && mem[node] >= vm.mem){
core[node] -= vm.core;
mem[node] -= vm.mem;
vms[id] = vm;
return node;
}
}
}else{ // 双节点虚拟机
for(int node = 0; node < 2; node++){
if(core[node] < vm.core/2 || mem[node] < vm.mem/2) return -1;
}
core[0] -= vm.core/2; core[1] -= vm.core/2;
mem[0] -= vm.mem/2; mem[1] -= vm.mem/2;
vms[id] = vm;
return 2;
}
return -1;
}
void addVm(string model, int id, int node){
VirtualMachineInfo vm = vmDict[model];
if(vm.type == 0){ // 单结点虚拟机
core[node] -= vm.core;
mem[node] -= vm.mem;
vms[id] = vm;
}else{ // 双节点虚拟机
core[0] -= vm.core/2; core[1] -= vm.core/2;
mem[0] -= vm.mem/2; mem[1] -= vm.mem/2;
vms[id] = vm;
}
}
void addVm(VirtualMachineInfo& vm, int id, int node){
if(vm.type == 0){ // 单结点虚拟机
core[node] -= vm.core;
mem[node] -= vm.mem;
vms[id] = vm;
}else{ // 双节点虚拟机
core[0] -= vm.core/2; core[1] -= vm.core/2;
mem[0] -= vm.mem/2; mem[1] -= vm.mem/2;
vms[id] = vm;
}
}
/*
node: 0-A节点,1-B节点,2-AB节点
*/
void delVm(int id, int node){
VirtualMachineInfo vm = vms[id];
if(node == 0 || node == 1){
core[node] += vm.core;
mem[node] += vm.mem;
}else{
core[0] += vm.core/2; core[1] += vm.core/2;
mem[0] += vm.mem/2; mem[1] += vm.mem/2;
}
vms.erase(id);
}
};
void buildOutputStream(const vector<PSI>&book, const vector<MigrateInfo>&migrationInfo, const vector<Tuple>addInfo, vector<int>&idxForAddInfo){ //
cout << "(purchase, " << book.size() << ")\n";
for(auto& kv : book){
cout << "(" << kv.first << ", " << kv.second << ")\n";
}
cout << "(migration, " << migrationInfo.size() << ")" << endl;
for(auto& e : migrationInfo){
if(e.node == 2){
cout << "(" << e.vm_id << ", " << e.server_id << ")\n";
}else{
cout << "(" << e.vm_id << ", " << e.server_id << ", " << AB[e.node] << ")\n";
}
}
int n = idxForAddInfo.size();
int A[n];
for(int i = 0; i < n; i++){
A[idxForAddInfo[i]] = i;
}
for(int i = 0; i < n; i++){
const Tuple& e = addInfo[A[i]];
int id = e.serverId, node = e.node;
if(node != 2) cout << "(" << id << ", " << AB[node] << ")\n" ;
else cout << "(" << id << ")\n";
}
fflush(stdout);
}
class ServerResource{
public:
vector<Server>servers;
long long COST_HARDWARE, COST_POWER;
vector<PSI>purchaseInfo; // (server_model, vm_id)
vector<MigrateInfo>migrationInfo;
vector<Tuple>addInfo;
vector<int>idxForAddInfo;
vector<PSI>addRequests;
int totalVm = 0;
ServerResource(){
servers.clear();
COST_HARDWARE = COST_POWER = 0;
this->totalVm = 0;
}
void handleRequestsInTheFirstKDays(vector<Request>requestsInTheFirstKDays[], int K){
for(int i = 0; i < K; i++)
this->handleRequestsInOneDay(requestsInTheFirstKDays[i]);
}
void handleRequestsInOneDay(vector<Request>& requests){
this->addInfo.clear();
this->purchaseInfo.clear();
this->idxForAddInfo.clear();
this->addRequests.clear();
this->migrationInfo.clear();
this->migrateByVersion(migrationVersion);
int n = requests.size();
int cnt_add = 0;
for(int i = 0; i < n;){
if(requests[i].op == 'a'){
int j = i;
while(j < n && requests[j].op == 'a'){
addRequests.push_back({requests[j].model, requests[j].id});
j++;
}
for(int k = 0; k < (j-i); k++) idxForAddInfo.push_back(cnt_add + k);
// 给add请求按照所要求的资源从大到小排序
sort(this->idxForAddInfo.begin() + cnt_add, this->idxForAddInfo.begin() + cnt_add + j-i, [&](int x, int y){
return ratio*vmDict[addRequests[x].first].core + vmDict[addRequests[x].first].mem
< ratio*vmDict[addRequests[y].first].core + vmDict[addRequests[y].first].mem;
});
for(int k = cnt_add; k < cnt_add + j-i; k++) {
PSI& addRequest = addRequests[idxForAddInfo[k]];
this->deployByVersion(addRequest.first, addRequest.second, deployVersion);
this->totalVm++;
}
cnt_add += j - i;
i = j;
} else {
this->handleDeleteRequest(requests[i].id);
this->totalVm--;
i++;
}
}
n = this->purchaseInfo.size();
vector<PSI>book;
// 编号重排,构造输出信息
if(n > 0){
int res[n]; memset(res, -1, sizeof(res));
int cnt = 0;
for(int i = 0; i < n; i++){
if(res[i] != -1) continue;
res[i] = cnt++;
int j = i+1, num = 1;
for(; j < n; j++){
if(this->purchaseInfo[j].first == this->purchaseInfo[i].first){
res[j] = cnt++;
num++;
}
}
book.push_back({purchaseInfo[i].first, num});
}
// 新购买的服务器,需要修改其id
for(int i = 0; i < n; i++){
auto& pi = purchaseInfo[i];
Position& pos = vmToServer[pi.second];
this->servers[pos.idx].id = this->servers.size() - n + res[i];
}
// 部署信息
for(auto& e : addInfo){
Position& pos = vmToServer[e.vmId];
e.serverId = this->servers[pos.idx].id;
}
}
buildOutputStream(book, this->migrationInfo, addInfo, this->idxForAddInfo); //, this->idxForAddInfo
this->calPowerCost();
}
string purchaseAsRequired(string vmModel){
VirtualMachineInfo& vm = vmDict[vmModel];
// string preferedModel = purchaseVersion == 0 ? serverModel : vmToMinPowerCostServer[vmModel];
string preferedModel = vmToMinPowerCostServer[vmModel];
ServerInfo server = serverDict[preferedModel];
this->servers.push_back(server);
COST_HARDWARE += server.cost_hardware;
return preferedModel;
}
void migrateByVersion(int version){
switch (version){
case 0:
this->migrate0();
break;
case 1:
this->migrate1();
break;
default:
break;
}
}
void deployByVersion(string model, int id, int version){
switch (version){
case 0:
this->deploy0(model, id);
break;
default:
break;
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// A B无选择地插入,即调用addVm
void migrate0(){
int n = this->servers.size();
int idx[n]; for(int i = 0; i < n; i++) idx[i] = i;
sort(idx, idx + n, [&](int x, int y){
return this->servers[x].getTotalLeft() > this->servers[y].getTotalLeft();
// return this->servers[x].vms.size() > this->servers[y].vms.size();
});
int total = this->totalVm;
int limit = 3*total/100, curMigrationNum = 0;
for(int i = 0; i < n-1; i++){
Server& server = this->servers[idx[i]];
vector<PII>deleted; // (vm_id, node)
for(auto& vm : server.vms){
if(curMigrationNum+1 > limit) break;
int node = -1;
int toServer = n-1;
while(toServer > i && (node = this->servers[idx[toServer]].addVm(vm.second, vm.first)) == -1){
toServer--;
}
if(node == -1){ // 无处可插
break ;
}else{
// server.delVm(vm.first, node, false); // 不能在这里删除!!!!!
this->migrationInfo.push_back({vm.first, this->servers[idx[toServer]].id, node});
deleted.push_back({vm.first, vmToServer[vm.first].node}); // 收集delete信息,待本服务器这个vm循环退出再一起移除。
vmToServer[vm.first] = {idx[toServer], node};
curMigrationNum++;
}
}
for(auto& pii : deleted){
server.delVm(pii.first, pii.second);
}
if(curMigrationNum+1 > limit) break;
}
return;
}
// A B有选择地插入,即调用addVm2
void migrate1(){
int n = this->servers.size();
int idx[n]; for(int i = 0; i < n; i++) idx[i] = i;
sort(idx, idx + n, [&](int x, int y){
return this->servers[x].getTotalLeft() > this->servers[y].getTotalLeft();
// return this->servers[x].vms.size() > this->servers[y].vms.size();
});
int total = this->totalVm;
int limit = 3*total/100, curMigrationNum = 0;
for(int i = 0; i < n-1; i++){
Server& server = this->servers[idx[i]];
vector<PII>deleted; // (vm_id, node)
for(auto& vm : server.vms){
if(curMigrationNum+1 > limit) break;
int node = -1;
int toServer = n-1;
while(toServer > i && (node = this->servers[idx[toServer]].addVm2(vm.second, vm.first)) == -1){
toServer--;
}
if(node == -1){ // 无处可插
break ;
}else{
// server.delVm(vm.first, node, false); // 不能在这里删除!!!!!
this->migrationInfo.push_back({vm.first, this->servers[idx[toServer]].id, node});
deleted.push_back({vm.first, vmToServer[vm.first].node}); // 收集delete信息,待本服务器这个vm循环退出再一起移除。
vmToServer[vm.first] = {idx[toServer], node};
curMigrationNum++;
}
}
for(auto& pii : deleted){
server.delVm(pii.first, pii.second);
}
if(curMigrationNum+1 > limit) break;
}
return;
}
int bestFit(string model, int id, PII& res){
VirtualMachineInfo vm = vmDict[model];
int idx1 = -1, idx2 = -1;
PII minRes1 = {-1, INF}, minRes2 = {-1, INF};
for(int i = 0; i < this->servers.size(); i++){
Server& server = this->servers[i];
PII res;
int ok = server.getCost(vm, res);
if(!ok) continue;
if(!server.vms.empty() && res.second < minRes1.second){
minRes1 = res;
idx1 = i;
}else if(idx1 == -1 && // 如果在开机的服务器中找到了可以插的,那么根本无需考虑不开机的服务器
server.vms.empty() && res.second < minRes2.second){ // 空且
minRes2 = res;
idx2 = i;
}
}
if(idx1 != -1) {
res = minRes1; return idx1;
}else if(idx2 != -1){
res = minRes2; return idx2;
}
return -1;
}
void deploy0(string model, int id){
VirtualMachineInfo vm = vmDict[model];
PII minRes = {-1, INF};
int idx = bestFit(model, id, minRes);
if(idx != -1){ // 在已有的服务器中找到了
this->servers[idx].addVm(model, id, minRes.first);
this->addInfo.push_back({servers[idx].id, minRes.first, id});
vmToServer[id] = {idx, minRes.first};
}else{ // 需要购买
string serverModel = this->purchaseAsRequired(model);
this->purchaseInfo.push_back({serverModel, id}); // 为编号为id的虚拟机购买了型号为serverModel的服务器
int node = this->servers.back().
addVm(model, id);
this->addInfo.push_back({-1, node, id});
vmToServer[id] = {(int)(this->servers.size()-1), node};
}
}
void handleDeleteRequest(int id){
Position& pos = vmToServer[id];
this->servers[pos.idx].delVm(id, pos.node);
vmToServer.erase(id); ////////////////////
}
void calPowerCost(){
for(auto& server : this->servers){
if(!server.vms.empty()){
this->COST_POWER += server.powerCost;
}
}
}
};
ServerResource serverResource;
void readServerInfos(string model, string core, string mem, string cost1, string cost2){
int i_core = stoi(core);
int i_mem = stoi(mem);
int i_cost1 = stoi(cost1);
int i_cost2 = stoi(cost2);
serverDict[model] = {i_core, i_mem, i_cost1, i_cost2, model};
sortedServerList.push_back({i_core, i_mem, i_cost1, i_cost2, model});
}
void readVmInfos(string model, string core, string mem, string isDouble){
int i_core = stoi(core);
int i_mem = stoi(mem);
vmDict[model] = {i_core, i_mem, isDouble[0]-'0'};
}
void buildServerAndVmDict(){
// 读服务器
int N; cin >> N; // 最大100
for(int i = 0; i < N; i++){
string model, core, mem, cost1, cost2;
cin >> model >> core >> mem >> cost1 >> cost2;
readServerInfos(model.substr(1, model.size()-2),
core.substr(0, core.size()-1), mem.substr(0, mem.size()-1),
cost1.substr(0, cost1.size()-1), cost2.substr(0, cost2.size()-1));
}
// 预处理服务器
sort(sortedServerList.begin(), sortedServerList.end(), [](ServerInfo& x, ServerInfo& y){
return x.cost_power < y.cost_power;
});
// 读虚拟机
int M; cin >> M; // 最大1000
for(int i = 0; i < M; i++){
string model, core, mem, isDouble;
cin >> model >> core >> mem >> isDouble;
readVmInfos(model.substr(1, model.size()-2),
core.substr(0, core.size()-1), mem.substr(0, mem.size()-1),
isDouble.substr(0, isDouble.size()-1));
}
}
void buildVmToServerWithMinPowerCost(){
auto check = [](VirtualMachineInfo& vm, ServerInfo& server){
if(vm.type == 0){
return vm.core <= server.core/2 && vm.mem <= server.mem/2;
}else{
return vm.core <= server.core && vm.mem <= server.mem;
}
};
for(auto& vm : vmDict){
// vmToMinPowerCostServer[vm.first] = serverModel;
for(auto& server : sortedServerList){
if(check(vm.second, server)){
vmToMinPowerCostServer[vm.first] = server.model;
break;
}
}
}
}
void solve(){
int T, K; cin >> T >> K; // 最大1000 ,add操作不超过100000
auto readOneDay = [](vector<Request>& requests){
int R; cin >> R;
while(R--){
string op, model, id;
cin >> op;
if(op[1] == 'a') cin >> model >> id;
else cin >> id;
requests.push_back(
{op[1], model.substr(0, model.size()-1), stoi(id.substr(0, id.size()-1))}
);
}
};
vector<Request> requestsInTheFirstKDays[K];
for(int t = 0; t < K; t++){
readOneDay(requestsInTheFirstKDays[t]);
}
serverResource.handleRequestsInTheFirstKDays(requestsInTheFirstKDays, K);
for(int t = K; t < T; t++){
vector<Request>requestInfos;
readOneDay(requestInfos);
serverResource.handleRequestsInOneDay(requestInfos);
}
}
int main(){
#ifdef TEST //重定向
freopen(inputFilePath.c_str(), "rb", stdin);
freopen(outputFilePath.c_str(), "wb", stdout);
clock_t start, finish;
start = clock();
#endif
ios::sync_with_stdio(false);
buildServerAndVmDict();
buildVmToServerWithMinPowerCost();
solve();
#ifdef TEST
finish = clock();
cout << endl;
cout << "data" << testedFile << ":" << endl;
cout << "COST_HARDWARE: " << serverResource.COST_HARDWARE << endl;
cout << "COST_POWER: " << serverResource.COST_POWER << endl;
cout << "COST: " << serverResource.COST_HARDWARE + serverResource.COST_POWER << endl;
cout << "Number of vm: " << serverResource.totalVm << endl;
cout << "Time used: " << (finish-start) / CLOCKS_PER_SEC << "s" << endl;
#endif
// system("pause");
return 0;
} | [
"409147163@qq.com"
] | 409147163@qq.com |
f4f46e210d152f7046446a4904a21dc3ea60f600 | 21af2b2a90caf7d2ab3df75004db2923c1bb564e | /machines/RosPingPong.machine/State_Publish.h | 7445f22661b82ced2e70426b421ce09dcd2ba508 | [] | no_license | lpmayos/catkin_ws | 03b3d316c067f99becbd45f6ba2a45ad7c9c9166 | 5062b7ada6cdc8447dd36bc7ed74212ccd00bf37 | refs/heads/master | 2016-09-09T17:39:56.729117 | 2015-01-14T17:38:30 | 2015-01-14T17:38:30 | 26,480,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,598 | h | //
//State_Publish.h
//
//Automatically created through MiEditCLFSM -- do not change manually!
//
#ifndef __clfsm__RosPingPong_State_Publish_h__
#define __clfsm__RosPingPong_State_Publish_h__
#include "CLState.h"
#include "CLAction.h"
#include "CLTransition.h"
namespace FSM
{
namespace CLM
{
namespace FSMRosPingPong
{
namespace State
{
class Publish: public CLState
{
class OnEntry: public CLAction
{
virtual void perform(CLMachine *, CLState *) const;
};
class OnExit: public CLAction
{
virtual void perform(CLMachine *, CLState *) const;
};
class Internal: public CLAction
{
virtual void perform(CLMachine *, CLState *) const;
};
class Transition_0: public CLTransition
{
public:
Transition_0(int toState = 3): CLTransition(toState) {}
virtual bool check(CLMachine *, CLState *) const;
};
class Transition_1: public CLTransition
{
public:
Transition_1(int toState = 2): CLTransition(toState) {}
virtual bool check(CLMachine *, CLState *) const;
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wzero-length-array"
CLTransition *_transitions[2];
public:
Publish(const char *name = "Publish");
virtual ~Publish();
virtual CLTransition * const *transitions() const { return _transitions; }
virtual int numberOfTransitions() const { return 2; }
# include "State_Publish_Variables.h"
#pragma clang diagnostic pop
};
}
}
}
}
#endif // defined(__gufsm__RosPingPong_State_Publish__)
| [
"lpmayo@gmail.com"
] | lpmayo@gmail.com |
1f1a096a31a23184e03861b9f1d53ce1ffb76f45 | 0cb808cbc8087602107e0e4724f2d177c77a00f3 | /test example/test example/Complex.cpp | 74ba87666259f7314b764fe3830fe23c395e7ec6 | [] | no_license | mikecolistro/First_Year_C-Cplusplus | 861eb965cc3b06f7ae0419701d13c9cb8fe5bb9a | e4898d8983e7373b9aadbc34d809e755cff96a0a | refs/heads/master | 2021-01-10T06:39:29.737468 | 2015-05-28T04:02:35 | 2015-05-28T04:02:35 | 36,413,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | cpp | #include <iostream>
using std::cout;
#include <iomanip>
#include "Complex.h" // complex class definition
//Constructor
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart), imaginary( imaginaryPart )
{
}
//addition operator
Complex Complex::operator+( const Complex &operand2) const
{
return Complex( real + operand2.real,
imaginary + operand2.imaginary );
}
//subtraction operator
Complex Complex::operator-( const Complex &operand2) const
{
return Complex( real - operand2.real,
imaginary - operand2.imaginary );
}
Complex &Complex::operator=( const Complex &right)
{
real = right.real;
imaginary = right.imaginary;
return *this;
}
ostream &operator<<( ostream &output, const Complex &example){
output << "(" << example.real << "," << example.imaginary << ")";
return output;
}
istream &operator>>( istream &input, Complex &example){
input.ignore();
input >> setw(2) >> example.real;
input.ignore();
input >> setw(2) >> example.imaginary;
return input;
}
void Complex::print() const
{
cout << "(" << real << "," << imaginary << ")";
}
| [
"mfcolist@lakeheadu.ca"
] | mfcolist@lakeheadu.ca |
0c7eaecd9604e0ea6efeaad17977d8ebc7fadfae | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_3376.cpp | 3c1d825a1f05f7e6c9d814b9ffe4dbecbd6b1c0a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18 | cpp | (zPend < 2) break; | [
"993273596@qq.com"
] | 993273596@qq.com |
1188fd55dfb2c80e45c0a1ef54b04928646b288e | 67b4bc373412ad450f76c50d2a8473d5542b5169 | /Classes/FrozenLayer.cpp | c8bb7cb6a9ba5594d187820ca1ed6d015d875aa1 | [
"MIT"
] | permissive | AndyZhou3087/JH | 91da3bc72e56bc82085458a0187c4ebe5e2cea49 | 354c19ebf6a962e6c884222fdcd3b8875fe6d016 | refs/heads/master | 2020-05-27T13:56:56.697411 | 2018-04-24T07:17:50 | 2018-04-24T07:17:50 | 82,545,435 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | cpp | #include "FrozenLayer.h"
#include "GlobalData.h"
#include "CommonFuncs.h"
#include "SoundManager.h"
#include "Const.h"
bool FrozenLayer::init()
{
if (!Layer::init())
{
return false;
}
LayerColor* color = LayerColor::create(Color4B(11, 32, 22, 150));
this->addChild(color);
Node* csbnode = CSLoader::createNode("frozenLayer.csb");
this->addChild(csbnode);
cocos2d::ui::Text* content_0 = (cocos2d::ui::Text*)csbnode->getChildByName("content_0");
cocos2d::ui::Text* qqtitle = (cocos2d::ui::Text*)csbnode->getChildByName("qqtext");
content_0->setVisible(false);
qqtitle->setVisible(false);
cocos2d::ui::Text* qq1 = (cocos2d::ui::Text*)csbnode->getChildByName("qq");
qq1->addTouchEventListener(CC_CALLBACK_2(FrozenLayer::onQQ, this));
qq1->setVisible(false);
cocos2d::ui::Text* qq2 = (cocos2d::ui::Text*)csbnode->getChildByName("qq_1");
qq2->addTouchEventListener(CC_CALLBACK_2(FrozenLayer::onQQ, this));
qq2->setVisible(false);
int qqsize = GlobalData::vec_qq.size();
if (qqsize > 0)
{
content_0->setVisible(true);
qqtitle->setVisible(true);
int rqq = GlobalData::createRandomNum(qqsize);
qq1->setString(GlobalData::vec_qq[rqq]);
qq1->setVisible(true);
if (qqsize > 1)
{
qq2->setString(GlobalData::vec_qq[1 - rqq]);
qq2->setVisible(true);
}
else
{
qq2->setVisible(false);
}
}
//////layer 点击事件,屏蔽下层事件
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [=](Touch *touch, Event *event)
{
return true;
};
//点击任何位置移除掉
listener->onTouchEnded = [=](Touch *touch, Event *event)
{
};
listener->setSwallowTouches(true);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
FrozenLayer* FrozenLayer::create()
{
FrozenLayer *pRet = new FrozenLayer();
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
return pRet;
}
void FrozenLayer::onQQ(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type)
{
if (type == ui::Widget::TouchEventType::ENDED)
{
SoundManager::getInstance()->playSound(SoundManager::SOUND_ID_BUTTON);
cocos2d::ui::Text* qq = (cocos2d::ui::Text*)pSender;
GlobalData::copyToClipBoard(qq->getString());
}
}
| [
"zhou_jian007@126.com"
] | zhou_jian007@126.com |
a5ff3bacff6a01576cd5635d379f6e75cae7ff5e | c9d073d4c966119fe8865bc8188330ed32bf9d63 | /src/control/position.cpp | c64e4069c51fe519384e96dbb02d1f4e68eae1cf | [
"MIT"
] | permissive | dennisss/tansa | 7d8d6ab2ba2cb65d957d4a7faf998725bd5a33a7 | e6044af397f99b9b985ed56015e9e0be13d4b026 | refs/heads/master | 2021-05-01T00:24:55.496906 | 2018-01-12T16:21:35 | 2018-01-12T16:21:35 | 63,459,337 | 39 | 21 | MIT | 2020-04-29T22:49:14 | 2016-07-16T01:15:48 | C++ | UTF-8 | C++ | false | false | 2,686 | cpp | #include <tansa/control.h>
#include "pid.h"
namespace tansa {
// TODO: Integrate forward the position, velocity and time based on connection latency (so that commmands are accurate for the cmoment at which they are received)
PositionController::PositionController(Vehicle *v, bool directAttitudeControl) {
this->vehicle = v;
Vector3d windupMin = Point(-2.0, -2.0, -2.0),
windupMax = Point(2.0, 2.0, 2.0);
PID<PointDims>::State::Ptr s = std::make_shared<PID<PointDims>::State>();
pid = new PID<PointDims>(s);
pid->setWindupOutputLimit(windupMin, windupMax);
pid->setGains(
v->params.gains.p,
Vector3d(0, 0, v->params.gains.i.z()), // Only perform z integration for position control
//Point::Zero(), // Don't use
v->params.gains.d
);
hoverPid = new PID<PointDims>(s);
hoverPid->setWindupOutputLimit(windupMin, windupMax);
hoverPid->setGains(
v->params.gains.p,
v->params.gains.i,
v->params.gains.d
);
this->directAttitudeControl = directAttitudeControl;
}
void PositionController::track(Trajectory::Ptr traj) {
this->trajectory = traj;
hoverMode = false;
}
void PositionController::track(Point point) {
this->point = point;
hoverMode = true;
}
TrajectoryState PositionController::getTargetState(double t) {
if(hoverMode) {
TrajectoryState s;
s.position = point;
s.velocity = Point::Zero();
s.acceleration = Point::Zero();
return s;
}
return trajectory->evaluate(t);
}
void PositionController::control(double t) {
// Evaluate trajectory
TrajectoryState s = this->getTargetState(t);
ModelState cur = vehicle->arrival_state();
Vector3d eP = s.position - cur.position;
Vector3d eV = s.velocity - cur.velocity;
// At low altitudes, there's no room to rotate so we reduce the error effect
// TODO: Have a better way of doing this: essentially we want a trajectory straight up followed
if(s.position.z() < 0.1) {
double factor = 0.8;
for(unsigned i = 0; i < 2; i++) {
eP(i) *= factor;
eV(i) *= factor;
}
}
Vector3d out;
if(hoverMode) {
// Do nothing if hovering on the ground
if(point.z() < 0.1) {
vehicle->setpoint_zero();
return;
}
out = hoverPid->compute(eP, eV, 0.01);
}
else {
out = pid->compute(eP, eV, 0.01 /* TODO: Make this more dynamic */);
}
Vector3d a = out + s.acceleration;
double yaw_angle = DEFAULT_YAW_ANGLE;
if(directAttitudeControl) {
vehicle->lastControlInput = a;
a += Vector3d(0, 0, GRAVITY_MS);
Quaterniond att = Quaterniond::FromTwoVectors(Vector3d(0,0,1), a.normalized());
Quaterniond yaw( AngleAxisd(yaw_angle, Vector3d::UnitZ()) );
vehicle->setpoint_attitude(att*yaw, a.norm());
}
else {
vehicle->setpoint_accel(a, yaw_angle);
}
}
}
| [
"densht@gmail.com"
] | densht@gmail.com |
a6bce2a8fc664b3c82cd098c93abd722870f626d | e9d7b4f87a513685efc2d4eb980350caa514bea7 | /Project Speadsheets/CellInt.cpp | b9f7249851e79ee9782d59e18419cbfc27fdd012 | [] | no_license | ganchGra/OOP-Spreadsheet-project-2017 | b47a34b06d275580c4a4536c44b6cf3b27b01ad8 | 05975b3da700c140cd101f1b7d65eac32d75e9fc | refs/heads/master | 2021-01-22T06:20:03.969841 | 2017-09-03T20:14:34 | 2017-09-03T20:14:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include"stdafx.h"
/// Default constructor
CellInt::CellInt()
:m_number(NULL),m_stringNumber()
{}
/// Create new obj from assign value
CellInt::CellInt(int number,String StringNumber)
:m_number(number),m_stringNumber(StringNumber)
{}
/* Virtual function from the base class CellType */
CellType* CellInt::clone() const
{
return new CellInt(*this);
}
void CellInt::print(std::ostream& out) const
{
out << m_stringNumber;
}
unsigned CellInt::lenght() const
{
return m_stringNumber.lenght();
}
double CellInt::value() const
{
return m_number;
}
String CellInt::type() const
{
return "int";
}
String CellInt::stringCell() const
{
return m_stringNumber;
}
/* End virtual function from the base class CellType */
| [
"gratsiela.gancheva@gmail.com"
] | gratsiela.gancheva@gmail.com |
7bebbe065af118b3ff6e103418c0bd302a25c5ba | 9de3eb18280762690fddfc6d4e9e8da2ed159d00 | /PWGCF/FLOW/GF/AliAnalysisTaskPtCorr.h | 672cf0b0200d188cee2ba29ff4b1d4ee7da9da27 | [] | permissive | SiyuTang/AliPhysics | 72b62e80d834d2a8987f1b967fba8d947c4c8c01 | 9e3f3ec3650f1ae750e13c23c109fcb4ed51aa69 | refs/heads/master | 2022-06-28T12:50:47.943757 | 2022-06-09T15:41:00 | 2022-06-09T15:41:00 | 263,941,216 | 0 | 0 | BSD-3-Clause | 2020-05-14T14:41:28 | 2020-05-14T14:41:27 | null | UTF-8 | C++ | false | false | 5,450 | h | #ifndef PTCORRTASK_H
#define PTCORRTASK_H
#include "AliAnalysisTaskSE.h"
#include "complex.h"
#include "AliEventCuts.h"
#include "AliVEvent.h"
#include "AliMCEvent.h"
#include "AliGFWCuts.h"
#include "TString.h"
#include "TRandom.h"
#include "AliESDtrackCuts.h"
#include "AliProfileBS.h"
#include "AliCkContainer.h"
#include "AliPtContainer.h"
#include "TH3D.h"
class TList;
class TH1;
class TRandom;
class TAxis;
class AliVEvent;
using namespace std;
class AliAnalysisTaskPtCorr : public AliAnalysisTaskSE
{
public:
AliAnalysisTaskPtCorr();
AliAnalysisTaskPtCorr(const char *name, bool IsMC, TString ContSubfix);
virtual ~AliAnalysisTaskPtCorr();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual void Terminate(Option_t *option);
virtual void NotifyRun();
void SetSystFlag(Int_t newval) { if(!fGFWSelection) fGFWSelection = new AliGFWCuts(); fGFWSelection->SetupCuts(newval); };
void SetCentralityEstimator(TString newval) { if(fCentEst) delete fCentEst; fCentEst = new TString(newval); };
void SetV0MBins(int nBins, double* bins);
void SetMultiplicityBins(int nBins, double* bins);
void SetPtBins(int nBins, double *ptbins);
void SetContSubfix(TString newval) {if(fContSubfix) delete fContSubfix; fContSubfix = new TString(newval); if(!fContSubfix->IsNull()) fContSubfix->Prepend("_"); };
void SetMPar(int m) { mpar = m; }
void OverrideMC(bool ismc) { fIsMC = ismc; }
void OnTheFly(bool otf) { fOnTheFly = otf; }
void SetTrigger(unsigned int newval) {fTriggerType = newval; };
void SetEta(double eta) { fEta = eta; }
void SetEtaGap(double eta) { fEtaGap = eta; }
void TurnOffPileup(bool off) { fPileupOff = off; }
void SetPileupCut(double cut) { fPUcut = cut; }
void SetEventWeight(unsigned int weight) { fEventWeight = weight; }
void SetUseWeightsOne(bool use) { fUseWeightsOne = use; }
void SetUseRecNchForMc(bool userec) { fUseRecNchForMC = userec; }
void SetUseNch(bool usench) { fUseNch = usench; }
void SetEtaNch(double etanch) { fEtaNch = etanch; }
void SetNBootstrap(double nboot) { fNbootstrap = nboot; }
void SetUsePowerEff(double useeff) { fUsePowerEff = useeff; }
protected:
AliEventCuts fEventCuts;
private:
AliAnalysisTaskPtCorr(const AliAnalysisTaskPtCorr&);
AliAnalysisTaskPtCorr& operator=(const AliAnalysisTaskPtCorr&);
TString* fCentEst;
int fRunNo; //!
int fSystFlag;
TString* fContSubfix;
bool fIsMC;
AliMCEvent* fMCEvent; //!
TList* fCorrList; //!
TList* fQAList; //!
TList* fEfficiencyList;
TH1D** fEfficiencies;
TH2D** fPowerEfficiencies;
TString fWeightSubfix;
AliGFWCuts* fGFWSelection;
AliGFWCuts* fGFWnTrackSelection;
TAxis* fV0MAxis;
TAxis* fMultiAxis;
double* fMultiBins; //!
int fNMultiBins; //!
TAxis* fPtAxis;
double* fPtBins; //!
int fNPtBins; //!
double fEta;
double fEtaNch;
double fEtaGap;
double fPUcut;
TRandom* fRndm;
int fNbootstrap;
bool fUseWeightsOne;
bool fUseRecNchForMC;
bool fPileupOff;
bool fUseNch;
bool fUsePowerEff;
int mpar;
vector<vector<double>> wp;
vector<vector<double>> wpP;
vector<vector<double>> wpN;
unsigned int fEventWeight;
TH1D* fV0MMulti; //!
TProfile* pfmpt; //!
AliPtContainer* fck; //!
AliPtContainer* fskew; //!
AliPtContainer* fkur; //!
AliPtContainer* fp5; //!
AliPtContainer* fp6; //!
TH2D* fNchTrueVsRec; //!
TH2D* fV0MvsMult; //!
TH2D* fPtMoms; //!
TH2D* fPtDist; //!
TH3D* fPtDCA; //!
unsigned int fTriggerType;
bool fOnTheFly;
double fImpactParameter;
map<double,double> centralitymap;
bool AcceptAODTrack(AliAODTrack *tr, double *ltrackXYZ, const double &ptMin, const double &ptMax, double *vtxp);
bool AcceptAODTrack(AliAODTrack *mtr, double *ltrackXYZ, const double &ptMin, const double &ptMax, double *vtxp, int &nTot);
bool AcceptAODEvent(AliAODEvent *ev, double *vtxXYZ);
bool AcceptMCEvent(AliVEvent* inev);
bool CheckTrigger(Double_t lCent);
double getCentrality();
void FillPtCorr(AliAODEvent* ev, const double &l_Cent, double *vtxXYZ);
void FillWPCounter(vector<vector<double>> &inarr, double w, double p);
void FillWPCounter(vector<vector<double>> &inarr, vector<double> w, double p);
int GetNTracks(AliAODEvent* ev, const Double_t &ptmin, const Double_t &ptmax, Double_t *vtxp);
double *GetBinsFromAxis(TAxis *inax);
ClassDef(AliAnalysisTaskPtCorr,1);
};
#endif | [
"emil.gorm.nielsen@cern.ch"
] | emil.gorm.nielsen@cern.ch |
7bdebc0d17a404a6eca18cda632042b6415d9556 | b3f0037b6483e6be647cd8b64d06befc3f6ce8c4 | /codeforces/1216/D.cpp | 1b0c8c975a9a3beeb3bc2fa7b5d3931675263fc6 | [] | no_license | arnab000/Problem-Solving | 7b658ac19b7e8ec926e6f689f989637926b8089b | b407c0d7382961c50edd59fed9ca746b057a90fd | refs/heads/master | 2023-04-05T14:40:50.634735 | 2021-04-21T01:45:00 | 2021-04-23T01:05:39 | 328,335,023 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,k;
cin>>n;
long long maxi=0,gcd=0,ans=0;
vector<long long>sura;
for(int i=0;i<n;i++)
{
cin>>k;
sura.push_back(k);
maxi=max(k,maxi);
}
gcd=0;
for(int i=0;i<n;i++)
{
ans+=maxi-sura[i];
gcd=__gcd(gcd,maxi-sura[i]);
}
cout<<ans/gcd<<" "<<gcd<<endl;
}
| [
"arnab.saintjoseph@gmail.com"
] | arnab.saintjoseph@gmail.com |
e31673583f9cb8dcde5894a165eea6a7bd0fd214 | f6c2191a68804ea2edba644e64e5c256a6cff91e | /SpaceShooter/Classes/SpaceShooter.cpp | 92dd8be4c5fea5786ff4919146ba353ae6eba278 | [] | no_license | 07haicloud/MiniGame | af2c4139526d0ffe89d65fe4b1ed7ef7b70ee935 | 93a01aea5cab2cfee0df8c78a7f81eaf7e498c11 | refs/heads/master | 2020-06-09T10:34:01.829877 | 2019-07-08T09:16:00 | 2019-07-08T09:16:00 | 193,423,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,162 | cpp | #include "SpaceShooter.h"
#include "ResourceManager.h"
#include "HelloWorldScene.h"
int countFrame = 0;
SpaceShooter::SpaceShooter(Scene * scene)
{
Init(); //create SpaceShip
scene->addChild(this->m_sprite,10);
for (register int i = 0; i < 10; i++)
{
m_bullets.push_back(new Bullet(scene));
}
}
SpaceShooter::~SpaceShooter()
{
}
void SpaceShooter::Init()
{
//Create SpaceShip
auto screenSize = Director::getInstance()->getVisibleSize();
this->m_sprite = ResourceManager::GetInstance()->GetSpriteById('4');
this->m_sprite->removeFromParent();
this->m_sprite->setAnchorPoint(Vec2(0.5, 0.5));
//this->m_sprite->setScale(1.5);
this->m_sprite->setPosition(Vec2(screenSize.width / 2, screenSize.height / 5));
Vector<SpriteFrame*> animFrames;
animFrames.pushBack(SpriteFrame::create("res/Sprites/1.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/2.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/3.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/4.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/5.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/6.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/7.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
animFrames.pushBack(SpriteFrame::create("res/Sprites/8.png", Rect(0, 0, m_sprite->getContentSize().width, m_sprite->getContentSize().height)));
auto animation = Animation::createWithSpriteFrames(animFrames, 0.02f);
auto animate = Animate::create(animation);
//m_sprite->runAction(RepeatForever::create(animate));
}
void SpaceShooter::Update(float deltaTime)
{
if (countFrame == 10)
{
Shoot();
countFrame = 1;
}
else {
countFrame++;
}
if (countFrame != 0)
{
register list <MyObject*> ::iterator it;
for (it = m_bullets.begin(); it != m_bullets.end(); it++)
{
(*it)->Update(deltaTime);
}
}
}
void SpaceShooter::Shoot()
{
list <MyObject*> ::iterator it;
for (it = m_bullets.begin(); it != m_bullets.end(); it++)
{
if (!(*it)->getState())
{
(*it)->setState(true);
(*it)->setPos(Vec2(this->m_sprite->getPositionX(), m_sprite->getPositionY()+ m_sprite->getContentSize().height/2));
break;
}
}
}
void SpaceShooter::Collision(vector<Rock*> m_rocks)
{
register list <MyObject*> ::iterator bullet;
register vector<Rock*>::iterator rock;
Rect recRock, recSpaceship;
//Collision between rocks and bullets
for (rock = m_rocks.begin(); rock != m_rocks.end(); rock++)
{
recRock = (*rock)->getSprite()->getBoundingBox();
if ((*rock)->getState())
{
for (bullet = m_bullets.begin(); bullet != m_bullets.end(); bullet++)
{
Rect recBullet = (*bullet)->getSprite()->getBoundingBox();
if (recBullet.intersectsRect(recRock))
{
(*bullet)->setState(false);
(*rock)->setState(false);
//(*rock)->setPos(Vec2(20, -200));
break;
}
}
}
}
recSpaceship = this->getSprite()->getBoundingBox();
for (rock = m_rocks.begin(); rock != m_rocks.end(); rock++)
{
recRock = (*rock)->getSprite()->getBoundingBox();
if ((*rock)->getState()==true)
{
if (recSpaceship.intersectsRect(recRock))
{
Vec2 m = m_sprite->getPosition();
Vec2 r = (*rock)->getSprite()->getPosition();
//(*rock)->setState(true);
(*rock)->getSprite()->setScale(1);
//m_sprite->setScale(3);
//auto da = Sprite::create("");
bool v = (*rock)->getSprite()->isVisible();
//float w = Director::getInstance()->getVisibleSize().width;
//Director::getInstance()->replaceScene(HelloWorld::createScene());
Director::getInstance()->replaceScene(GameOverScene::createScene());
break;
}
}
}
}
| [
"="
] | = |
c390b0acc115d6603e9481eb5238b2ae2cf6b298 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/ExponentialHeightFog.gen.cpp | 4278576b0efc887b508b276d4a08ec119c9419b9 | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 9,432 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "Engine/Classes/Engine/ExponentialHeightFog.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeExponentialHeightFog() {}
// Cross Module References
ENGINE_API UClass* Z_Construct_UClass_AExponentialHeightFog_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_AExponentialHeightFog();
ENGINE_API UClass* Z_Construct_UClass_AInfo();
UPackage* Z_Construct_UPackage__Script_Engine();
ENGINE_API UClass* Z_Construct_UClass_UExponentialHeightFogComponent_NoRegister();
// End Cross Module References
DEFINE_FUNCTION(AExponentialHeightFog::execOnRep_bEnabled)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->OnRep_bEnabled();
P_NATIVE_END;
}
void AExponentialHeightFog::StaticRegisterNativesAExponentialHeightFog()
{
UClass* Class = AExponentialHeightFog::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "OnRep_bEnabled", &AExponentialHeightFog::execOnRep_bEnabled },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics::Function_MetaDataParams[] = {
{ "Comment", "/** Replication Notification Callbacks */" },
{ "ModuleRelativePath", "Classes/Engine/ExponentialHeightFog.h" },
{ "ToolTip", "Replication Notification Callbacks" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AExponentialHeightFog, nullptr, "OnRep_bEnabled", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00020400, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_AExponentialHeightFog_NoRegister()
{
return AExponentialHeightFog::StaticClass();
}
struct Z_Construct_UClass_AExponentialHeightFog_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bEnabled_MetaData[];
#endif
static void NewProp_bEnabled_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bEnabled;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Component_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Component;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AExponentialHeightFog_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_AInfo,
(UObject* (*)())Z_Construct_UPackage__Script_Engine,
};
const FClassFunctionLinkInfo Z_Construct_UClass_AExponentialHeightFog_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_AExponentialHeightFog_OnRep_bEnabled, "OnRep_bEnabled" }, // 2726140967
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AExponentialHeightFog_Statics::Class_MetaDataParams[] = {
{ "ClassGroupNames", "Fog" },
{ "Comment", "/**\n * Implements an Actor for exponential height fog.\n */" },
{ "HideCategories", "Input Collision" },
{ "IncludePath", "Engine/ExponentialHeightFog.h" },
{ "ModuleRelativePath", "Classes/Engine/ExponentialHeightFog.h" },
{ "ShowCategories", "Input|MouseInput Input|TouchInput" },
{ "ToolTip", "Implements an Actor for exponential height fog." },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled_MetaData[] = {
{ "Comment", "/** replicated copy of ExponentialHeightFogComponent's bEnabled property */" },
{ "ModuleRelativePath", "Classes/Engine/ExponentialHeightFog.h" },
{ "ToolTip", "replicated copy of ExponentialHeightFogComponent's bEnabled property" },
};
#endif
void Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled_SetBit(void* Obj)
{
((AExponentialHeightFog*)Obj)->bEnabled = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled = { "bEnabled", "OnRep_bEnabled", (EPropertyFlags)0x0010000100000020, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(AExponentialHeightFog), &Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled_SetBit, METADATA_PARAMS(Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_Component_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "ExponentialHeightFog" },
{ "Comment", "/** @todo document */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Classes/Engine/ExponentialHeightFog.h" },
{ "ToolTip", "@todo document" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_Component = { "Component", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AExponentialHeightFog, Component), Z_Construct_UClass_UExponentialHeightFogComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_Component_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_Component_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AExponentialHeightFog_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_bEnabled,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AExponentialHeightFog_Statics::NewProp_Component,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AExponentialHeightFog_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AExponentialHeightFog>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AExponentialHeightFog_Statics::ClassParams = {
&AExponentialHeightFog::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_AExponentialHeightFog_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_AExponentialHeightFog_Statics::PropPointers),
0,
0x008800A4u,
METADATA_PARAMS(Z_Construct_UClass_AExponentialHeightFog_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AExponentialHeightFog_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AExponentialHeightFog()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AExponentialHeightFog_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AExponentialHeightFog, 2878483389);
template<> ENGINE_API UClass* StaticClass<AExponentialHeightFog>()
{
return AExponentialHeightFog::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_AExponentialHeightFog(Z_Construct_UClass_AExponentialHeightFog, &AExponentialHeightFog::StaticClass, TEXT("/Script/Engine"), TEXT("AExponentialHeightFog"), false, nullptr, nullptr, nullptr);
void AExponentialHeightFog::ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const
{
static const FName Name_bEnabled(TEXT("bEnabled"));
const bool bIsValid = true
&& Name_bEnabled == ClassReps[(int32)ENetFields_Private::bEnabled].Property->GetFName();
checkf(bIsValid, TEXT("UHT Generated Rep Indices do not match runtime populated Rep Indices for properties in AExponentialHeightFog"));
}
DEFINE_VTABLE_PTR_HELPER_CTOR(AExponentialHeightFog);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
40fd9f90c658d300302277d245803d9e03d7e6b2 | bddb40149f9028297d9b4f3f6b77514cadac9bca | /Source/Utilities/RakNet/Source/RakClient.cpp | f6c0f1ddd6bfd2353de8ca59580e1c93a5f32238 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | JamesTerm/GremlinGames | 91d61a50d0926b8e95cad21053ba2cf6c3316003 | fd0366af007bff8cffe4941b4bb5bb16948a8c66 | refs/heads/master | 2021-10-20T21:15:53.121770 | 2019-03-01T15:45:58 | 2019-03-01T15:45:58 | 173,261,435 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,142 | cpp | /// \file
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#include "RakClient.h"
#include "PacketEnumerations.h"
#include "GetTime.h"
#ifdef _MSC_VER
#pragma warning( push )
#endif
// Constructor
RakClient::RakClient()
{
unsigned i;
for ( i = 0; i < 32; i++ )
otherClients[ i ].isActive = false;
nextSeedUpdate = 0;
}
// Destructor
RakClient::~RakClient()
{}
#ifdef _MSC_VER
#pragma warning( disable : 4100 ) // warning C4100: 'depreciated' : unreferenced formal parameter
#endif
bool RakClient::Connect( const char* host, unsigned short serverPort, unsigned short clientPort, unsigned int depreciated, int threadSleepTimer )
{
RakPeer::Disconnect( 100 );
RakPeer::Initialize( 1, clientPort, threadSleepTimer );
if ( host[ 0 ] < '0' || host[ 0 ] > '2' )
{
#if !defined(_COMPATIBILITY_1)
host = ( char* ) SocketLayer::Instance()->DomainNameToIP( host );
#else
return false;
#endif
}
unsigned i;
for ( i = 0; i < 32; i++ )
{
otherClients[ i ].isActive = false;
otherClients[ i ].playerId = UNASSIGNED_PLAYER_ID;
otherClients[ i ].staticData.Reset();
}
// ignore depreciated. A pointless variable
return RakPeer::Connect( host, serverPort, ( char* ) password.GetData(), password.GetNumberOfBytesUsed() );
}
void RakClient::Disconnect( unsigned int blockDuration, unsigned char orderingChannel )
{
RakPeer::Disconnect( blockDuration, orderingChannel );
}
void RakClient::InitializeSecurity( const char *privKeyP, const char *privKeyQ )
{
RakPeer::InitializeSecurity( privKeyP, privKeyQ, 0, 0 );
}
void RakClient::SetPassword( const char *_password )
{
if ( _password == 0 || _password[ 0 ] == 0 )
password.Reset();
else
{
password.Reset();
password.Write( _password, ( int ) strlen( _password ) + 1 );
}
}
bool RakClient::HasPassword( void ) const
{
return password.GetNumberOfBytesUsed() > 0;
}
bool RakClient::Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel )
{
if ( remoteSystemList == 0 )
return false;
return RakPeer::Send( data, length, priority, reliability, orderingChannel, remoteSystemList[ 0 ].playerId, false );
}
bool RakClient::Send( RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel )
{
if ( remoteSystemList == 0 )
return false;
return RakPeer::Send( bitStream, priority, reliability, orderingChannel, remoteSystemList[ 0 ].playerId, false );
}
Packet* RakClient::Receive( void )
{
Packet * packet = RakPeer::Receive();
// Intercept specific client / server feature packets
if ( packet )
{
RakNet::BitStream bitStream( packet->data, packet->length, false );
int i;
if ( packet->data[ 0 ] == ID_CONNECTION_REQUEST_ACCEPTED )
{
// ConnectionAcceptStruct cas;
// cas.Deserialize(bitStream);
// unsigned short remotePort;
// PlayerID externalID;
PlayerIndex playerIndex;
RakNet::BitStream inBitStream(packet->data, packet->length, false);
inBitStream.IgnoreBits(8); // ID_CONNECTION_REQUEST_ACCEPTED
inBitStream.IgnoreBits(8 * sizeof(unsigned short)); //inBitStream.Read(remotePort);
inBitStream.IgnoreBits(8 * sizeof(unsigned int)); //inBitStream.Read(externalID.binaryAddress);
inBitStream.IgnoreBits(8 * sizeof(unsigned short)); //inBitStream.Read(externalID.port);
inBitStream.Read(playerIndex);
localPlayerIndex = playerIndex;
packet->playerIndex = playerIndex;
}
else if (
packet->data[ 0 ] == ID_REMOTE_NEW_INCOMING_CONNECTION ||
packet->data[ 0 ] == ID_REMOTE_EXISTING_CONNECTION ||
packet->data[ 0 ] == ID_REMOTE_DISCONNECTION_NOTIFICATION ||
packet->data[ 0 ] == ID_REMOTE_CONNECTION_LOST )
{
bitStream.IgnoreBits( 8 ); // Ignore identifier
bitStream.Read( packet->playerId.binaryAddress );
bitStream.Read( packet->playerId.port );
if ( bitStream.Read( ( unsigned short& ) packet->playerIndex ) == false )
{
DeallocatePacket( packet );
return 0;
}
if ( packet->data[ 0 ] == ID_REMOTE_DISCONNECTION_NOTIFICATION ||
packet->data[ 0 ] == ID_REMOTE_CONNECTION_LOST )
{
i = GetOtherClientIndexByPlayerID( packet->playerId );
if ( i >= 0 )
otherClients[ i ].isActive = false;
}
}
else if ( packet->data[ 0 ] == ID_REMOTE_STATIC_DATA )
{
bitStream.IgnoreBits( 8 ); // Ignore identifier
bitStream.Read( packet->playerId.binaryAddress );
bitStream.Read( packet->playerId.port );
bitStream.Read( packet->playerIndex ); // ADDED BY KURI
i = GetOtherClientIndexByPlayerID( packet->playerId );
if ( i < 0 )
i = GetFreeOtherClientIndex();
if ( i >= 0 )
{
otherClients[ i ].playerId = packet->playerId;
otherClients[ i ].isActive = true;
otherClients[ i ].staticData.Reset();
// The static data is what is left over in the stream
otherClients[ i ].staticData.Write( ( char* ) bitStream.GetData() + BITS_TO_BYTES( bitStream.GetReadOffset() ), bitStream.GetNumberOfBytesUsed() - BITS_TO_BYTES( bitStream.GetReadOffset() ) );
}
}
else if ( packet->data[ 0 ] == ID_BROADCAST_PINGS )
{
PlayerID playerId;
int index;
bitStream.IgnoreBits( 8 ); // Ignore identifier
for ( i = 0; i < 32; i++ )
{
if ( bitStream.Read( playerId.binaryAddress ) == false )
break; // No remaining data!
bitStream.Read( playerId.port );
index = GetOtherClientIndexByPlayerID( playerId );
if ( index >= 0 )
bitStream.Read( otherClients[ index ].ping );
else
{
index = GetFreeOtherClientIndex();
if ( index >= 0 )
{
otherClients[ index ].isActive = true;
bitStream.Read( otherClients[ index ].ping );
otherClients[ index ].playerId = playerId;
otherClients[ index ].staticData.Reset();
}
else
bitStream.IgnoreBits( sizeof( short ) * 8 );
}
}
DeallocatePacket( packet );
return 0;
}
else
if ( packet->data[ 0 ] == ID_TIMESTAMP &&
packet->length == sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned int) )
{
RakNet::BitStream inBitStream(packet->data, packet->length, false);
RakNetTime timeStamp;
unsigned char typeId;
unsigned int in_seed;
unsigned int in_nextSeed;
inBitStream.IgnoreBits(8); // ID_TIMESTAMP
inBitStream.Read(timeStamp);
inBitStream.Read(typeId); // ID_SET_RANDOM_NUMBER_SEED ?
// Check to see if this is a user TIMESTAMP message which
// accidentally has length SetRandomNumberSeedStruct_Size
if ( typeId != ID_SET_RANDOM_NUMBER_SEED )
return packet;
inBitStream.Read(in_seed);
inBitStream.Read(in_nextSeed);
seed = in_seed;
nextSeed = in_nextSeed;
nextSeedUpdate = timeStamp + 9000; // Seeds are updated every 9 seconds
DeallocatePacket( packet );
return 0;
}
}
return packet;
}
void RakClient::DeallocatePacket( Packet *packet )
{
RakPeer::DeallocatePacket( packet );
}
void RakClient::PingServer( void )
{
if ( remoteSystemList == 0 )
return ;
RakPeer::Ping( remoteSystemList[ 0 ].playerId );
}
void RakClient::PingServer( const char* host, unsigned short serverPort, unsigned short clientPort, bool onlyReplyOnAcceptingConnections )
{
RakPeer::Initialize( 1, clientPort, 0 );
RakPeer::Ping( host, serverPort, onlyReplyOnAcceptingConnections );
}
int RakClient::GetAveragePing( void )
{
if ( remoteSystemList == 0 )
return -1;
return RakPeer::GetAveragePing( remoteSystemList[ 0 ].playerId );
}
int RakClient::GetLastPing( void ) const
{
if ( remoteSystemList == 0 )
return -1;
return RakPeer::GetLastPing( remoteSystemList[ 0 ].playerId );
}
int RakClient::GetLowestPing( void ) const
{
if ( remoteSystemList == 0 )
return -1;
return RakPeer::GetLowestPing( remoteSystemList[ 0 ].playerId );
}
int RakClient::GetPlayerPing( const PlayerID playerId )
{
int i;
for ( i = 0; i < 32; i++ )
if ( otherClients[ i ].playerId == playerId )
return otherClients[ i ].ping;
return -1;
}
void RakClient::StartOccasionalPing( void )
{
RakPeer::SetOccasionalPing( true );
}
void RakClient::StopOccasionalPing( void )
{
RakPeer::SetOccasionalPing( false );
}
bool RakClient::IsConnected( void ) const
{
unsigned short numberOfSystems;
RakPeer::GetConnectionList( 0, &numberOfSystems );
return numberOfSystems == 1;
}
unsigned int RakClient::GetSynchronizedRandomInteger( void ) const
{
if ( RakNet::GetTime() > nextSeedUpdate )
return nextSeed;
else
return seed;
}
bool RakClient::GenerateCompressionLayer( unsigned int inputFrequencyTable[ 256 ], bool inputLayer )
{
return RakPeer::GenerateCompressionLayer( inputFrequencyTable, inputLayer );
}
bool RakClient::DeleteCompressionLayer( bool inputLayer )
{
return RakPeer::DeleteCompressionLayer( inputLayer );
}
void RakClient::RegisterAsRemoteProcedureCall( char* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) )
{
RakPeer::RegisterAsRemoteProcedureCall( uniqueID, functionPointer );
}
void RakClient::RegisterClassMemberRPC( char* uniqueID, void *functionPointer )
{
RakPeer::RegisterClassMemberRPC( uniqueID, functionPointer );
}
void RakClient::UnregisterAsRemoteProcedureCall( char* uniqueID )
{
RakPeer::UnregisterAsRemoteProcedureCall( uniqueID );
}
bool RakClient::RPC( char* uniqueID, const char *data, unsigned int bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, bool shiftTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )
{
if ( remoteSystemList == 0 )
return false;
return RakPeer::RPC( uniqueID, data, bitLength, priority, reliability, orderingChannel, remoteSystemList[ 0 ].playerId, false, shiftTimestamp, networkID, replyFromTarget );
}
bool RakClient::RPC( char* uniqueID, RakNet::BitStream *parameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, bool shiftTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )
{
if ( remoteSystemList == 0 )
return false;
return RakPeer::RPC( uniqueID, parameters, priority, reliability, orderingChannel, remoteSystemList[ 0 ].playerId, false, shiftTimestamp, networkID, replyFromTarget );
}
void RakClient::SetTrackFrequencyTable( bool b )
{
RakPeer::SetCompileFrequencyTable( b );
}
bool RakClient::GetSendFrequencyTable( unsigned int outputFrequencyTable[ 256 ] )
{
return RakPeer::GetOutgoingFrequencyTable( outputFrequencyTable );
}
float RakClient::GetCompressionRatio( void ) const
{
return RakPeer::GetCompressionRatio();
}
float RakClient::GetDecompressionRatio( void ) const
{
return RakPeer::GetDecompressionRatio();
}
void RakClient::AttachPlugin( PluginInterface *messageHandler )
{
RakPeer::AttachPlugin(messageHandler);
}
void RakClient::DetachPlugin( PluginInterface *messageHandler )
{
RakPeer::DetachPlugin(messageHandler);
}
RakNet::BitStream * RakClient::GetStaticServerData( void )
{
if ( remoteSystemList == 0 )
return 0;
return RakPeer::GetRemoteStaticData( remoteSystemList[ 0 ].playerId );
}
void RakClient::SetStaticServerData( const char *data, const int length )
{
if ( remoteSystemList == 0 )
return ;
RakPeer::SetRemoteStaticData( remoteSystemList[ 0 ].playerId, data, length );
}
RakNet::BitStream * RakClient::GetStaticClientData( const PlayerID playerId )
{
int i;
if ( playerId == UNASSIGNED_PLAYER_ID )
{
return & localStaticData;
}
else
{
i = GetOtherClientIndexByPlayerID( playerId );
if ( i >= 0 )
{
return & ( otherClients[ i ].staticData );
}
}
return 0;
}
void RakClient::SetStaticClientData( const PlayerID playerId, const char *data, const int length )
{
int i;
if ( playerId == UNASSIGNED_PLAYER_ID )
{
localStaticData.Reset();
localStaticData.Write( data, length );
}
else
{
i = GetOtherClientIndexByPlayerID( playerId );
if ( i >= 0 )
{
otherClients[ i ].staticData.Reset();
otherClients[ i ].staticData.Write( data, length );
}
else
RakPeer::SetRemoteStaticData( playerId, data, length );
}
}
void RakClient::SendStaticClientDataToServer( void )
{
if ( remoteSystemList == 0 )
return ;
RakPeer::SendStaticData( remoteSystemList[ 0 ].playerId );
}
PlayerID RakClient::GetServerID( void ) const
{
if ( remoteSystemList == 0 )
return UNASSIGNED_PLAYER_ID;
return remoteSystemList[ 0 ].playerId;
}
PlayerID RakClient::GetPlayerID( void ) const
{
if ( remoteSystemList == 0 )
return UNASSIGNED_PLAYER_ID;
// GetExternalID is more accurate because it reflects our external IP and port to the server.
// GetInternalID only matches the parameters we passed
PlayerID myID = RakPeer::GetExternalID( remoteSystemList[ 0 ].playerId );
if ( myID == UNASSIGNED_PLAYER_ID )
return RakPeer::GetInternalID();
else
return myID;
}
PlayerID RakClient::GetInternalID( void ) const
{
return RakPeer::GetInternalID();
}
const char* RakClient::PlayerIDToDottedIP( const PlayerID playerId ) const
{
return RakPeer::PlayerIDToDottedIP( playerId );
}
void RakClient::PushBackPacket( Packet *packet, bool pushAtHead )
{
RakPeer::PushBackPacket(packet, pushAtHead);
}
void RakClient::SetRouterInterface( RouterInterface *routerInterface )
{
RakPeer::SetRouterInterface(routerInterface);
}
void RakClient::RemoveRouterInterface( RouterInterface *routerInterface )
{
RakPeer::RemoveRouterInterface(routerInterface);
}
void RakClient::SetTimeoutTime( RakNetTime timeMS )
{
RakPeer::SetTimeoutTime( timeMS, GetServerID() );
}
bool RakClient::SetMTUSize( int size )
{
return RakPeer::SetMTUSize( size );
}
int RakClient::GetMTUSize( void ) const
{
return RakPeer::GetMTUSize();
}
void RakClient::AllowConnectionResponseIPMigration( bool allow )
{
RakPeer::AllowConnectionResponseIPMigration( allow );
}
void RakClient::AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength )
{
RakPeer::AdvertiseSystem( host, remotePort, data, dataLength );
}
RakNetStatisticsStruct* const RakClient::GetStatistics( void )
{
return RakPeer::GetStatistics( remoteSystemList[ 0 ].playerId );
}
void RakClient::ApplyNetworkSimulator( double maxSendBPS, unsigned short minExtraPing, unsigned short extraPingVariance)
{
RakPeer::ApplyNetworkSimulator( maxSendBPS, minExtraPing, extraPingVariance );
}
bool RakClient::IsNetworkSimulatorActive( void )
{
return RakPeer::IsNetworkSimulatorActive();
}
int RakClient::GetOtherClientIndexByPlayerID( const PlayerID playerId )
{
unsigned i;
for ( i = 0; i < 32; i++ )
{
if ( otherClients[ i ].playerId == playerId )
return i;
}
return -1;
}
int RakClient::GetFreeOtherClientIndex( void )
{
unsigned i;
for ( i = 0; i < 32; i++ )
{
if ( otherClients[ i ].isActive == false )
return i;
}
return -1;
}
PlayerIndex RakClient::GetPlayerIndex( void )
{
return localPlayerIndex;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
| [
"james@e2c3bcc0-b32a-0410-840c-db224dcf21cb"
] | james@e2c3bcc0-b32a-0410-840c-db224dcf21cb |
fdefc9a415877c5f1725e781a034d3d2ea8b473b | 6a151d774c8230cf2a6a04cd6566c5aa813f9a3a | /Codeforces/Restricted RPS CF 1245B.cpp | 63bd34f1b154003f5e09ed126af89480f980aa68 | [] | no_license | RakibulRanak/Solved-ACM-problems | fdc5b39bdbe1bcc06f95c2a77478534362dca257 | 7d28d4da7bb01989f741228c4039a96ab307a8a6 | refs/heads/master | 2021-07-01T09:50:02.039776 | 2020-10-11T20:46:28 | 2020-10-11T20:46:28 | 168,976,930 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int r, p, s;
cin >> r >> p >> s;
string x;
cin >> x;
int vic = 0;
char vec[n];
memset(vec,'x',sizeof(vec));
for (int i = 0; i < n; i++)
{
if(x[i]=='R')
{
if(p>0)
{
p--;
vec[i]='p';
vic++;
}
}
else if(x[i]=='S')
{
if(r>0)
{
r--;
vec[i]='r';
vic++;
}
}
else
{
if(s>0)
{
s--;
vec[i]='s';
vic++;
}
}
}
//cout<<vic<<endl;
int temp = (n + 1) / 2;
if (vic >= temp)
{
cout << "YES" << endl;
for (int i = 0; i < n; i++)
{
char c = toupper(vec[i]);
if(c=='X')
{
if(p>0)
{
c='P';
p--;
}
else if(s>0)
{
c='S';
s--;
}
else
{
c='R';
r--;
}
}
cout << c;
}
cout << endl;
}
else{
cout << "NO" << endl;
}
}
return 0;
} | [
"rakibulhasanranak1@gmail.com"
] | rakibulhasanranak1@gmail.com |
c48c507489688e00b921bce2cea3180886077d15 | cbbdaa9c4af7bd0b3c7283ae4dd6b11942cefe49 | /ConsoleApplication2/ConsoleApplication2/Peoson.h | 7a8be97dd0a25de7de197448dae86b060bef217e | [] | no_license | misc-song/PerCSharp | d145815d8b02354a3dd216d547dca066552e9712 | 956a85fb4ada24aef463d82d0dcc3f1586c5a836 | refs/heads/master | 2021-01-11T17:06:48.922432 | 2017-11-05T06:51:26 | 2017-11-05T06:51:26 | 79,721,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | h | #pragma once
#include"Calculator.h"
#include<string>
using namespace std;
class Peoson
{
public:
int Age;
string Name;
char sex;
void Say(string);
void Use(Calculator *c);
public:
Peoson();
~Peoson();
};
| [
"wqshj@126.com"
] | wqshj@126.com |
9ad67d6d947f045ff483dcb55cc99617fadc11f5 | 090243cf699213f32f870baf2902eb4211f825d6 | /CDOJ/Contest/题解报告/专题一/何柱2014060105005/B/B.cpp | d134777e4a33264f4cbedbf6f391c8a5b3b3af34 | [] | no_license | zhu-he/ACM-Source | 0d4d0ac0668b569846b12297e7ed4abbb1c16571 | 02e3322e50336063d0d2dad37b2761ecb3d4e380 | refs/heads/master | 2021-06-07T18:27:19.702607 | 2016-07-10T09:20:48 | 2016-07-10T09:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,548 | cpp | #include <cstdio>
#include <cstring>
#define lchild rt << 1, l, m
#define rchild rt << 1 | 1, m + 1, r
int n;
long long lazy[600001];
long long tree[600001];
void pushup(int rt)
{
tree[rt] = tree[rt << 1] + tree[rt << 1 | 1];
}
void pushdown(int rt, int len)
{
if (lazy[rt])
{
tree[rt << 1] += lazy[rt] * (len - (len >> 1));
lazy[rt << 1] += lazy[rt];
tree[rt << 1 | 1] += lazy[rt] * (len >> 1);
lazy[rt << 1 | 1] += lazy[rt];
lazy[rt] = 0;
}
}
long long query(int L, int R, int rt = 1, int l = 1, int r = n)
{
if (L <= l && r <= R)
{
return tree[rt];
}
pushdown(rt, r - l + 1);
int m = (l + r) >> 1;
long long ret = 0;
if (L <= m)
{
ret += query(L, R, lchild);
}
if (R > m)
{
ret += query(L, R, rchild);
}
return ret;
}
void update(int L, int R, long long delta, int rt = 1, int l = 1, int r = n)
{
if (L <= l && r <= R)
{
tree[rt] += delta * (r - l + 1);
lazy[rt] += delta;
return;
}
pushdown(rt, r - l + 1);
int m = (l + r) >> 1;
if (L <= m)
{
update(L, R, delta, lchild);
}
if (R > m)
{
update(L, R, delta, rchild);
}
pushup(rt);
}
void build(int rt = 1, int l = 1, int r = n)
{
if (l == r)
{
scanf("%lld", &tree[rt]);
return;
}
int m = (l + r) >> 1;
build(lchild);
build(rchild);
pushup(rt);
}
int main()
{
scanf("%d", &n);
memset(lazy, 0, sizeof lazy);
memset(tree, 0, sizeof tree);
build();
int m;
scanf("%d", &m);
while (m--)
{
int l, r;
long long v;
scanf("%d %d %lld", &l, &r, &v);
update(l, r, v);
printf("%lld\n", query(l, r));
}
return 0;
}
| [
"841815229@qq.com"
] | 841815229@qq.com |
46e4386f5b49fd5ec08af9c32d4faefe2d93cde5 | e70b8c9a6f71492db211d6ac8bf90860ca30a76e | /Bipartite Matching/15007번_Easter Eggs.cpp | 2bb53c84dd923657154e92e84aaca79f4efbc26c | [] | no_license | orihehe/BOJ | b289031abf5736c7f9d933fa52a889d73de39614 | 6c78d53f8ec1a9251f252f913d5f8e3a6fdb14fc | refs/heads/master | 2020-04-04T09:56:25.511131 | 2019-11-04T13:19:17 | 2019-11-04T13:19:17 | 155,836,795 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | cpp | /*
BOJ 15007 - Easter Eggs
https://www.acmicpc.net/problem/15007
모든 빨간, 파란 점 쌍의 거리를 구해두고 정렬한다.
이분탐색으로 거리를 구해주는데, 그 거리보다 작은 두 점은 둘 다 선택될 수 없다.
따라서 최소 버택스 커버(이분매칭) 문제로 바꿀 수 있다.
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#define pii pair<int,int>
using namespace std;
/* 🐣🐥 */
struct info {
double dist;
int a, b;
bool operator<(const info &op) const {
return dist < op.dist;
}
};
pii arr[251];
vector<info> vvv;
int cnt, B[251];
pii fn[1001];
bool visited[1001];
vector<int> vec[1001];
bool dfs(int cur) {
visited[cur] = true;
for (int v : vec[cur]) {
if (B[v] == -1 || !visited[B[v]] && dfs(B[v])) {
B[v] = cur;
return true;
}
}
return false;
}
int main() {
int n, b, r, x, y;
double ans;
scanf("%d %d %d", &n, &b, &r);
for (int i = 0; i < b; i++) {
scanf("%d %d", &arr[i].first, &arr[i].second);
}
for (int i = 0; i < r; i++) {
scanf("%d %d", &x, &y);
for (int j = 0; j < b; j++) {
int xx = arr[j].first - x;
int yy = arr[j].second - y;
double dd = sqrt(xx*xx + yy * yy);
vvv.push_back({ dd,j,i });
}
}
sort(vvv.begin(), vvv.end());
int sz = vvv.size();
double l = 0, rr = 800000000, mid;
for (int k = 0; k < 60; k++) {
mid = (l + rr) / 2;
int tmp = 0;
memset(B, -1, sizeof(B));
for (int i = 0; i < sz; i++) {
if (vvv[i].dist >= mid) break;
vec[vvv[i].a].push_back(vvv[i].b);
}
for (int i = 0; i < b; i++) {
memset(visited, false, sizeof(visited));
if (dfs(i)) tmp++;
}
for (int i = 0; i < b; i++) {
vec[i].clear();
}
if (r + b - tmp<n) {
rr = mid;
}
else {
ans = mid;
l = mid;
}
}
printf("%lf", ans);
return 0;
} | [
"38060133+orihehe@users.noreply.github.com"
] | 38060133+orihehe@users.noreply.github.com |
e49ea7b67ff061e5eff5e24841ffb30b7763349d | ac12bf1e31089a42049e570fa631045a5b66370b | /SPOJ/DP/PARTY.cpp | 50c6f3bbf1574b46e78c8e989161fcb398985bb1 | [] | no_license | PyAgni/CompetitiveProgramming | fa647463ed0fd2cc92ebcce17ac0d743639e8969 | 358b47230c94b62bc693008c986e11cf6a5b9ada | refs/heads/master | 2022-12-02T02:38:04.413958 | 2020-07-27T14:52:06 | 2020-07-27T14:52:06 | 265,951,097 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,785 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef std::vector<ll> vec;
typedef std::vector<ld> vecld;
typedef std::vector< std::vector<ll> > vecvec;
typedef std::pair<ll, ll> pr;
typedef std::vector< pr > vpr;
#define tin ll t;cin>>t;while(t--)
#define fio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define endl "\n"
#define deb(x) cerr<< #x << " " << x << endl
#define sz(a) (ll)((a).size())
#define pb emplace_back
#define trvect(c,i) for(vector<ll>::iterator i = (c).begin(); i != (c).end(); i++)
#define trset(c,i) for(set<ll>::iterator i = (c).begin(); i != (c).end(); i++)
#define trmap(c,i) for(map<ll,ll>::iterator i = (c).begin(); i != (c).end(); i++)
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repp(i,a,b) for(ll i=a;i<=b;i++)
#define present(c,x) ((c).find(x) != (c).end())
#define all(x) x.begin(), x.end()
#define rall(v) v.rbegin(),v.rend()
#define rsort(v) sort(all(v),greater<int>())
#define mst(x) memset(x, 0, sizeof(x))
#define ff first
#define ss second
#define mp make_pair
#define sq(a) (a)*(a)
#define cube(a) (a)*(a)*(a)
#define cnti(x) (__builtin_popcount(x)) //number of set bits in x
#define N 100005
#define pi 2*acos(0.0)
const int mod = 1000000007;
// --------------------------- Inputs ---------------------------------------------- //
template<typename... T>
void read(T&... args){
((cin>>args), ...);
}
template <typename T , typename T0>
void read(pair< T , T0 > &p){
cin >> p.ff >>p.ss;
}
template <typename T>
void read(vector< T > &oneD){
for(ll i=0;i<oneD.size();i++){
read(oneD[i]);
}
}
template <typename T>
void read(T oneD[] , int n){
for(ll i=0;i<n;i++){
read(oneD[i]);
}
}
// --------------------------- Outputs --------------------------------------------- //
template<typename... T>
void write(T... args){
((cout<<args<<" "), ...);
cout<<endl;
}
template <typename T , typename T0>
void write(pair< T , T0 > &p){
write(p.ff);
write(p.ss);
cout << endl;
}
template <typename T>
void write(vector< T > &oneD){
for(ll i=0;i<oneD.size();i++){
cout<<oneD[i]<<" ";
}
cout<<endl;
}
template <typename T ,typename T0>
void write(vector< pair< T, T0 > > &oneD){
for(ll i=0;i<oneD.size();i++){
write(oneD[i].ff,oneD[i].ss);
}
}
template <typename T>
void write(T oneD[] ,int n){
for(ll i=0;i<n;i++){
cout<<oneD[i]<<" ";
}
cout << endl;
}
template <typename T , typename T0>
void write(map< T , T0 > &mpp){
for(auto it : mpp){
write(it.ff);
cout << ": ";
write(it.ss);
cout << "\n";
}
cout<<endl;
}
// -------------------------------------------------------------------------------- //
ll qpow (ll n, ll m) {
ll ret = 1;
while (m) {
if (m & 1) ret = ret * n % mod;
n = n * n % mod;
m >>= 1;
}
return ret;
}
ll inv (ll a) {
return qpow(a, mod - 2);
}
// ------------------------------------------------------------------------------- //
void solve(ll *fun,ll *cost,ll parties,ll budget){
ll dp[parties+1][budget+1];
// memset(dp,-1,sizeof(dp));
rep(i,0,parties+1){
rep(j,0,budget+1){
if(i==0||j==0)
dp[i][j]=0;
if(cost[i-1]<=j)
dp[i][j] = max(fun[i-1]+dp[i-1][j-cost[i-1]],dp[i-1][j]);
else
dp[i][j] = dp[i-1][j];
}
}
ll min_budget=INT_MAX;
rep(i,0,budget+1){
if(dp[parties][i]==dp[parties][budget])
min_budget=min(min_budget,i);
}
// rep(i,0,parties+1){
// rep(j,0,budget+1){
// cout<<dp[i][j]<<" ";
// }
// cout<<endl;
// }
cout<<min_budget<<" "<<dp[parties][budget]<<endl;
}
int main(){
while(1)
{
ll budget,parties;
cin>>budget>>parties;
if(budget==0 && parties==0)
return 0;
ll cost[parties],fun[parties];
rep(i,0,parties) cin>>cost[i]>>fun[i];
solve(fun,cost,parties,budget);
}
}
| [
"bhattacharyya.agni@gmail.com"
] | bhattacharyya.agni@gmail.com |
76110645cc6236fcd62558d1f2c071d5c046c9a7 | 3db023edb0af1dcf8a1da83434d219c3a96362ba | /windows_nt_3_5_source_code/NT-782/PRIVATE/UTILS/ULIB/SRC/LIST.CXX | cb4678a4dc74d802b21fd50a90b3c334553c76d6 | [] | no_license | xiaoqgao/windows_nt_3_5_source_code | de30e9b95856bc09469d4008d76191f94379c884 | d2894c9125ff1c14028435ed1b21164f6b2b871a | refs/heads/master | 2022-12-23T17:58:33.768209 | 2020-09-28T20:20:18 | 2020-09-28T20:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,798 | cxx | #include <pch.cxx>
#define _ULIB_MEMBER_
#include "ulib.hxx"
#include "list.hxx"
#include "listit.hxx"
DEFINE_EXPORTED_CONSTRUCTOR( LIST, SEQUENTIAL_CONTAINER, ULIB_EXPORT );
VOID
LIST::Construct(
)
/*++
Routine Description:
This routine initializes the object to a default state.
Arguments:
None.
Return Value:
None.
--*/
{
_head = NULL;
_tail = NULL;
_count = 0;
}
VOID
LIST::Destroy(
)
/*++
Routine Description:
This routine returns the object to a default state.
Arguments:
None.
Return Value:
None.
--*/
{
_head = NULL;
_tail = NULL;
_count = 0;
}
ULIB_EXPORT
LIST::~LIST(
)
/*++
Routine Description:
Destructor for LIST.
Arguments:
None.
Return Value:
None.
--*/
{
Destroy();
}
ULIB_EXPORT
BOOLEAN
LIST::Initialize(
)
/*++
Routine Description:
This routine initializes the object to a valid initial state.
Arguments:
None.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
Destroy();
if (!_mem_block_mgr.Initialize(sizeof(OBJECT_LIST_NODE))) {
Destroy();
return FALSE;
}
return TRUE;
}
ULONG
LIST::QueryMemberCount(
) CONST
/*++
Routine Description:
This routine computes the number of members in the list.
Arguments:
None.
Return Value:
The number of members in the list.
--*/
{
return _count;
}
ULIB_EXPORT
BOOLEAN
LIST::Put(
IN POBJECT Member
)
/*++
Routine Description:
This routine adds a new member to the end of the list.
Arguments:
Member - Supplies the element to add to the list.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
if (!_tail) {
if (!(_head = _tail = (POBJECT_LIST_NODE) _mem_block_mgr.Alloc())) {
return FALSE;
}
_head->next = _head->prev = NULL;
_head->data = Member;
_count++;
return TRUE;
}
if (!(_tail->next = (POBJECT_LIST_NODE) _mem_block_mgr.Alloc())) {
return FALSE;
}
_tail->next->prev = _tail;
_tail = _tail->next;
_tail->next = NULL;
_tail->data = Member;
_count++;
return TRUE;
}
POBJECT
LIST::Remove(
IN OUT PITERATOR Position
)
/*++
Routine Description:
This routine removes the element at the specified position from the
list. The iterator is left pointing at the following element in
the list.
Arguments:
Position - Supplies a pointer to the element to remove.
Return Value:
A pointer to the element removed.
--*/
{
POBJECT_LIST_NODE p;
PLIST_ITERATOR piter;
POBJECT pobj;
DbgAssert(LIST_ITERATOR::Cast(Position));
if (!(piter = (PLIST_ITERATOR) Position) || !(p = piter->_current)) {
return NULL;
}
if (p->next) {
p->next->prev = p->prev;
}
if (p->prev) {
p->prev->next = p->next;
}
if (_head == p) {
_head = p->next;
}
if (_tail == p) {
_tail = p->prev;
}
piter->_current = p->next;
pobj = p->data;
_mem_block_mgr.Free(p);
_count--;
return pobj;
}
ULIB_EXPORT
PITERATOR
LIST::QueryIterator(
) CONST
/*++
Routine Description:
This routine returns an iterator for this list.
Arguments:
None.
Return Value:
A valid iterator.
--*/
{
PLIST_ITERATOR p;
if (!(p = NEW LIST_ITERATOR)) {
return NULL;
}
p->Initialize(this);
return p;
}
ULIB_EXPORT
BOOLEAN
LIST::Insert(
IN OUT POBJECT Member,
IN OUT PITERATOR Position
)
/*++
Routine Description:
This routine inserts a new element before the specified position.
The 'Position' continues to point to the same element.
Arguments:
Member - Supplies the element to insert.
Position - Supplies the point at which to insert this member.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
POBJECT_LIST_NODE p, current;
DbgAssert(LIST_ITERATOR::Cast(Position));
current = ((PLIST_ITERATOR) Position)->_current;
if (!current) {
return Put(Member);
}
if (!(p = (POBJECT_LIST_NODE) _mem_block_mgr.Alloc())) {
return FALSE;
}
_count++;
p->data = Member;
if (current == _head) {
_head = p;
}
p->next = current;
p->prev = current->prev;
current->prev = p;
if (p->prev) {
p->prev->next = p;
}
return TRUE;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
65192da4befd6dd0162001755333f0f15823029b | 401c864dbe6fbdc0f2b74bda9ac02e0e43159cc3 | /Arduinosy/libraries/_ESP82666_Libs/SPI_esp8266/SPI.h | 5cf49e5ba348f8c8a7bf62d870a1e59ede90b14f | [] | no_license | cytrus77/Arduinosy | 9cc400027444f73255743b46cd291e4f9d49c031 | 4cbb6a69d15105b343ce145f1270ae2847252989 | refs/heads/master | 2020-12-10T16:56:16.017422 | 2018-07-01T10:00:51 | 2018-07-01T10:00:51 | 34,057,272 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,337 | h | /*
SPI.h - SPI library for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _SPI_H_INCLUDED
#define _SPI_H_INCLUDED
#include <Arduino.h>
#include <stdlib.h>
#define SPI_HAS_TRANSACTION
// This defines are not representing the real Divider of the ESP8266
// the Defines match to an AVR Arduino on 16MHz for better compatibility
#if F_CPU == 80000000L
#define SPI_CLOCK_DIV2 0x00101001 //8 MHz
#define SPI_CLOCK_DIV4 0x00241001 //4 MHz
#define SPI_CLOCK_DIV8 0x004c1001 //2 MHz
#define SPI_CLOCK_DIV16 0x009c1001 //1 MHz
#define SPI_CLOCK_DIV32 0x013c1001 //500 KHz
#define SPI_CLOCK_DIV64 0x027c1001 //250 KHz
#define SPI_CLOCK_DIV128 0x04fc1001 //125 KHz
#else
#define SPI_CLOCK_DIV2 0x00241001 //8 MHz
#define SPI_CLOCK_DIV4 0x004c1001 //4 MHz
#define SPI_CLOCK_DIV8 0x009c1001 //2 MHz
#define SPI_CLOCK_DIV16 0x013c1001 //1 MHz
#define SPI_CLOCK_DIV32 0x027c1001 //500 KHz
#define SPI_CLOCK_DIV64 0x04fc1001 //250 KHz
#endif
const uint8_t SPI_MODE0 = 0x00; ///< CPOL: 0 CPHA: 0
const uint8_t SPI_MODE1 = 0x01; ///< CPOL: 0 CPHA: 1
const uint8_t SPI_MODE2 = 0x10; ///< CPOL: 1 CPHA: 0
const uint8_t SPI_MODE3 = 0x11; ///< CPOL: 1 CPHA: 1
class SPISettings {
public:
SPISettings() :_clock(1000000), _bitOrder(LSBFIRST), _dataMode(SPI_MODE0){}
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) :_clock(clock), _bitOrder(bitOrder), _dataMode(dataMode){}
uint32_t _clock;
uint8_t _bitOrder;
uint8_t _dataMode;
};
class SPIClass {
public:
SPIClass();
void begin();
void end();
void setHwCs(bool use);
void setBitOrder(uint8_t bitOrder);
void setDataMode(uint8_t dataMode);
void setFrequency(uint32_t freq);
void setClockDivider(uint32_t clockDiv);
void beginTransaction(SPISettings settings);
uint8_t transfer(uint8_t data);
uint16_t transfer16(uint16_t data);
void write(uint8_t data);
void write16(uint16_t data);
void write16(uint16_t data, bool msb);
void write32(uint32_t data);
void write32(uint32_t data, bool msb);
void writeBytes(uint8_t * data, uint32_t size);
void writePattern(uint8_t * data, uint8_t size, uint32_t repeat);
void transferBytes(uint8_t * out, uint8_t * in, uint32_t size);
void endTransaction(void);
private:
bool useHwCs;
void writeBytes_(uint8_t * data, uint8_t size);
void writePattern_(uint8_t * data, uint8_t size, uint8_t repeat);
void transferBytes_(uint8_t * out, uint8_t * in, uint8_t size);
inline void setDataBits(uint16_t bits);
};
extern SPIClass SPI;
#endif | [
"cytrus77@gmail.com"
] | cytrus77@gmail.com |
a6acb63d1e82bcfa30ef132f562aa51a58d1c8e6 | dae883ee037ad0680e8aff4936f4880be98acaee | /tools/clang/lib/Sema/SemaExpr.cpp | 73baf1a660f81cddc0608f228712d2048558f692 | [
"NCSA"
] | permissive | frankroeder/llvm_mpi_checks | 25af07d680f825fe2f0871abcd8658ffedcec4a7 | d1f6385f3739bd746329276822d42efb6385941c | refs/heads/master | 2021-07-01T00:50:27.308673 | 2017-09-21T20:30:07 | 2017-09-21T20:30:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613,448 | cpp | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for expressions.
//
//===----------------------------------------------------------------------===//
#include "TreeTransform.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExprOpenMP.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/Designator.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaFixItUtils.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "llvm/Support/ConvertUTF.h"
using namespace clang;
using namespace sema;
/// \brief Determine whether the use of this declaration is valid, without
/// emitting diagnostics.
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
// See if this is an auto-typed variable whose initializer we are parsing.
if (ParsingInitForAutoVars.count(D))
return false;
// See if this is a deleted function.
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->isDeleted())
return false;
// If the function has a deduced return type, and we can't deduce it,
// then we can't use it either.
if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
return false;
}
// See if this function is unavailable.
if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
return false;
return true;
}
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
// Warn if this is used but marked unused.
if (const auto *A = D->getAttr<UnusedAttr>()) {
// [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
// should diagnose them.
if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
if (DC && !DC->hasAttr<UnusedAttr>())
S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
}
}
}
static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
if (!OMD)
return false;
const ObjCInterfaceDecl *OID = OMD->getClassInterface();
if (!OID)
return false;
for (const ObjCCategoryDecl *Cat : OID->visible_categories())
if (ObjCMethodDecl *CatMeth =
Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
if (!CatMeth->hasAttr<AvailabilityAttr>())
return true;
return false;
}
AvailabilityResult
Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
AvailabilityResult Result = D->getAvailability(Message);
// For typedefs, if the typedef declaration appears available look
// to the underlying type to see if it is more restrictive.
while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
if (Result == AR_Available) {
if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
D = TT->getDecl();
Result = D->getAvailability(Message);
continue;
}
}
break;
}
// Forward class declarations get their attributes from their definition.
if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
if (IDecl->getDefinition()) {
D = IDecl->getDefinition();
Result = D->getAvailability(Message);
}
}
if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
if (Result == AR_Available) {
const DeclContext *DC = ECD->getDeclContext();
if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Result = TheEnumDecl->getAvailability(Message);
}
if (Result == AR_NotYetIntroduced) {
// Don't do this for enums, they can't be redeclared.
if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
return AR_Available;
bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
// Objective-C method declarations in categories are not modelled as
// redeclarations, so manually look for a redeclaration in a category
// if necessary.
if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
Warn = false;
// In general, D will point to the most recent redeclaration. However,
// for `@class A;` decls, this isn't true -- manually go through the
// redecl chain in that case.
if (Warn && isa<ObjCInterfaceDecl>(D))
for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
Redecl = Redecl->getPreviousDecl())
if (!Redecl->hasAttr<AvailabilityAttr>() ||
Redecl->getAttr<AvailabilityAttr>()->isInherited())
Warn = false;
return Warn ? AR_NotYetIntroduced : AR_Available;
}
return Result;
}
static void
DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess) {
std::string Message;
// See if this declaration is unavailable, deprecated, or partial.
if (AvailabilityResult Result =
S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
return;
}
const ObjCPropertyDecl *ObjCPDecl = nullptr;
if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
if (PDeclResult == Result)
ObjCPDecl = PD;
}
}
S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
ObjCPDecl, ObjCPropertyAccess);
}
}
/// \brief Emit a note explaining that this function is deleted.
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
assert(Decl->isDeleted());
CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
if (Method && Method->isDeleted() && Method->isDefaulted()) {
// If the method was explicitly defaulted, point at that declaration.
if (!Method->isImplicit())
Diag(Decl->getLocation(), diag::note_implicitly_deleted);
// Try to diagnose why this special member function was implicitly
// deleted. This might fail, if that reason no longer applies.
CXXSpecialMember CSM = getSpecialMember(Method);
if (CSM != CXXInvalid)
ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
return;
}
auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
if (Ctor && Ctor->isInheritingConstructor())
return NoteDeletedInheritingConstructor(Ctor);
Diag(Decl->getLocation(), diag::note_availability_specified_here)
<< Decl << true;
}
/// \brief Determine whether a FunctionDecl was ever declared with an
/// explicit storage class.
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
for (auto I : D->redecls()) {
if (I->getStorageClass() != SC_None)
return true;
}
return false;
}
/// \brief Check whether we're in an extern inline function and referring to a
/// variable or function with internal linkage (C11 6.7.4p3).
///
/// This is only a warning because we used to silently accept this code, but
/// in many cases it will not behave correctly. This is not enabled in C++ mode
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
/// and so while there may still be user mistakes, most of the time we can't
/// prove that there are errors.
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
const NamedDecl *D,
SourceLocation Loc) {
// This is disabled under C++; there are too many ways for this to fire in
// contexts where the warning is a false positive, or where it is technically
// correct but benign.
if (S.getLangOpts().CPlusPlus)
return;
// Check if this is an inlined function or method.
FunctionDecl *Current = S.getCurFunctionDecl();
if (!Current)
return;
if (!Current->isInlined())
return;
if (!Current->isExternallyVisible())
return;
// Check if the decl has internal linkage.
if (D->getFormalLinkage() != InternalLinkage)
return;
// Downgrade from ExtWarn to Extension if
// (1) the supposedly external inline function is in the main file,
// and probably won't be included anywhere else.
// (2) the thing we're referencing is a pure function.
// (3) the thing we're referencing is another inline function.
// This last can give us false negatives, but it's better than warning on
// wrappers for simple C library functions.
const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
if (!DowngradeWarning && UsedFn)
DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
: diag::ext_internal_in_extern_inline)
<< /*IsVar=*/!UsedFn << D;
S.MaybeSuggestAddingStaticToDecl(Current);
S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
<< D;
}
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
const FunctionDecl *First = Cur->getFirstDecl();
// Suggest "static" on the function, if possible.
if (!hasAnyExplicitStorageClass(First)) {
SourceLocation DeclBegin = First->getSourceRange().getBegin();
Diag(DeclBegin, diag::note_convert_inline_to_static)
<< Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
}
}
/// \brief Determine whether the use of this declaration is valid, and
/// emit any corresponding diagnostics.
///
/// This routine diagnoses various problems with referencing
/// declarations that can occur when using a declaration. For example,
/// it might warn if a deprecated or unavailable declaration is being
/// used, or produce an error (and return true) if a C++0x deleted
/// function is being used.
///
/// \returns true if there was an error (this declaration cannot be
/// referenced), false otherwise.
///
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess) {
if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
// If there were any diagnostics suppressed by template argument deduction,
// emit them now.
auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
if (Pos != SuppressedDiagnostics.end()) {
for (const PartialDiagnosticAt &Suppressed : Pos->second)
Diag(Suppressed.first, Suppressed.second);
// Clear out the list of suppressed diagnostics, so that we don't emit
// them again for this specialization. However, we don't obsolete this
// entry from the table, because we want to avoid ever emitting these
// diagnostics again.
Pos->second.clear();
}
// C++ [basic.start.main]p3:
// The function 'main' shall not be used within a program.
if (cast<FunctionDecl>(D)->isMain())
Diag(Loc, diag::ext_main_used);
}
// See if this is an auto-typed variable whose initializer we are parsing.
if (ParsingInitForAutoVars.count(D)) {
if (isa<BindingDecl>(D)) {
Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
<< D->getDeclName();
} else {
Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
<< D->getDeclName() << cast<VarDecl>(D)->getType();
}
return true;
}
// See if this is a deleted function.
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->isDeleted()) {
auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
if (Ctor && Ctor->isInheritingConstructor())
Diag(Loc, diag::err_deleted_inherited_ctor_use)
<< Ctor->getParent()
<< Ctor->getInheritedConstructor().getConstructor()->getParent();
else
Diag(Loc, diag::err_deleted_function_use);
NoteDeletedFunction(FD);
return true;
}
// If the function has a deduced return type, and we can't deduce it,
// then we can't use it either.
if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
DeduceReturnType(FD, Loc))
return true;
if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
return true;
if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
return true;
}
// [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
// Only the variables omp_in and omp_out are allowed in the combiner.
// Only the variables omp_priv and omp_orig are allowed in the
// initializer-clause.
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
isa<VarDecl>(D)) {
Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
<< getCurFunction()->HasOMPDeclareReductionCombiner;
Diag(D->getLocation(), diag::note_entity_declared_at) << D;
return true;
}
DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
ObjCPropertyAccess);
DiagnoseUnusedOfDecl(*this, D, Loc);
diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
return false;
}
/// \brief Retrieve the message suffix that should be added to a
/// diagnostic complaining about the given function being deleted or
/// unavailable.
std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
std::string Message;
if (FD->getAvailability(&Message))
return ": " + Message;
return std::string();
}
/// DiagnoseSentinelCalls - This routine checks whether a call or
/// message-send is to a declaration with the sentinel attribute, and
/// if so, it checks that the requirements of the sentinel are
/// satisfied.
void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args) {
const SentinelAttr *attr = D->getAttr<SentinelAttr>();
if (!attr)
return;
// The number of formal parameters of the declaration.
unsigned numFormalParams;
// The kind of declaration. This is also an index into a %select in
// the diagnostic.
enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
numFormalParams = MD->param_size();
calleeType = CT_Method;
} else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
numFormalParams = FD->param_size();
calleeType = CT_Function;
} else if (isa<VarDecl>(D)) {
QualType type = cast<ValueDecl>(D)->getType();
const FunctionType *fn = nullptr;
if (const PointerType *ptr = type->getAs<PointerType>()) {
fn = ptr->getPointeeType()->getAs<FunctionType>();
if (!fn) return;
calleeType = CT_Function;
} else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
fn = ptr->getPointeeType()->castAs<FunctionType>();
calleeType = CT_Block;
} else {
return;
}
if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
numFormalParams = proto->getNumParams();
} else {
numFormalParams = 0;
}
} else {
return;
}
// "nullPos" is the number of formal parameters at the end which
// effectively count as part of the variadic arguments. This is
// useful if you would prefer to not have *any* formal parameters,
// but the language forces you to have at least one.
unsigned nullPos = attr->getNullPos();
assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
// The number of arguments which should follow the sentinel.
unsigned numArgsAfterSentinel = attr->getSentinel();
// If there aren't enough arguments for all the formal parameters,
// the sentinel, and the args after the sentinel, complain.
if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
return;
}
// Otherwise, find the sentinel expression.
Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
if (!sentinelExpr) return;
if (sentinelExpr->isValueDependent()) return;
if (Context.isSentinelNullExpr(sentinelExpr)) return;
// Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
// or 'NULL' if those are actually defined in the context. Only use
// 'nil' for ObjC methods, where it's much more likely that the
// variadic arguments form a list of object pointers.
SourceLocation MissingNilLoc
= getLocForEndOfToken(sentinelExpr->getLocEnd());
std::string NullValue;
if (calleeType == CT_Method && PP.isMacroDefined("nil"))
NullValue = "nil";
else if (getLangOpts().CPlusPlus11)
NullValue = "nullptr";
else if (PP.isMacroDefined("NULL"))
NullValue = "NULL";
else
NullValue = "(void*) 0";
if (MissingNilLoc.isInvalid())
Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
else
Diag(MissingNilLoc, diag::warn_missing_sentinel)
<< int(calleeType)
<< FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
}
SourceRange Sema::getExprRange(Expr *E) const {
return E ? E->getSourceRange() : SourceRange();
}
//===----------------------------------------------------------------------===//
// Standard Promotions and Conversions
//===----------------------------------------------------------------------===//
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
// Handle any placeholder expressions which made it here.
if (E->getType()->isPlaceholderType()) {
ExprResult result = CheckPlaceholderExpr(E);
if (result.isInvalid()) return ExprError();
E = result.get();
}
QualType Ty = E->getType();
assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
if (Ty->isFunctionType()) {
// If we are here, we are not calling a function but taking
// its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
if (getLangOpts().OpenCL) {
if (Diagnose)
Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
return ExprError();
}
if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
return ExprError();
E = ImpCastExprToType(E, Context.getPointerType(Ty),
CK_FunctionToPointerDecay).get();
} else if (Ty->isArrayType()) {
// In C90 mode, arrays only promote to pointers if the array expression is
// an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
// type 'array of type' is converted to an expression that has type 'pointer
// to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
// that has type 'array of type' ...". The relevant change is "an lvalue"
// (C90) to "an expression" (C99).
//
// C++ 4.2p1:
// An lvalue or rvalue of type "array of N T" or "array of unknown bound of
// T" can be converted to an rvalue of type "pointer to T".
//
if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
CK_ArrayToPointerDecay).get();
}
return E;
}
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
// Check to see if we are dereferencing a null pointer. If so,
// and if not volatile-qualified, this is undefined behavior that the
// optimizer will delete, so warn about it. People sometimes try to use this
// to get a deterministic trap and are surprised by clang's behavior. This
// only handles the pattern "*null", which is a very syntactic check.
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
if (UO->getOpcode() == UO_Deref &&
UO->getSubExpr()->IgnoreParenCasts()->
isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
!UO->getType().isVolatileQualified()) {
S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
S.PDiag(diag::warn_indirection_through_null)
<< UO->getSubExpr()->getSourceRange());
S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
S.PDiag(diag::note_indirection_through_null));
}
}
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
SourceLocation AssignLoc,
const Expr* RHS) {
const ObjCIvarDecl *IV = OIRE->getDecl();
if (!IV)
return;
DeclarationName MemberName = IV->getDeclName();
IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
if (!Member || !Member->isStr("isa"))
return;
const Expr *Base = OIRE->getBase();
QualType BaseType = Base->getType();
if (OIRE->isArrow())
BaseType = BaseType->getPointeeType();
if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
ObjCInterfaceDecl *ClassDeclared = nullptr;
ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
if (!ClassDeclared->getSuperClass()
&& (*ClassDeclared->ivar_begin()) == IV) {
if (RHS) {
NamedDecl *ObjectSetClass =
S.LookupSingleName(S.TUScope,
&S.Context.Idents.get("object_setClass"),
SourceLocation(), S.LookupOrdinaryName);
if (ObjectSetClass) {
SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
AssignLoc), ",") <<
FixItHint::CreateInsertion(RHSLocEnd, ")");
}
else
S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
} else {
NamedDecl *ObjectGetClass =
S.LookupSingleName(S.TUScope,
&S.Context.Idents.get("object_getClass"),
SourceLocation(), S.LookupOrdinaryName);
if (ObjectGetClass)
S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
FixItHint::CreateReplacement(
SourceRange(OIRE->getOpLoc(),
OIRE->getLocEnd()), ")");
else
S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
}
S.Diag(IV->getLocation(), diag::note_ivar_decl);
}
}
}
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
// Handle any placeholder expressions which made it here.
if (E->getType()->isPlaceholderType()) {
ExprResult result = CheckPlaceholderExpr(E);
if (result.isInvalid()) return ExprError();
E = result.get();
}
// C++ [conv.lval]p1:
// A glvalue of a non-function, non-array type T can be
// converted to a prvalue.
if (!E->isGLValue()) return E;
QualType T = E->getType();
assert(!T.isNull() && "r-value conversion on typeless expression?");
// We don't want to throw lvalue-to-rvalue casts on top of
// expressions of certain types in C++.
if (getLangOpts().CPlusPlus &&
(E->getType() == Context.OverloadTy ||
T->isDependentType() ||
T->isRecordType()))
return E;
// The C standard is actually really unclear on this point, and
// DR106 tells us what the result should be but not why. It's
// generally best to say that void types just doesn't undergo
// lvalue-to-rvalue at all. Note that expressions of unqualified
// 'void' type are never l-values, but qualified void can be.
if (T->isVoidType())
return E;
// OpenCL usually rejects direct accesses to values of 'half' type.
if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
T->isHalfType()) {
Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
<< 0 << T;
return ExprError();
}
CheckForNullPointerDereference(*this, E);
if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
&Context.Idents.get("object_getClass"),
SourceLocation(), LookupOrdinaryName);
if (ObjectGetClass)
Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
FixItHint::CreateReplacement(
SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
else
Diag(E->getExprLoc(), diag::warn_objc_isa_use);
}
else if (const ObjCIvarRefExpr *OIRE =
dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
// C++ [conv.lval]p1:
// [...] If T is a non-class type, the type of the prvalue is the
// cv-unqualified version of T. Otherwise, the type of the
// rvalue is T.
//
// C99 6.3.2.1p2:
// If the lvalue has qualified type, the value has the unqualified
// version of the type of the lvalue; otherwise, the value has the
// type of the lvalue.
if (T.hasQualifiers())
T = T.getUnqualifiedType();
// Under the MS ABI, lock down the inheritance model now.
if (T->isMemberPointerType() &&
Context.getTargetInfo().getCXXABI().isMicrosoft())
(void)isCompleteType(E->getExprLoc(), T);
UpdateMarkingForLValueToRValue(E);
// Loading a __weak object implicitly retains the value, so we need a cleanup to
// balance that.
if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
Cleanup.setExprNeedsCleanups(true);
ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
nullptr, VK_RValue);
// C11 6.3.2.1p2:
// ... if the lvalue has atomic type, the value has the non-atomic version
// of the type of the lvalue ...
if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
T = Atomic->getValueType().getUnqualifiedType();
Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
nullptr, VK_RValue);
}
return Res;
}
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
if (Res.isInvalid())
return ExprError();
Res = DefaultLvalueConversion(Res.get());
if (Res.isInvalid())
return ExprError();
return Res;
}
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
QualType Ty = E->getType();
ExprResult Res = E;
// Only do implicit cast for a function type, but not for a pointer
// to function type.
if (Ty->isFunctionType()) {
Res = ImpCastExprToType(E, Context.getPointerType(Ty),
CK_FunctionToPointerDecay).get();
if (Res.isInvalid())
return ExprError();
}
Res = DefaultLvalueConversion(Res.get());
if (Res.isInvalid())
return ExprError();
return Res.get();
}
/// UsualUnaryConversions - Performs various conversions that are common to most
/// operators (C99 6.3). The conversions of array and function types are
/// sometimes suppressed. For example, the array->pointer conversion doesn't
/// apply if the array is an argument to the sizeof or address (&) operators.
/// In these instances, this routine should *not* be called.
ExprResult Sema::UsualUnaryConversions(Expr *E) {
// First, convert to an r-value.
ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
if (Res.isInvalid())
return ExprError();
E = Res.get();
QualType Ty = E->getType();
assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
// Half FP have to be promoted to float unless it is natively supported
if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
// Try to perform integral promotions if the object has a theoretically
// promotable type.
if (Ty->isIntegralOrUnscopedEnumerationType()) {
// C99 6.3.1.1p2:
//
// The following may be used in an expression wherever an int or
// unsigned int may be used:
// - an object or expression with an integer type whose integer
// conversion rank is less than or equal to the rank of int
// and unsigned int.
// - A bit-field of type _Bool, int, signed int, or unsigned int.
//
// If an int can represent all values of the original type, the
// value is converted to an int; otherwise, it is converted to an
// unsigned int. These are called the integer promotions. All
// other types are unchanged by the integer promotions.
QualType PTy = Context.isPromotableBitField(E);
if (!PTy.isNull()) {
E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
return E;
}
if (Ty->isPromotableIntegerType()) {
QualType PT = Context.getPromotedIntegerType(Ty);
E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
return E;
}
}
return E;
}
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
/// do not have a prototype. Arguments that have type float or __fp16
/// are promoted to double. All other argument types are converted by
/// UsualUnaryConversions().
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
QualType Ty = E->getType();
assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
ExprResult Res = UsualUnaryConversions(E);
if (Res.isInvalid())
return ExprError();
E = Res.get();
// If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
// double.
const BuiltinType *BTy = Ty->getAs<BuiltinType>();
if (BTy && (BTy->getKind() == BuiltinType::Half ||
BTy->getKind() == BuiltinType::Float)) {
if (getLangOpts().OpenCL &&
!getOpenCLOptions().isEnabled("cl_khr_fp64")) {
if (BTy->getKind() == BuiltinType::Half) {
E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
}
} else {
E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
}
}
// C++ performs lvalue-to-rvalue conversion as a default argument
// promotion, even on class types, but note:
// C++11 [conv.lval]p2:
// When an lvalue-to-rvalue conversion occurs in an unevaluated
// operand or a subexpression thereof the value contained in the
// referenced object is not accessed. Otherwise, if the glvalue
// has a class type, the conversion copy-initializes a temporary
// of type T from the glvalue and the result of the conversion
// is a prvalue for the temporary.
// FIXME: add some way to gate this entire thing for correctness in
// potentially potentially evaluated contexts.
if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
ExprResult Temp = PerformCopyInitialization(
InitializedEntity::InitializeTemporary(E->getType()),
E->getExprLoc(), E);
if (Temp.isInvalid())
return ExprError();
E = Temp.get();
}
return E;
}
/// Determine the degree of POD-ness for an expression.
/// Incomplete types are considered POD, since this check can be performed
/// when we're in an unevaluated context.
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
if (Ty->isIncompleteType()) {
// C++11 [expr.call]p7:
// After these conversions, if the argument does not have arithmetic,
// enumeration, pointer, pointer to member, or class type, the program
// is ill-formed.
//
// Since we've already performed array-to-pointer and function-to-pointer
// decay, the only such type in C++ is cv void. This also handles
// initializer lists as variadic arguments.
if (Ty->isVoidType())
return VAK_Invalid;
if (Ty->isObjCObjectType())
return VAK_Invalid;
return VAK_Valid;
}
if (Ty.isCXX98PODType(Context))
return VAK_Valid;
// C++11 [expr.call]p7:
// Passing a potentially-evaluated argument of class type (Clause 9)
// having a non-trivial copy constructor, a non-trivial move constructor,
// or a non-trivial destructor, with no corresponding parameter,
// is conditionally-supported with implementation-defined semantics.
if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
if (!Record->hasNonTrivialCopyConstructor() &&
!Record->hasNonTrivialMoveConstructor() &&
!Record->hasNonTrivialDestructor())
return VAK_ValidInCXX11;
if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
return VAK_Valid;
if (Ty->isObjCObjectType())
return VAK_Invalid;
if (getLangOpts().MSVCCompat)
return VAK_MSVCUndefined;
// FIXME: In C++11, these cases are conditionally-supported, meaning we're
// permitted to reject them. We should consider doing so.
return VAK_Undefined;
}
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
// Don't allow one to pass an Objective-C interface to a vararg.
const QualType &Ty = E->getType();
VarArgKind VAK = isValidVarArgType(Ty);
// Complain about passing non-POD types through varargs.
switch (VAK) {
case VAK_ValidInCXX11:
DiagRuntimeBehavior(
E->getLocStart(), nullptr,
PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
<< Ty << CT);
// Fall through.
case VAK_Valid:
if (Ty->isRecordType()) {
// This is unlikely to be what the user intended. If the class has a
// 'c_str' member function, the user probably meant to call that.
DiagRuntimeBehavior(E->getLocStart(), nullptr,
PDiag(diag::warn_pass_class_arg_to_vararg)
<< Ty << CT << hasCStrMethod(E) << ".c_str()");
}
break;
case VAK_Undefined:
case VAK_MSVCUndefined:
DiagRuntimeBehavior(
E->getLocStart(), nullptr,
PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
<< getLangOpts().CPlusPlus11 << Ty << CT);
break;
case VAK_Invalid:
if (Ty->isObjCObjectType())
DiagRuntimeBehavior(
E->getLocStart(), nullptr,
PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
<< Ty << CT);
else
Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
<< isa<InitListExpr>(E) << Ty << CT;
break;
}
}
/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
/// will create a trap if the resulting type is not a POD type.
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl) {
if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
// Strip the unbridged-cast placeholder expression off, if applicable.
if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
(CT == VariadicMethod ||
(FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
E = stripARCUnbridgedCast(E);
// Otherwise, do normal placeholder checking.
} else {
ExprResult ExprRes = CheckPlaceholderExpr(E);
if (ExprRes.isInvalid())
return ExprError();
E = ExprRes.get();
}
}
ExprResult ExprRes = DefaultArgumentPromotion(E);
if (ExprRes.isInvalid())
return ExprError();
E = ExprRes.get();
// Diagnostics regarding non-POD argument types are
// emitted along with format string checking in Sema::CheckFunctionCall().
if (isValidVarArgType(E->getType()) == VAK_Undefined) {
// Turn this into a trap.
CXXScopeSpec SS;
SourceLocation TemplateKWLoc;
UnqualifiedId Name;
Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
E->getLocStart());
ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
Name, true, false);
if (TrapFn.isInvalid())
return ExprError();
ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
E->getLocStart(), None,
E->getLocEnd());
if (Call.isInvalid())
return ExprError();
ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
Call.get(), E);
if (Comma.isInvalid())
return ExprError();
return Comma.get();
}
if (!getLangOpts().CPlusPlus &&
RequireCompleteType(E->getExprLoc(), E->getType(),
diag::err_call_incomplete_argument))
return ExprError();
return E;
}
/// \brief Converts an integer to complex float type. Helper function of
/// UsualArithmeticConversions()
///
/// \return false if the integer expression is an integer type and is
/// successfully converted to the complex type.
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
ExprResult &ComplexExpr,
QualType IntTy,
QualType ComplexTy,
bool SkipCast) {
if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
if (SkipCast) return false;
if (IntTy->isIntegerType()) {
QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
CK_FloatingRealToComplex);
} else {
assert(IntTy->isComplexIntegerType());
IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
CK_IntegralComplexToFloatingComplex);
}
return false;
}
/// \brief Handle arithmetic conversion with complex types. Helper function of
/// UsualArithmeticConversions()
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
ExprResult &RHS, QualType LHSType,
QualType RHSType,
bool IsCompAssign) {
// if we have an integer operand, the result is the complex type.
if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
/*skipCast*/false))
return LHSType;
if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
/*skipCast*/IsCompAssign))
return RHSType;
// This handles complex/complex, complex/float, or float/complex.
// When both operands are complex, the shorter operand is converted to the
// type of the longer, and that is the type of the result. This corresponds
// to what is done when combining two real floating-point operands.
// The fun begins when size promotion occur across type domains.
// From H&S 6.3.4: When one operand is complex and the other is a real
// floating-point type, the less precise type is converted, within it's
// real or complex domain, to the precision of the other type. For example,
// when combining a "long double" with a "double _Complex", the
// "double _Complex" is promoted to "long double _Complex".
// Compute the rank of the two types, regardless of whether they are complex.
int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
QualType LHSElementType =
LHSComplexType ? LHSComplexType->getElementType() : LHSType;
QualType RHSElementType =
RHSComplexType ? RHSComplexType->getElementType() : RHSType;
QualType ResultType = S.Context.getComplexType(LHSElementType);
if (Order < 0) {
// Promote the precision of the LHS if not an assignment.
ResultType = S.Context.getComplexType(RHSElementType);
if (!IsCompAssign) {
if (LHSComplexType)
LHS =
S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
else
LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
}
} else if (Order > 0) {
// Promote the precision of the RHS.
if (RHSComplexType)
RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
else
RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
}
return ResultType;
}
/// \brief Hande arithmetic conversion from integer to float. Helper function
/// of UsualArithmeticConversions()
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
ExprResult &IntExpr,
QualType FloatTy, QualType IntTy,
bool ConvertFloat, bool ConvertInt) {
if (IntTy->isIntegerType()) {
if (ConvertInt)
// Convert intExpr to the lhs floating point type.
IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
CK_IntegralToFloating);
return FloatTy;
}
// Convert both sides to the appropriate complex float.
assert(IntTy->isComplexIntegerType());
QualType result = S.Context.getComplexType(FloatTy);
// _Complex int -> _Complex float
if (ConvertInt)
IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
CK_IntegralComplexToFloatingComplex);
// float -> _Complex float
if (ConvertFloat)
FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
CK_FloatingRealToComplex);
return result;
}
/// \brief Handle arithmethic conversion with floating point types. Helper
/// function of UsualArithmeticConversions()
static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
ExprResult &RHS, QualType LHSType,
QualType RHSType, bool IsCompAssign) {
bool LHSFloat = LHSType->isRealFloatingType();
bool RHSFloat = RHSType->isRealFloatingType();
// If we have two real floating types, convert the smaller operand
// to the bigger result.
if (LHSFloat && RHSFloat) {
int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
if (order > 0) {
RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
return LHSType;
}
assert(order < 0 && "illegal float comparison");
if (!IsCompAssign)
LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
return RHSType;
}
if (LHSFloat) {
// Half FP has to be promoted to float unless it is natively supported
if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
LHSType = S.Context.FloatTy;
return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
/*convertFloat=*/!IsCompAssign,
/*convertInt=*/ true);
}
assert(RHSFloat);
return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
/*convertInt=*/ true,
/*convertFloat=*/!IsCompAssign);
}
/// \brief Diagnose attempts to convert between __float128 and long double if
/// there is no support for such conversion. Helper function of
/// UsualArithmeticConversions().
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
QualType RHSType) {
/* No issue converting if at least one of the types is not a floating point
type or the two types have the same rank.
*/
if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
return false;
assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
"The remaining types must be floating point types.");
auto *LHSComplex = LHSType->getAs<ComplexType>();
auto *RHSComplex = RHSType->getAs<ComplexType>();
QualType LHSElemType = LHSComplex ?
LHSComplex->getElementType() : LHSType;
QualType RHSElemType = RHSComplex ?
RHSComplex->getElementType() : RHSType;
// No issue if the two types have the same representation
if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
&S.Context.getFloatTypeSemantics(RHSElemType))
return false;
bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
RHSElemType == S.Context.LongDoubleTy);
Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
RHSElemType == S.Context.Float128Ty);
/* We've handled the situation where __float128 and long double have the same
representation. The only other allowable conversion is if long double is
really just double.
*/
return Float128AndLongDouble &&
(&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
&llvm::APFloat::IEEEdouble());
}
typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
namespace {
/// These helper callbacks are placed in an anonymous namespace to
/// permit their use as function template parameters.
ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
return S.ImpCastExprToType(op, toType, CK_IntegralCast);
}
ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
CK_IntegralComplexCast);
}
}
/// \brief Handle integer arithmetic conversions. Helper function of
/// UsualArithmeticConversions()
template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
ExprResult &RHS, QualType LHSType,
QualType RHSType, bool IsCompAssign) {
// The rules for this case are in C99 6.3.1.8
int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
if (LHSSigned == RHSSigned) {
// Same signedness; use the higher-ranked type
if (order >= 0) {
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
return LHSType;
} else if (!IsCompAssign)
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
return RHSType;
} else if (order != (LHSSigned ? 1 : -1)) {
// The unsigned type has greater than or equal rank to the
// signed type, so use the unsigned type
if (RHSSigned) {
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
return LHSType;
} else if (!IsCompAssign)
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
return RHSType;
} else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
// The two types are different widths; if we are here, that
// means the signed type is larger than the unsigned type, so
// use the signed type.
if (LHSSigned) {
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
return LHSType;
} else if (!IsCompAssign)
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
return RHSType;
} else {
// The signed type is higher-ranked than the unsigned type,
// but isn't actually any bigger (like unsigned int and long
// on most 32-bit systems). Use the unsigned type corresponding
// to the signed type.
QualType result =
S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
RHS = (*doRHSCast)(S, RHS.get(), result);
if (!IsCompAssign)
LHS = (*doLHSCast)(S, LHS.get(), result);
return result;
}
}
/// \brief Handle conversions with GCC complex int extension. Helper function
/// of UsualArithmeticConversions()
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
ExprResult &RHS, QualType LHSType,
QualType RHSType,
bool IsCompAssign) {
const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
if (LHSComplexInt && RHSComplexInt) {
QualType LHSEltType = LHSComplexInt->getElementType();
QualType RHSEltType = RHSComplexInt->getElementType();
QualType ScalarType =
handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
(S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
return S.Context.getComplexType(ScalarType);
}
if (LHSComplexInt) {
QualType LHSEltType = LHSComplexInt->getElementType();
QualType ScalarType =
handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
(S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
QualType ComplexType = S.Context.getComplexType(ScalarType);
RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
CK_IntegralRealToComplex);
return ComplexType;
}
assert(RHSComplexInt);
QualType RHSEltType = RHSComplexInt->getElementType();
QualType ScalarType =
handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
(S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
QualType ComplexType = S.Context.getComplexType(ScalarType);
if (!IsCompAssign)
LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
CK_IntegralRealToComplex);
return ComplexType;
}
/// UsualArithmeticConversions - Performs various conversions that are common to
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
/// routine returns the first non-arithmetic type found. The client is
/// responsible for emitting appropriate error diagnostics.
QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
bool IsCompAssign) {
if (!IsCompAssign) {
LHS = UsualUnaryConversions(LHS.get());
if (LHS.isInvalid())
return QualType();
}
RHS = UsualUnaryConversions(RHS.get());
if (RHS.isInvalid())
return QualType();
// For conversion purposes, we ignore any qualifiers.
// For example, "const float" and "float" are equivalent.
QualType LHSType =
Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
QualType RHSType =
Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
// For conversion purposes, we ignore any atomic qualifier on the LHS.
if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
LHSType = AtomicLHS->getValueType();
// If both types are identical, no conversion is needed.
if (LHSType == RHSType)
return LHSType;
// If either side is a non-arithmetic type (e.g. a pointer), we are done.
// The caller can deal with this (e.g. pointer + int).
if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
return QualType();
// Apply unary and bitfield promotions to the LHS's type.
QualType LHSUnpromotedType = LHSType;
if (LHSType->isPromotableIntegerType())
LHSType = Context.getPromotedIntegerType(LHSType);
QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
if (!LHSBitfieldPromoteTy.isNull())
LHSType = LHSBitfieldPromoteTy;
if (LHSType != LHSUnpromotedType && !IsCompAssign)
LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
// If both types are identical, no conversion is needed.
if (LHSType == RHSType)
return LHSType;
// At this point, we have two different arithmetic types.
// Diagnose attempts to convert between __float128 and long double where
// such conversions currently can't be handled.
if (unsupportedTypeConversion(*this, LHSType, RHSType))
return QualType();
// Handle complex types first (C99 6.3.1.8p1).
if (LHSType->isComplexType() || RHSType->isComplexType())
return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
IsCompAssign);
// Now handle "real" floating types (i.e. float, double, long double).
if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
IsCompAssign);
// Handle GCC complex int extension.
if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
IsCompAssign);
// Finally, we have two differing integer types.
return handleIntegerConversion<doIntegralCast, doIntegralCast>
(*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
}
//===----------------------------------------------------------------------===//
// Semantic Analysis for various Expression Types
//===----------------------------------------------------------------------===//
ExprResult
Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs) {
unsigned NumAssocs = ArgTypes.size();
assert(NumAssocs == ArgExprs.size());
TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
for (unsigned i = 0; i < NumAssocs; ++i) {
if (ArgTypes[i])
(void) GetTypeFromParser(ArgTypes[i], &Types[i]);
else
Types[i] = nullptr;
}
ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
ControllingExpr,
llvm::makeArrayRef(Types, NumAssocs),
ArgExprs);
delete [] Types;
return ER;
}
ExprResult
Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs) {
unsigned NumAssocs = Types.size();
assert(NumAssocs == Exprs.size());
// Decay and strip qualifiers for the controlling expression type, and handle
// placeholder type replacement. See committee discussion from WG14 DR423.
{
EnterExpressionEvaluationContext Unevaluated(
*this, Sema::ExpressionEvaluationContext::Unevaluated);
ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
if (R.isInvalid())
return ExprError();
ControllingExpr = R.get();
}
// The controlling expression is an unevaluated operand, so side effects are
// likely unintended.
if (!inTemplateInstantiation() &&
ControllingExpr->HasSideEffects(Context, false))
Diag(ControllingExpr->getExprLoc(),
diag::warn_side_effects_unevaluated_context);
bool TypeErrorFound = false,
IsResultDependent = ControllingExpr->isTypeDependent(),
ContainsUnexpandedParameterPack
= ControllingExpr->containsUnexpandedParameterPack();
for (unsigned i = 0; i < NumAssocs; ++i) {
if (Exprs[i]->containsUnexpandedParameterPack())
ContainsUnexpandedParameterPack = true;
if (Types[i]) {
if (Types[i]->getType()->containsUnexpandedParameterPack())
ContainsUnexpandedParameterPack = true;
if (Types[i]->getType()->isDependentType()) {
IsResultDependent = true;
} else {
// C11 6.5.1.1p2 "The type name in a generic association shall specify a
// complete object type other than a variably modified type."
unsigned D = 0;
if (Types[i]->getType()->isIncompleteType())
D = diag::err_assoc_type_incomplete;
else if (!Types[i]->getType()->isObjectType())
D = diag::err_assoc_type_nonobject;
else if (Types[i]->getType()->isVariablyModifiedType())
D = diag::err_assoc_type_variably_modified;
if (D != 0) {
Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
<< Types[i]->getTypeLoc().getSourceRange()
<< Types[i]->getType();
TypeErrorFound = true;
}
// C11 6.5.1.1p2 "No two generic associations in the same generic
// selection shall specify compatible types."
for (unsigned j = i+1; j < NumAssocs; ++j)
if (Types[j] && !Types[j]->getType()->isDependentType() &&
Context.typesAreCompatible(Types[i]->getType(),
Types[j]->getType())) {
Diag(Types[j]->getTypeLoc().getBeginLoc(),
diag::err_assoc_compatible_types)
<< Types[j]->getTypeLoc().getSourceRange()
<< Types[j]->getType()
<< Types[i]->getType();
Diag(Types[i]->getTypeLoc().getBeginLoc(),
diag::note_compat_assoc)
<< Types[i]->getTypeLoc().getSourceRange()
<< Types[i]->getType();
TypeErrorFound = true;
}
}
}
}
if (TypeErrorFound)
return ExprError();
// If we determined that the generic selection is result-dependent, don't
// try to compute the result expression.
if (IsResultDependent)
return new (Context) GenericSelectionExpr(
Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
ContainsUnexpandedParameterPack);
SmallVector<unsigned, 1> CompatIndices;
unsigned DefaultIndex = -1U;
for (unsigned i = 0; i < NumAssocs; ++i) {
if (!Types[i])
DefaultIndex = i;
else if (Context.typesAreCompatible(ControllingExpr->getType(),
Types[i]->getType()))
CompatIndices.push_back(i);
}
// C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
// type compatible with at most one of the types named in its generic
// association list."
if (CompatIndices.size() > 1) {
// We strip parens here because the controlling expression is typically
// parenthesized in macro definitions.
ControllingExpr = ControllingExpr->IgnoreParens();
Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
<< ControllingExpr->getSourceRange() << ControllingExpr->getType()
<< (unsigned) CompatIndices.size();
for (unsigned I : CompatIndices) {
Diag(Types[I]->getTypeLoc().getBeginLoc(),
diag::note_compat_assoc)
<< Types[I]->getTypeLoc().getSourceRange()
<< Types[I]->getType();
}
return ExprError();
}
// C11 6.5.1.1p2 "If a generic selection has no default generic association,
// its controlling expression shall have type compatible with exactly one of
// the types named in its generic association list."
if (DefaultIndex == -1U && CompatIndices.size() == 0) {
// We strip parens here because the controlling expression is typically
// parenthesized in macro definitions.
ControllingExpr = ControllingExpr->IgnoreParens();
Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
<< ControllingExpr->getSourceRange() << ControllingExpr->getType();
return ExprError();
}
// C11 6.5.1.1p3 "If a generic selection has a generic association with a
// type name that is compatible with the type of the controlling expression,
// then the result expression of the generic selection is the expression
// in that generic association. Otherwise, the result expression of the
// generic selection is the expression in the default generic association."
unsigned ResultIndex =
CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
return new (Context) GenericSelectionExpr(
Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
ContainsUnexpandedParameterPack, ResultIndex);
}
/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
/// location of the token and the offset of the ud-suffix within it.
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
unsigned Offset) {
return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
S.getLangOpts());
}
/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
/// the corresponding cooked (non-raw) literal operator, and build a call to it.
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
IdentifierInfo *UDSuffix,
SourceLocation UDSuffixLoc,
ArrayRef<Expr*> Args,
SourceLocation LitEndLoc) {
assert(Args.size() <= 2 && "too many arguments for literal operator");
QualType ArgTy[2];
for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
ArgTy[ArgIdx] = Args[ArgIdx]->getType();
if (ArgTy[ArgIdx]->isArrayType())
ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
}
DeclarationName OpName =
S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
/*AllowRaw*/false, /*AllowTemplate*/false,
/*AllowStringTemplate*/false) == Sema::LOLR_Error)
return ExprError();
return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
}
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
/// multiple tokens. However, the common case is that StringToks points to one
/// string.
///
ExprResult
Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
assert(!StringToks.empty() && "Must have at least one string!");
StringLiteralParser Literal(StringToks, PP);
if (Literal.hadError)
return ExprError();
SmallVector<SourceLocation, 4> StringTokLocs;
for (const Token &Tok : StringToks)
StringTokLocs.push_back(Tok.getLocation());
QualType CharTy = Context.CharTy;
StringLiteral::StringKind Kind = StringLiteral::Ascii;
if (Literal.isWide()) {
CharTy = Context.getWideCharType();
Kind = StringLiteral::Wide;
} else if (Literal.isUTF8()) {
Kind = StringLiteral::UTF8;
} else if (Literal.isUTF16()) {
CharTy = Context.Char16Ty;
Kind = StringLiteral::UTF16;
} else if (Literal.isUTF32()) {
CharTy = Context.Char32Ty;
Kind = StringLiteral::UTF32;
} else if (Literal.isPascal()) {
CharTy = Context.UnsignedCharTy;
}
QualType CharTyConst = CharTy;
// A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
CharTyConst.addConst();
// Get an array type for the string, according to C99 6.4.5. This includes
// the nul terminator character as well as the string length for pascal
// strings.
QualType StrTy = Context.getConstantArrayType(CharTyConst,
llvm::APInt(32, Literal.GetNumStringChars()+1),
ArrayType::Normal, 0);
// OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
if (getLangOpts().OpenCL) {
StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
}
// Pass &StringTokLocs[0], StringTokLocs.size() to factory!
StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
Kind, Literal.Pascal, StrTy,
&StringTokLocs[0],
StringTokLocs.size());
if (Literal.getUDSuffix().empty())
return Lit;
// We're building a user-defined literal.
IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
SourceLocation UDSuffixLoc =
getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
Literal.getUDSuffixOffset());
// Make sure we're allowed user-defined literals here.
if (!UDLScope)
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
// C++11 [lex.ext]p5: The literal L is treated as a call of the form
// operator "" X (str, len)
QualType SizeType = Context.getSizeType();
DeclarationName OpName =
Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
QualType ArgTy[] = {
Context.getArrayDecayedType(StrTy), SizeType
};
LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
switch (LookupLiteralOperator(UDLScope, R, ArgTy,
/*AllowRaw*/false, /*AllowTemplate*/false,
/*AllowStringTemplate*/true)) {
case LOLR_Cooked: {
llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
StringTokLocs[0]);
Expr *Args[] = { Lit, LenArg };
return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
}
case LOLR_StringTemplate: {
TemplateArgumentListInfo ExplicitArgs;
unsigned CharBits = Context.getIntWidth(CharTy);
bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
llvm::APSInt Value(CharBits, CharIsUnsigned);
TemplateArgument TypeArg(CharTy);
TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
Value = Lit->getCodeUnit(I);
TemplateArgument Arg(Context, Value, CharTy);
TemplateArgumentLocInfo ArgInfo;
ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
}
return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
&ExplicitArgs);
}
case LOLR_Raw:
case LOLR_Template:
llvm_unreachable("unexpected literal operator lookup result");
case LOLR_Error:
return ExprError();
}
llvm_unreachable("unexpected literal operator lookup result");
}
ExprResult
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS) {
DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
}
/// BuildDeclRefExpr - Build an expression that references a
/// declaration that does not require a closure capture.
ExprResult
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS, NamedDecl *FoundD,
const TemplateArgumentListInfo *TemplateArgs) {
bool RefersToCapturedVariable =
isa<VarDecl>(D) &&
NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
DeclRefExpr *E;
if (isa<VarTemplateSpecializationDecl>(D)) {
VarTemplateSpecializationDecl *VarSpec =
cast<VarTemplateSpecializationDecl>(D);
E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
: NestedNameSpecifierLoc(),
VarSpec->getTemplateKeywordLoc(), D,
RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
FoundD, TemplateArgs);
} else {
assert(!TemplateArgs && "No template arguments for non-variable"
" template specialization references");
E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
: NestedNameSpecifierLoc(),
SourceLocation(), D, RefersToCapturedVariable,
NameInfo, Ty, VK, FoundD);
}
MarkDeclRefReferenced(E);
if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
recordUseOfEvaluatedWeak(E);
if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
UnusedPrivateFields.remove(FD);
// Just in case we're building an illegal pointer-to-member.
if (FD->isBitField())
E->setObjectKind(OK_BitField);
}
// C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
// designates a bit-field.
if (auto *BD = dyn_cast<BindingDecl>(D))
if (auto *BE = BD->getBinding())
E->setObjectKind(BE->getObjectKind());
return E;
}
/// Decomposes the given name into a DeclarationNameInfo, its location, and
/// possibly a list of template arguments.
///
/// If this produces template arguments, it is permitted to call
/// DecomposeTemplateName.
///
/// This actually loses a lot of source location information for
/// non-standard name kinds; we should consider preserving that in
/// some way.
void
Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs) {
if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
Id.TemplateId->NumArgs);
translateTemplateArguments(TemplateArgsPtr, Buffer);
TemplateName TName = Id.TemplateId->Template.get();
SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
NameInfo = Context.getNameForTemplate(TName, TNameLoc);
TemplateArgs = &Buffer;
} else {
NameInfo = GetNameFromUnqualifiedId(Id);
TemplateArgs = nullptr;
}
}
static void emitEmptyLookupTypoDiagnostic(
const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
DeclContext *Ctx =
SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
if (!TC) {
// Emit a special diagnostic for failed member lookups.
// FIXME: computing the declaration context might fail here (?)
if (Ctx)
SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
<< SS.getRange();
else
SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
return;
}
std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
bool DroppedSpecifier =
TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
? diag::note_implicit_param_decl
: diag::note_previous_decl;
if (!Ctx)
SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
SemaRef.PDiag(NoteID));
else
SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
<< Typo << Ctx << DroppedSpecifier
<< SS.getRange(),
SemaRef.PDiag(NoteID));
}
/// Diagnose an empty lookup.
///
/// \return false if new lookup candidates were found
bool
Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args, TypoExpr **Out) {
DeclarationName Name = R.getLookupName();
unsigned diagnostic = diag::err_undeclared_var_use;
unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
diagnostic = diag::err_undeclared_use;
diagnostic_suggest = diag::err_undeclared_use_suggest;
}
// If the original lookup was an unqualified lookup, fake an
// unqualified lookup. This is useful when (for example) the
// original lookup would not have found something because it was a
// dependent name.
DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
while (DC) {
if (isa<CXXRecordDecl>(DC)) {
LookupQualifiedName(R, DC);
if (!R.empty()) {
// Don't give errors about ambiguities in this lookup.
R.suppressDiagnostics();
// During a default argument instantiation the CurContext points
// to a CXXMethodDecl; but we can't apply a this-> fixit inside a
// function parameter list, hence add an explicit check.
bool isDefaultArgument =
!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.back().Kind ==
CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
bool isInstance = CurMethod &&
CurMethod->isInstance() &&
DC == CurMethod->getParent() && !isDefaultArgument;
// Give a code modification hint to insert 'this->'.
// TODO: fixit for inserting 'Base<T>::' in the other cases.
// Actually quite difficult!
if (getLangOpts().MSVCCompat)
diagnostic = diag::ext_found_via_dependent_bases_lookup;
if (isInstance) {
Diag(R.getNameLoc(), diagnostic) << Name
<< FixItHint::CreateInsertion(R.getNameLoc(), "this->");
CheckCXXThisCapture(R.getNameLoc());
} else {
Diag(R.getNameLoc(), diagnostic) << Name;
}
// Do we really want to note all of these?
for (NamedDecl *D : R)
Diag(D->getLocation(), diag::note_dependent_var_use);
// Return true if we are inside a default argument instantiation
// and the found name refers to an instance member function, otherwise
// the function calling DiagnoseEmptyLookup will try to create an
// implicit member call and this is wrong for default argument.
if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
Diag(R.getNameLoc(), diag::err_member_call_without_object);
return true;
}
// Tell the callee to try to recover.
return false;
}
R.clear();
}
// In Microsoft mode, if we are performing lookup from within a friend
// function definition declared at class scope then we must set
// DC to the lexical parent to be able to search into the parent
// class.
if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
cast<FunctionDecl>(DC)->getFriendObjectKind() &&
DC->getLexicalParent()->isRecord())
DC = DC->getLexicalParent();
else
DC = DC->getParent();
}
// We didn't find anything, so try to correct for a typo.
TypoCorrection Corrected;
if (S && Out) {
SourceLocation TypoLoc = R.getNameLoc();
assert(!ExplicitTemplateArgs &&
"Diagnosing an empty lookup with explicit template args!");
*Out = CorrectTypoDelayed(
R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
[=](const TypoCorrection &TC) {
emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
diagnostic, diagnostic_suggest);
},
nullptr, CTK_ErrorRecovery);
if (*Out)
return true;
} else if (S && (Corrected =
CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
&SS, std::move(CCC), CTK_ErrorRecovery))) {
std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
bool DroppedSpecifier =
Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
R.setLookupName(Corrected.getCorrection());
bool AcceptableWithRecovery = false;
bool AcceptableWithoutRecovery = false;
NamedDecl *ND = Corrected.getFoundDecl();
if (ND) {
if (Corrected.isOverloaded()) {
OverloadCandidateSet OCS(R.getNameLoc(),
OverloadCandidateSet::CSK_Normal);
OverloadCandidateSet::iterator Best;
for (NamedDecl *CD : Corrected) {
if (FunctionTemplateDecl *FTD =
dyn_cast<FunctionTemplateDecl>(CD))
AddTemplateOverloadCandidate(
FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Args, OCS);
else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Args, OCS);
}
switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
case OR_Success:
ND = Best->FoundDecl;
Corrected.setCorrectionDecl(ND);
break;
default:
// FIXME: Arbitrarily pick the first declaration for the note.
Corrected.setCorrectionDecl(ND);
break;
}
}
R.addDecl(ND);
if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
CXXRecordDecl *Record = nullptr;
if (Corrected.getCorrectionSpecifier()) {
const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
Record = Ty->getAsCXXRecordDecl();
}
if (!Record)
Record = cast<CXXRecordDecl>(
ND->getDeclContext()->getRedeclContext());
R.setNamingClass(Record);
}
auto *UnderlyingND = ND->getUnderlyingDecl();
AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
isa<FunctionTemplateDecl>(UnderlyingND);
// FIXME: If we ended up with a typo for a type name or
// Objective-C class name, we're in trouble because the parser
// is in the wrong place to recover. Suggest the typo
// correction, but don't make it a fix-it since we're not going
// to recover well anyway.
AcceptableWithoutRecovery =
isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
} else {
// FIXME: We found a keyword. Suggest it, but don't provide a fix-it
// because we aren't able to recover.
AcceptableWithoutRecovery = true;
}
if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
? diag::note_implicit_param_decl
: diag::note_previous_decl;
if (SS.isEmpty())
diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
PDiag(NoteID), AcceptableWithRecovery);
else
diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
<< Name << computeDeclContext(SS, false)
<< DroppedSpecifier << SS.getRange(),
PDiag(NoteID), AcceptableWithRecovery);
// Tell the callee whether to try to recover.
return !AcceptableWithRecovery;
}
}
R.clear();
// Emit a special diagnostic for failed member lookups.
// FIXME: computing the declaration context might fail here (?)
if (!SS.isEmpty()) {
Diag(R.getNameLoc(), diag::err_no_member)
<< Name << computeDeclContext(SS, false)
<< SS.getRange();
return true;
}
// Give up, we can't recover.
Diag(R.getNameLoc(), diagnostic) << Name;
return true;
}
/// In Microsoft mode, if we are inside a template class whose parent class has
/// dependent base classes, and we can't resolve an unqualified identifier, then
/// assume the identifier is a member of a dependent base class. We can only
/// recover successfully in static methods, instance methods, and other contexts
/// where 'this' is available. This doesn't precisely match MSVC's
/// instantiation model, but it's close enough.
static Expr *
recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
DeclarationNameInfo &NameInfo,
SourceLocation TemplateKWLoc,
const TemplateArgumentListInfo *TemplateArgs) {
// Only try to recover from lookup into dependent bases in static methods or
// contexts where 'this' is available.
QualType ThisType = S.getCurrentThisType();
const CXXRecordDecl *RD = nullptr;
if (!ThisType.isNull())
RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
RD = MD->getParent();
if (!RD || !RD->hasAnyDependentBases())
return nullptr;
// Diagnose this as unqualified lookup into a dependent base class. If 'this'
// is available, suggest inserting 'this->' as a fixit.
SourceLocation Loc = NameInfo.getLoc();
auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
DB << NameInfo.getName() << RD;
if (!ThisType.isNull()) {
DB << FixItHint::CreateInsertion(Loc, "this->");
return CXXDependentScopeMemberExpr::Create(
Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
/*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
/*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
}
// Synthesize a fake NNS that points to the derived class. This will
// perform name lookup during template instantiation.
CXXScopeSpec SS;
auto *NNS =
NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
return DependentScopeDeclRefExpr::Create(
Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
TemplateArgs);
}
ExprResult
Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
SourceLocation TemplateKWLoc, UnqualifiedId &Id,
bool HasTrailingLParen, bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC,
bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
assert(!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen");
if (SS.isInvalid())
return ExprError();
TemplateArgumentListInfo TemplateArgsBuffer;
// Decompose the UnqualifiedId into the following data.
DeclarationNameInfo NameInfo;
const TemplateArgumentListInfo *TemplateArgs;
DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
DeclarationName Name = NameInfo.getName();
IdentifierInfo *II = Name.getAsIdentifierInfo();
SourceLocation NameLoc = NameInfo.getLoc();
// C++ [temp.dep.expr]p3:
// An id-expression is type-dependent if it contains:
// -- an identifier that was declared with a dependent type,
// (note: handled after lookup)
// -- a template-id that is dependent,
// (note: handled in BuildTemplateIdExpr)
// -- a conversion-function-id that specifies a dependent type,
// -- a nested-name-specifier that contains a class-name that
// names a dependent type.
// Determine whether this is a member of an unknown specialization;
// we need to handle these differently.
bool DependentID = false;
if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
Name.getCXXNameType()->isDependentType()) {
DependentID = true;
} else if (SS.isSet()) {
if (DeclContext *DC = computeDeclContext(SS, false)) {
if (RequireCompleteDeclContext(SS, DC))
return ExprError();
} else {
DependentID = true;
}
}
if (DependentID)
return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
IsAddressOfOperand, TemplateArgs);
// Perform the required lookup.
LookupResult R(*this, NameInfo,
(Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
? LookupObjCImplicitSelfParam : LookupOrdinaryName);
if (TemplateArgs) {
// Lookup the template name again to correctly establish the context in
// which it was found. This is really unfortunate as we already did the
// lookup to determine that it was a template name in the first place. If
// this becomes a performance hit, we can work harder to preserve those
// results until we get here but it's likely not worth it.
bool MemberOfUnknownSpecialization;
LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
MemberOfUnknownSpecialization);
if (MemberOfUnknownSpecialization ||
(R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
IsAddressOfOperand, TemplateArgs);
} else {
bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
// If the result might be in a dependent base class, this is a dependent
// id-expression.
if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
IsAddressOfOperand, TemplateArgs);
// If this reference is in an Objective-C method, then we need to do
// some special Objective-C lookup, too.
if (IvarLookupFollowUp) {
ExprResult E(LookupInObjCMethod(R, S, II, true));
if (E.isInvalid())
return ExprError();
if (Expr *Ex = E.getAs<Expr>())
return Ex;
}
}
if (R.isAmbiguous())
return ExprError();
// This could be an implicitly declared function reference (legal in C90,
// extension in C99, forbidden in C++).
if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
if (D) R.addDecl(D);
}
// Determine whether this name might be a candidate for
// argument-dependent lookup.
bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
if (R.empty() && !ADL) {
if (SS.isEmpty() && getLangOpts().MSVCCompat) {
if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
TemplateKWLoc, TemplateArgs))
return E;
}
// Don't diagnose an empty lookup for inline assembly.
if (IsInlineAsmIdentifier)
return ExprError();
// If this name wasn't predeclared and if this is not a function
// call, diagnose the problem.
TypoExpr *TE = nullptr;
auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
II, SS.isValid() ? SS.getScopeRep() : nullptr);
DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured");
if (CCC) {
// Make sure the callback knows what the typo being diagnosed is.
CCC->setTypoName(II);
if (SS.isValid())
CCC->setTypoNNS(SS.getScopeRep());
}
if (DiagnoseEmptyLookup(S, SS, R,
CCC ? std::move(CCC) : std::move(DefaultValidator),
nullptr, None, &TE)) {
if (TE && KeywordReplacement) {
auto &State = getTypoExprState(TE);
auto BestTC = State.Consumer->getNextCorrection();
if (BestTC.isKeyword()) {
auto *II = BestTC.getCorrectionAsIdentifierInfo();
if (State.DiagHandler)
State.DiagHandler(BestTC);
KeywordReplacement->startToken();
KeywordReplacement->setKind(II->getTokenID());
KeywordReplacement->setIdentifierInfo(II);
KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
// Clean up the state associated with the TypoExpr, since it has
// now been diagnosed (without a call to CorrectDelayedTyposInExpr).
clearDelayedTypo(TE);
// Signal that a correction to a keyword was performed by returning a
// valid-but-null ExprResult.
return (Expr*)nullptr;
}
State.Consumer->resetCorrectionStream();
}
return TE ? TE : ExprError();
}
assert(!R.empty() &&
"DiagnoseEmptyLookup returned false but added no results");
// If we found an Objective-C instance variable, let
// LookupInObjCMethod build the appropriate expression to
// reference the ivar.
if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
R.clear();
ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
// In a hopelessly buggy code, Objective-C instance variable
// lookup fails and no expression will be built to reference it.
if (!E.isInvalid() && !E.get())
return ExprError();
return E;
}
}
// This is guaranteed from this point on.
assert(!R.empty() || ADL);
// Check whether this might be a C++ implicit instance member access.
// C++ [class.mfct.non-static]p3:
// When an id-expression that is not part of a class member access
// syntax and not used to form a pointer to member is used in the
// body of a non-static member function of class X, if name lookup
// resolves the name in the id-expression to a non-static non-type
// member of some class C, the id-expression is transformed into a
// class member access expression using (*this) as the
// postfix-expression to the left of the . operator.
//
// But we don't actually need to do this for '&' operands if R
// resolved to a function or overloaded function set, because the
// expression is ill-formed if it actually works out to be a
// non-static member function:
//
// C++ [expr.ref]p4:
// Otherwise, if E1.E2 refers to a non-static member function. . .
// [t]he expression can be used only as the left-hand operand of a
// member function call.
//
// There are other safeguards against such uses, but it's important
// to get this right here so that we don't end up making a
// spuriously dependent expression if we're inside a dependent
// instance method.
if (!R.empty() && (*R.begin())->isCXXClassMember()) {
bool MightBeImplicitMember;
if (!IsAddressOfOperand)
MightBeImplicitMember = true;
else if (!SS.isEmpty())
MightBeImplicitMember = false;
else if (R.isOverloadedResult())
MightBeImplicitMember = false;
else if (R.isUnresolvableResult())
MightBeImplicitMember = true;
else
MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
isa<IndirectFieldDecl>(R.getFoundDecl()) ||
isa<MSPropertyDecl>(R.getFoundDecl());
if (MightBeImplicitMember)
return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
R, TemplateArgs, S);
}
if (TemplateArgs || TemplateKWLoc.isValid()) {
// In C++1y, if this is a variable template id, then check it
// in BuildTemplateIdExpr().
// The single lookup result must be a variable template declaration.
if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
Id.TemplateId->Kind == TNK_Var_template) {
assert(R.getAsSingle<VarTemplateDecl>() &&
"There should only be one declaration found.");
}
return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
}
return BuildDeclarationNameExpr(SS, R, ADL);
}
/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
/// declaration name, generally during template instantiation.
/// There's a large number of things which don't need to be done along
/// this path.
ExprResult Sema::BuildQualifiedDeclarationNameExpr(
CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
DeclContext *DC = computeDeclContext(SS, false);
if (!DC)
return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
NameInfo, /*TemplateArgs=*/nullptr);
if (RequireCompleteDeclContext(SS, DC))
return ExprError();
LookupResult R(*this, NameInfo, LookupOrdinaryName);
LookupQualifiedName(R, DC);
if (R.isAmbiguous())
return ExprError();
if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
NameInfo, /*TemplateArgs=*/nullptr);
if (R.empty()) {
Diag(NameInfo.getLoc(), diag::err_no_member)
<< NameInfo.getName() << DC << SS.getRange();
return ExprError();
}
if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
// Diagnose a missing typename if this resolved unambiguously to a type in
// a dependent context. If we can recover with a type, downgrade this to
// a warning in Microsoft compatibility mode.
unsigned DiagID = diag::err_typename_missing;
if (RecoveryTSI && getLangOpts().MSVCCompat)
DiagID = diag::ext_typename_missing;
SourceLocation Loc = SS.getBeginLoc();
auto D = Diag(Loc, DiagID);
D << SS.getScopeRep() << NameInfo.getName().getAsString()
<< SourceRange(Loc, NameInfo.getEndLoc());
// Don't recover if the caller isn't expecting us to or if we're in a SFINAE
// context.
if (!RecoveryTSI)
return ExprError();
// Only issue the fixit if we're prepared to recover.
D << FixItHint::CreateInsertion(Loc, "typename ");
// Recover by pretending this was an elaborated type.
QualType Ty = Context.getTypeDeclType(TD);
TypeLocBuilder TLB;
TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
QualType ET = getElaboratedType(ETK_None, SS, Ty);
ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
QTL.setElaboratedKeywordLoc(SourceLocation());
QTL.setQualifierLoc(SS.getWithLocInContext(Context));
*RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
return ExprEmpty();
}
// Defend against this resolving to an implicit member access. We usually
// won't get here if this might be a legitimate a class member (we end up in
// BuildMemberReferenceExpr instead), but this can be valid if we're forming
// a pointer-to-member or in an unevaluated context in C++11.
if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
return BuildPossibleImplicitMemberExpr(SS,
/*TemplateKWLoc=*/SourceLocation(),
R, /*TemplateArgs=*/nullptr, S);
return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
}
/// LookupInObjCMethod - The parser has read a name in, and Sema has
/// detected that we're currently inside an ObjC method. Perform some
/// additional lookup.
///
/// Ideally, most of this would be done by lookup, but there's
/// actually quite a lot of extra work involved.
///
/// Returns a null sentinel to indicate trivial success.
ExprResult
Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
IdentifierInfo *II, bool AllowBuiltinCreation) {
SourceLocation Loc = Lookup.getNameLoc();
ObjCMethodDecl *CurMethod = getCurMethodDecl();
// Check for error condition which is already reported.
if (!CurMethod)
return ExprError();
// There are two cases to handle here. 1) scoped lookup could have failed,
// in which case we should look for an ivar. 2) scoped lookup could have
// found a decl, but that decl is outside the current instance method (i.e.
// a global variable). In these two cases, we do a lookup for an ivar with
// this name, if the lookup sucedes, we replace it our current decl.
// If we're in a class method, we don't normally want to look for
// ivars. But if we don't find anything else, and there's an
// ivar, that's an error.
bool IsClassMethod = CurMethod->isClassMethod();
bool LookForIvars;
if (Lookup.empty())
LookForIvars = true;
else if (IsClassMethod)
LookForIvars = false;
else
LookForIvars = (Lookup.isSingleResult() &&
Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
ObjCInterfaceDecl *IFace = nullptr;
if (LookForIvars) {
IFace = CurMethod->getClassInterface();
ObjCInterfaceDecl *ClassDeclared;
ObjCIvarDecl *IV = nullptr;
if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
// Diagnose using an ivar in a class method.
if (IsClassMethod)
return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
<< IV->getDeclName());
// If we're referencing an invalid decl, just return this as a silent
// error node. The error diagnostic was already emitted on the decl.
if (IV->isInvalidDecl())
return ExprError();
// Check if referencing a field with __attribute__((deprecated)).
if (DiagnoseUseOfDecl(IV, Loc))
return ExprError();
// Diagnose the use of an ivar outside of the declaring class.
if (IV->getAccessControl() == ObjCIvarDecl::Private &&
!declaresSameEntity(ClassDeclared, IFace) &&
!getLangOpts().DebuggerSupport)
Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
// FIXME: This should use a new expr for a direct reference, don't
// turn this into Self->ivar, just return a BareIVarExpr or something.
IdentifierInfo &II = Context.Idents.get("self");
UnqualifiedId SelfName;
SelfName.setIdentifier(&II, SourceLocation());
SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
CXXScopeSpec SelfScopeSpec;
SourceLocation TemplateKWLoc;
ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
SelfName, false, false);
if (SelfExpr.isInvalid())
return ExprError();
SelfExpr = DefaultLvalueConversion(SelfExpr.get());
if (SelfExpr.isInvalid())
return ExprError();
MarkAnyDeclReferenced(Loc, IV, true);
ObjCMethodFamily MF = CurMethod->getMethodFamily();
if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
!IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
ObjCIvarRefExpr *Result = new (Context)
ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
IV->getLocation(), SelfExpr.get(), true, true);
if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
recordUseOfEvaluatedWeak(Result);
}
if (getLangOpts().ObjCAutoRefCount) {
if (CurContext->isClosure())
Diag(Loc, diag::warn_implicitly_retains_self)
<< FixItHint::CreateInsertion(Loc, "self->");
}
return Result;
}
} else if (CurMethod->isInstanceMethod()) {
// We should warn if a local variable hides an ivar.
if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
ObjCInterfaceDecl *ClassDeclared;
if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
if (IV->getAccessControl() != ObjCIvarDecl::Private ||
declaresSameEntity(IFace, ClassDeclared))
Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
}
}
} else if (Lookup.isSingleResult() &&
Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
// If accessing a stand-alone ivar in a class method, this is an error.
if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
<< IV->getDeclName());
}
if (Lookup.empty() && II && AllowBuiltinCreation) {
// FIXME. Consolidate this with similar code in LookupName.
if (unsigned BuiltinID = II->getBuiltinID()) {
if (!(getLangOpts().CPlusPlus &&
Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
S, Lookup.isForRedeclaration(),
Lookup.getNameLoc());
if (D) Lookup.addDecl(D);
}
}
}
// Sentinel value saying that we didn't do anything special.
return ExprResult((Expr *)nullptr);
}
/// \brief Cast a base object to a member's actual type.
///
/// Logically this happens in three phases:
///
/// * First we cast from the base type to the naming class.
/// The naming class is the class into which we were looking
/// when we found the member; it's the qualifier type if a
/// qualifier was provided, and otherwise it's the base type.
///
/// * Next we cast from the naming class to the declaring class.
/// If the member we found was brought into a class's scope by
/// a using declaration, this is that class; otherwise it's
/// the class declaring the member.
///
/// * Finally we cast from the declaring class to the "true"
/// declaring class of the member. This conversion does not
/// obey access control.
ExprResult
Sema::PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member) {
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
if (!RD)
return From;
QualType DestRecordType;
QualType DestType;
QualType FromRecordType;
QualType FromType = From->getType();
bool PointerConversions = false;
if (isa<FieldDecl>(Member)) {
DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
if (FromType->getAs<PointerType>()) {
DestType = Context.getPointerType(DestRecordType);
FromRecordType = FromType->getPointeeType();
PointerConversions = true;
} else {
DestType = DestRecordType;
FromRecordType = FromType;
}
} else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
if (Method->isStatic())
return From;
DestType = Method->getThisType(Context);
DestRecordType = DestType->getPointeeType();
if (FromType->getAs<PointerType>()) {
FromRecordType = FromType->getPointeeType();
PointerConversions = true;
} else {
FromRecordType = FromType;
DestType = DestRecordType;
}
} else {
// No conversion necessary.
return From;
}
if (DestType->isDependentType() || FromType->isDependentType())
return From;
// If the unqualified types are the same, no conversion is necessary.
if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
return From;
SourceRange FromRange = From->getSourceRange();
SourceLocation FromLoc = FromRange.getBegin();
ExprValueKind VK = From->getValueKind();
// C++ [class.member.lookup]p8:
// [...] Ambiguities can often be resolved by qualifying a name with its
// class name.
//
// If the member was a qualified name and the qualified referred to a
// specific base subobject type, we'll cast to that intermediate type
// first and then to the object in which the member is declared. That allows
// one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
//
// class Base { public: int x; };
// class Derived1 : public Base { };
// class Derived2 : public Base { };
// class VeryDerived : public Derived1, public Derived2 { void f(); };
//
// void VeryDerived::f() {
// x = 17; // error: ambiguous base subobjects
// Derived1::x = 17; // okay, pick the Base subobject of Derived1
// }
if (Qualifier && Qualifier->getAsType()) {
QualType QType = QualType(Qualifier->getAsType(), 0);
assert(QType->isRecordType() && "lookup done with non-record type");
QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
// In C++98, the qualifier type doesn't actually have to be a base
// type of the object type, in which case we just ignore it.
// Otherwise build the appropriate casts.
if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
CXXCastPath BasePath;
if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
FromLoc, FromRange, &BasePath))
return ExprError();
if (PointerConversions)
QType = Context.getPointerType(QType);
From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
VK, &BasePath).get();
FromType = QType;
FromRecordType = QRecordType;
// If the qualifier type was the same as the destination type,
// we're done.
if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
return From;
}
}
bool IgnoreAccess = false;
// If we actually found the member through a using declaration, cast
// down to the using declaration's type.
//
// Pointer equality is fine here because only one declaration of a
// class ever has member declarations.
if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
assert(isa<UsingShadowDecl>(FoundDecl));
QualType URecordType = Context.getTypeDeclType(
cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
// We only need to do this if the naming-class to declaring-class
// conversion is non-trivial.
if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
CXXCastPath BasePath;
if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
FromLoc, FromRange, &BasePath))
return ExprError();
QualType UType = URecordType;
if (PointerConversions)
UType = Context.getPointerType(UType);
From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
VK, &BasePath).get();
FromType = UType;
FromRecordType = URecordType;
}
// We don't do access control for the conversion from the
// declaring class to the true declaring class.
IgnoreAccess = true;
}
CXXCastPath BasePath;
if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
FromLoc, FromRange, &BasePath,
IgnoreAccess))
return ExprError();
return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
VK, &BasePath);
}
bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen) {
// Only when used directly as the postfix-expression of a call.
if (!HasTrailingLParen)
return false;
// Never if a scope specifier was provided.
if (SS.isSet())
return false;
// Only in C++ or ObjC++.
if (!getLangOpts().CPlusPlus)
return false;
// Turn off ADL when we find certain kinds of declarations during
// normal lookup:
for (NamedDecl *D : R) {
// C++0x [basic.lookup.argdep]p3:
// -- a declaration of a class member
// Since using decls preserve this property, we check this on the
// original decl.
if (D->isCXXClassMember())
return false;
// C++0x [basic.lookup.argdep]p3:
// -- a block-scope function declaration that is not a
// using-declaration
// NOTE: we also trigger this for function templates (in fact, we
// don't check the decl type at all, since all other decl types
// turn off ADL anyway).
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
else if (D->getLexicalDeclContext()->isFunctionOrMethod())
return false;
// C++0x [basic.lookup.argdep]p3:
// -- a declaration that is neither a function or a function
// template
// And also for builtin functions.
if (isa<FunctionDecl>(D)) {
FunctionDecl *FDecl = cast<FunctionDecl>(D);
// But also builtin functions.
if (FDecl->getBuiltinID() && FDecl->isImplicit())
return false;
} else if (!isa<FunctionTemplateDecl>(D))
return false;
}
return true;
}
/// Diagnoses obvious problems with the use of the given declaration
/// as an expression. This is only actually called for lookups that
/// were not overloaded, and it doesn't promise that the declaration
/// will in fact be used.
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
if (D->isInvalidDecl())
return true;
if (isa<TypedefNameDecl>(D)) {
S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
return true;
}
if (isa<ObjCInterfaceDecl>(D)) {
S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
return true;
}
if (isa<NamespaceDecl>(D)) {
S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
return true;
}
return false;
}
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R, bool NeedsADL,
bool AcceptInvalidDecl) {
// If this is a single, fully-resolved result and we don't need ADL,
// just build an ordinary singleton decl ref.
if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
R.getRepresentativeDecl(), nullptr,
AcceptInvalidDecl);
// We only need to check the declaration if there's exactly one
// result, because in the overloaded case the results can only be
// functions and function templates.
if (R.isSingleResult() &&
CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
return ExprError();
// Otherwise, just build an unresolved lookup expression. Suppress
// any lookup-related diagnostics; we'll hash these out later, when
// we've picked a target.
R.suppressDiagnostics();
UnresolvedLookupExpr *ULE
= UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
SS.getWithLocInContext(Context),
R.getLookupNameInfo(),
NeedsADL, R.isOverloadedResult(),
R.begin(), R.end());
return ULE;
}
static void
diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
ValueDecl *var, DeclContext *DC);
/// \brief Complete semantic analysis for a reference to the given declaration.
ExprResult Sema::BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
bool AcceptInvalidDecl) {
assert(D && "Cannot refer to a NULL declaration");
assert(!isa<FunctionTemplateDecl>(D) &&
"Cannot refer unambiguously to a function template");
SourceLocation Loc = NameInfo.getLoc();
if (CheckDeclInExpr(*this, Loc, D))
return ExprError();
if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
// Specifically diagnose references to class templates that are missing
// a template argument list.
Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
<< Template << SS.getRange();
Diag(Template->getLocation(), diag::note_template_decl_here);
return ExprError();
}
// Make sure that we're referring to a value.
ValueDecl *VD = dyn_cast<ValueDecl>(D);
if (!VD) {
Diag(Loc, diag::err_ref_non_value)
<< D << SS.getRange();
Diag(D->getLocation(), diag::note_declared_at);
return ExprError();
}
// Check whether this declaration can be used. Note that we suppress
// this check when we're going to perform argument-dependent lookup
// on this function name, because this might not be the function
// that overload resolution actually selects.
if (DiagnoseUseOfDecl(VD, Loc))
return ExprError();
// Only create DeclRefExpr's for valid Decl's.
if (VD->isInvalidDecl() && !AcceptInvalidDecl)
return ExprError();
// Handle members of anonymous structs and unions. If we got here,
// and the reference is to a class member indirect field, then this
// must be the subject of a pointer-to-member expression.
if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
if (!indirectField->isCXXClassMember())
return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
indirectField);
{
QualType type = VD->getType();
if (auto *FPT = type->getAs<FunctionProtoType>()) {
// C++ [except.spec]p17:
// An exception-specification is considered to be needed when:
// - in an expression, the function is the unique lookup result or
// the selected member of a set of overloaded functions.
ResolveExceptionSpec(Loc, FPT);
type = VD->getType();
}
ExprValueKind valueKind = VK_RValue;
switch (D->getKind()) {
// Ignore all the non-ValueDecl kinds.
#define ABSTRACT_DECL(kind)
#define VALUE(type, base)
#define DECL(type, base) \
case Decl::type:
#include "clang/AST/DeclNodes.inc"
llvm_unreachable("invalid value decl kind");
// These shouldn't make it here.
case Decl::ObjCAtDefsField:
case Decl::ObjCIvar:
llvm_unreachable("forming non-member reference to ivar?");
// Enum constants are always r-values and never references.
// Unresolved using declarations are dependent.
case Decl::EnumConstant:
case Decl::UnresolvedUsingValue:
case Decl::OMPDeclareReduction:
valueKind = VK_RValue;
break;
// Fields and indirect fields that got here must be for
// pointer-to-member expressions; we just call them l-values for
// internal consistency, because this subexpression doesn't really
// exist in the high-level semantics.
case Decl::Field:
case Decl::IndirectField:
assert(getLangOpts().CPlusPlus &&
"building reference to field in C?");
// These can't have reference type in well-formed programs, but
// for internal consistency we do this anyway.
type = type.getNonReferenceType();
valueKind = VK_LValue;
break;
// Non-type template parameters are either l-values or r-values
// depending on the type.
case Decl::NonTypeTemplateParm: {
if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
type = reftype->getPointeeType();
valueKind = VK_LValue; // even if the parameter is an r-value reference
break;
}
// For non-references, we need to strip qualifiers just in case
// the template parameter was declared as 'const int' or whatever.
valueKind = VK_RValue;
type = type.getUnqualifiedType();
break;
}
case Decl::Var:
case Decl::VarTemplateSpecialization:
case Decl::VarTemplatePartialSpecialization:
case Decl::Decomposition:
case Decl::OMPCapturedExpr:
// In C, "extern void blah;" is valid and is an r-value.
if (!getLangOpts().CPlusPlus &&
!type.hasQualifiers() &&
type->isVoidType()) {
valueKind = VK_RValue;
break;
}
// fallthrough
case Decl::ImplicitParam:
case Decl::ParmVar: {
// These are always l-values.
valueKind = VK_LValue;
type = type.getNonReferenceType();
// FIXME: Does the addition of const really only apply in
// potentially-evaluated contexts? Since the variable isn't actually
// captured in an unevaluated context, it seems that the answer is no.
if (!isUnevaluatedContext()) {
QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
if (!CapturedType.isNull())
type = CapturedType;
}
break;
}
case Decl::Binding: {
// These are always lvalues.
valueKind = VK_LValue;
type = type.getNonReferenceType();
// FIXME: Support lambda-capture of BindingDecls, once CWG actually
// decides how that's supposed to work.
auto *BD = cast<BindingDecl>(VD);
if (BD->getDeclContext()->isFunctionOrMethod() &&
BD->getDeclContext() != CurContext)
diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
break;
}
case Decl::Function: {
if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
type = Context.BuiltinFnTy;
valueKind = VK_RValue;
break;
}
}
const FunctionType *fty = type->castAs<FunctionType>();
// If we're referring to a function with an __unknown_anytype
// result type, make the entire expression __unknown_anytype.
if (fty->getReturnType() == Context.UnknownAnyTy) {
type = Context.UnknownAnyTy;
valueKind = VK_RValue;
break;
}
// Functions are l-values in C++.
if (getLangOpts().CPlusPlus) {
valueKind = VK_LValue;
break;
}
// C99 DR 316 says that, if a function type comes from a
// function definition (without a prototype), that type is only
// used for checking compatibility. Therefore, when referencing
// the function, we pretend that we don't have the full function
// type.
if (!cast<FunctionDecl>(VD)->hasPrototype() &&
isa<FunctionProtoType>(fty))
type = Context.getFunctionNoProtoType(fty->getReturnType(),
fty->getExtInfo());
// Functions are r-values in C.
valueKind = VK_RValue;
break;
}
case Decl::CXXDeductionGuide:
llvm_unreachable("building reference to deduction guide");
case Decl::MSProperty:
valueKind = VK_LValue;
break;
case Decl::CXXMethod:
// If we're referring to a method with an __unknown_anytype
// result type, make the entire expression __unknown_anytype.
// This should only be possible with a type written directly.
if (const FunctionProtoType *proto
= dyn_cast<FunctionProtoType>(VD->getType()))
if (proto->getReturnType() == Context.UnknownAnyTy) {
type = Context.UnknownAnyTy;
valueKind = VK_RValue;
break;
}
// C++ methods are l-values if static, r-values if non-static.
if (cast<CXXMethodDecl>(VD)->isStatic()) {
valueKind = VK_LValue;
break;
}
// fallthrough
case Decl::CXXConversion:
case Decl::CXXDestructor:
case Decl::CXXConstructor:
valueKind = VK_RValue;
break;
}
return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
TemplateArgs);
}
}
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
SmallString<32> &Target) {
Target.resize(CharByteWidth * (Source.size() + 1));
char *ResultPtr = &Target[0];
const llvm::UTF8 *ErrorPtr;
bool success =
llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
(void)success;
assert(success);
Target.resize(ResultPtr - &Target[0]);
}
ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentType IT) {
// Pick the current block, lambda, captured statement or function.
Decl *currentDecl = nullptr;
if (const BlockScopeInfo *BSI = getCurBlock())
currentDecl = BSI->TheDecl;
else if (const LambdaScopeInfo *LSI = getCurLambda())
currentDecl = LSI->CallOperator;
else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
currentDecl = CSI->TheCapturedDecl;
else
currentDecl = getCurFunctionOrMethodDecl();
if (!currentDecl) {
Diag(Loc, diag::ext_predef_outside_function);
currentDecl = Context.getTranslationUnitDecl();
}
QualType ResTy;
StringLiteral *SL = nullptr;
if (cast<DeclContext>(currentDecl)->isDependentContext())
ResTy = Context.DependentTy;
else {
// Pre-defined identifiers are of type char[x], where x is the length of
// the string.
auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
unsigned Length = Str.length();
llvm::APInt LengthI(32, Length + 1);
if (IT == PredefinedExpr::LFunction) {
ResTy = Context.WideCharTy.withConst();
SmallString<32> RawChars;
ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
Str, RawChars);
ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
/*IndexTypeQuals*/ 0);
SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
/*Pascal*/ false, ResTy, Loc);
} else {
ResTy = Context.CharTy.withConst();
ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
/*IndexTypeQuals*/ 0);
SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
/*Pascal*/ false, ResTy, Loc);
}
}
return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
}
ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
PredefinedExpr::IdentType IT;
switch (Kind) {
default: llvm_unreachable("Unknown simple primary expr!");
case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
}
return BuildPredefinedExpr(Loc, IT);
}
ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
SmallString<16> CharBuffer;
bool Invalid = false;
StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
if (Invalid)
return ExprError();
CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
PP, Tok.getKind());
if (Literal.hadError())
return ExprError();
QualType Ty;
if (Literal.isWide())
Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
else if (Literal.isUTF16())
Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
else if (Literal.isUTF32())
Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
else
Ty = Context.CharTy; // 'x' -> char in C++
CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
if (Literal.isWide())
Kind = CharacterLiteral::Wide;
else if (Literal.isUTF16())
Kind = CharacterLiteral::UTF16;
else if (Literal.isUTF32())
Kind = CharacterLiteral::UTF32;
else if (Literal.isUTF8())
Kind = CharacterLiteral::UTF8;
Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
Tok.getLocation());
if (Literal.getUDSuffix().empty())
return Lit;
// We're building a user-defined literal.
IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
SourceLocation UDSuffixLoc =
getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
// Make sure we're allowed user-defined literals here.
if (!UDLScope)
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
// C++11 [lex.ext]p6: The literal L is treated as a call of the form
// operator "" X (ch)
return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Lit, Tok.getLocation());
}
ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
unsigned IntSize = Context.getTargetInfo().getIntWidth();
return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
Context.IntTy, Loc);
}
static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
QualType Ty, SourceLocation Loc) {
const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
using llvm::APFloat;
APFloat Val(Format);
APFloat::opStatus result = Literal.GetFloatValue(Val);
// Overflow is always an error, but underflow is only an error if
// we underflowed to zero (APFloat reports denormals as underflow).
if ((result & APFloat::opOverflow) ||
((result & APFloat::opUnderflow) && Val.isZero())) {
unsigned diagnostic;
SmallString<20> buffer;
if (result & APFloat::opOverflow) {
diagnostic = diag::warn_float_overflow;
APFloat::getLargest(Format).toString(buffer);
} else {
diagnostic = diag::warn_float_underflow;
APFloat::getSmallest(Format).toString(buffer);
}
S.Diag(Loc, diagnostic)
<< Ty
<< StringRef(buffer.data(), buffer.size());
}
bool isExact = (result == APFloat::opOK);
return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
}
bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
assert(E && "Invalid expression");
if (E->isValueDependent())
return false;
QualType QT = E->getType();
if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
return true;
}
llvm::APSInt ValueAPS;
ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
if (R.isInvalid())
return true;
bool ValueIsPositive = ValueAPS.isStrictlyPositive();
if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
<< ValueAPS.toString(10) << ValueIsPositive;
return true;
}
return false;
}
ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
// Fast path for a single digit (which is quite common). A single digit
// cannot have a trigraph, escaped newline, radix prefix, or suffix.
if (Tok.getLength() == 1) {
const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
}
SmallString<128> SpellingBuffer;
// NumericLiteralParser wants to overread by one character. Add padding to
// the buffer in case the token is copied to the buffer. If getSpelling()
// returns a StringRef to the memory buffer, it should have a null char at
// the EOF, so it is also safe.
SpellingBuffer.resize(Tok.getLength() + 1);
// Get the spelling of the token, which eliminates trigraphs, etc.
bool Invalid = false;
StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
if (Invalid)
return ExprError();
NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
if (Literal.hadError)
return ExprError();
if (Literal.hasUDSuffix()) {
// We're building a user-defined literal.
IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
SourceLocation UDSuffixLoc =
getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
// Make sure we're allowed user-defined literals here.
if (!UDLScope)
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
QualType CookedTy;
if (Literal.isFloatingLiteral()) {
// C++11 [lex.ext]p4: If S contains a literal operator with parameter type
// long double, the literal is treated as a call of the form
// operator "" X (f L)
CookedTy = Context.LongDoubleTy;
} else {
// C++11 [lex.ext]p3: If S contains a literal operator with parameter type
// unsigned long long, the literal is treated as a call of the form
// operator "" X (n ULL)
CookedTy = Context.UnsignedLongLongTy;
}
DeclarationName OpName =
Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
SourceLocation TokLoc = Tok.getLocation();
// Perform literal operator lookup to determine if we're building a raw
// literal or a cooked one.
LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
switch (LookupLiteralOperator(UDLScope, R, CookedTy,
/*AllowRaw*/true, /*AllowTemplate*/true,
/*AllowStringTemplate*/false)) {
case LOLR_Error:
return ExprError();
case LOLR_Cooked: {
Expr *Lit;
if (Literal.isFloatingLiteral()) {
Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
} else {
llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
if (Literal.GetIntegerValue(ResultVal))
Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
<< /* Unsigned */ 1;
Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
Tok.getLocation());
}
return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
}
case LOLR_Raw: {
// C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
// literal is treated as a call of the form
// operator "" X ("n")
unsigned Length = Literal.getUDSuffixOffset();
QualType StrTy = Context.getConstantArrayType(
Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
ArrayType::Normal, 0);
Expr *Lit = StringLiteral::Create(
Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
/*Pascal*/false, StrTy, &TokLoc, 1);
return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
}
case LOLR_Template: {
// C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
// template), L is treated as a call fo the form
// operator "" X <'c1', 'c2', ... 'ck'>()
// where n is the source character sequence c1 c2 ... ck.
TemplateArgumentListInfo ExplicitArgs;
unsigned CharBits = Context.getIntWidth(Context.CharTy);
bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
llvm::APSInt Value(CharBits, CharIsUnsigned);
for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Value = TokSpelling[I];
TemplateArgument Arg(Context, Value, Context.CharTy);
TemplateArgumentLocInfo ArgInfo;
ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
}
return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
&ExplicitArgs);
}
case LOLR_StringTemplate:
llvm_unreachable("unexpected literal operator lookup result");
}
}
Expr *Res;
if (Literal.isFloatingLiteral()) {
QualType Ty;
if (Literal.isHalf){
if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
Ty = Context.HalfTy;
else {
Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
return ExprError();
}
} else if (Literal.isFloat)
Ty = Context.FloatTy;
else if (Literal.isLong)
Ty = Context.LongDoubleTy;
else if (Literal.isFloat128)
Ty = Context.Float128Ty;
else
Ty = Context.DoubleTy;
Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
if (Ty == Context.DoubleTy) {
if (getLangOpts().SinglePrecisionConstants) {
const BuiltinType *BTy = Ty->getAs<BuiltinType>();
if (BTy->getKind() != BuiltinType::Float) {
Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
}
} else if (getLangOpts().OpenCL &&
!getOpenCLOptions().isEnabled("cl_khr_fp64")) {
// Impose single-precision float type when cl_khr_fp64 is not enabled.
Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
}
}
} else if (!Literal.isIntegerLiteral()) {
return ExprError();
} else {
QualType Ty;
// 'long long' is a C99 or C++11 feature.
if (!getLangOpts().C99 && Literal.isLongLong) {
if (getLangOpts().CPlusPlus)
Diag(Tok.getLocation(),
getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
else
Diag(Tok.getLocation(), diag::ext_c99_longlong);
}
// Get the value in the widest-possible width.
unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
llvm::APInt ResultVal(MaxWidth, 0);
if (Literal.GetIntegerValue(ResultVal)) {
// If this value didn't fit into uintmax_t, error and force to ull.
Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
<< /* Unsigned */ 1;
Ty = Context.UnsignedLongLongTy;
assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?");
} else {
// If this value fits into a ULL, try to figure out what else it fits into
// according to the rules of C99 6.4.4.1p5.
// Octal, Hexadecimal, and integers with a U suffix are allowed to
// be an unsigned int.
bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
// Check from smallest to largest, picking the smallest type we can.
unsigned Width = 0;
// Microsoft specific integer suffixes are explicitly sized.
if (Literal.MicrosoftInteger) {
if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
Width = 8;
Ty = Context.CharTy;
} else {
Width = Literal.MicrosoftInteger;
Ty = Context.getIntTypeForBitwidth(Width,
/*Signed=*/!Literal.isUnsigned);
}
}
if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
// Are int/unsigned possibilities?
unsigned IntSize = Context.getTargetInfo().getIntWidth();
// Does it fit in a unsigned int?
if (ResultVal.isIntN(IntSize)) {
// Does it fit in a signed int?
if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Ty = Context.IntTy;
else if (AllowUnsigned)
Ty = Context.UnsignedIntTy;
Width = IntSize;
}
}
// Are long/unsigned long possibilities?
if (Ty.isNull() && !Literal.isLongLong) {
unsigned LongSize = Context.getTargetInfo().getLongWidth();
// Does it fit in a unsigned long?
if (ResultVal.isIntN(LongSize)) {
// Does it fit in a signed long?
if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Ty = Context.LongTy;
else if (AllowUnsigned)
Ty = Context.UnsignedLongTy;
// Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
// is compatible.
else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
const unsigned LongLongSize =
Context.getTargetInfo().getLongLongWidth();
Diag(Tok.getLocation(),
getLangOpts().CPlusPlus
? Literal.isLong
? diag::warn_old_implicitly_unsigned_long_cxx
: /*C++98 UB*/ diag::
ext_old_implicitly_unsigned_long_cxx
: diag::warn_old_implicitly_unsigned_long)
<< (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
: /*will be ill-formed*/ 1);
Ty = Context.UnsignedLongTy;
}
Width = LongSize;
}
}
// Check long long if needed.
if (Ty.isNull()) {
unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
// Does it fit in a unsigned long long?
if (ResultVal.isIntN(LongLongSize)) {
// Does it fit in a signed long long?
// To be compatible with MSVC, hex integer literals ending with the
// LL or i64 suffix are always signed in Microsoft mode.
if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
(getLangOpts().MSVCCompat && Literal.isLongLong)))
Ty = Context.LongLongTy;
else if (AllowUnsigned)
Ty = Context.UnsignedLongLongTy;
Width = LongLongSize;
}
}
// If we still couldn't decide a type, we probably have something that
// does not fit in a signed long long, but has no U suffix.
if (Ty.isNull()) {
Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
Ty = Context.UnsignedLongLongTy;
Width = Context.getTargetInfo().getLongLongWidth();
}
if (ResultVal.getBitWidth() != Width)
ResultVal = ResultVal.trunc(Width);
}
Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
}
// If this is an imaginary literal, create the ImaginaryLiteral wrapper.
if (Literal.isImaginary)
Res = new (Context) ImaginaryLiteral(Res,
Context.getComplexType(Res->getType()));
return Res;
}
ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
assert(E && "ActOnParenExpr() missing expr");
return new (Context) ParenExpr(L, R, E);
}
static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
SourceLocation Loc,
SourceRange ArgRange) {
// [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
// scalar or vector data type argument..."
// Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
// type (C99 6.2.5p18) or void.
if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
<< T << ArgRange;
return true;
}
assert((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete");
return false;
}
static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
SourceLocation Loc,
SourceRange ArgRange,
UnaryExprOrTypeTrait TraitKind) {
// Invalid types must be hard errors for SFINAE in C++.
if (S.LangOpts.CPlusPlus)
return true;
// C99 6.5.3.4p1:
if (T->isFunctionType() &&
(TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
// sizeof(function)/alignof(function) is allowed as an extension.
S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
<< TraitKind << ArgRange;
return false;
}
// Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
// this is an error (OpenCL v1.1 s6.3.k)
if (T->isVoidType()) {
unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
: diag::ext_sizeof_alignof_void_type;
S.Diag(Loc, DiagID) << TraitKind << ArgRange;
return false;
}
return true;
}
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
SourceLocation Loc,
SourceRange ArgRange,
UnaryExprOrTypeTrait TraitKind) {
// Reject sizeof(interface) and sizeof(interface<proto>) if the
// runtime doesn't allow it.
if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
<< T << (TraitKind == UETT_SizeOf)
<< ArgRange;
return true;
}
return false;
}
/// \brief Check whether E is a pointer from a decayed array type (the decayed
/// pointer type is equal to T) and emit a warning if it is.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
Expr *E) {
// Don't warn if the operation changed the type.
if (T != E->getType())
return;
// Now look for array decays.
ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
return;
S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
<< ICE->getType()
<< ICE->getSubExpr()->getType();
}
/// \brief Check the constraints on expression operands to unary type expression
/// and type traits.
///
/// Completes any types necessary and validates the constraints on the operand
/// expression. The logic mostly mirrors the type-based overload, but may modify
/// the expression as it completes the type for that expression through template
/// instantiation, etc.
bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
UnaryExprOrTypeTrait ExprKind) {
QualType ExprTy = E->getType();
assert(!ExprTy->isReferenceType());
if (ExprKind == UETT_VecStep)
return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
E->getSourceRange());
// Whitelist some types as extensions
if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
E->getSourceRange(), ExprKind))
return false;
// 'alignof' applied to an expression only requires the base element type of
// the expression to be complete. 'sizeof' requires the expression's type to
// be complete (and will attempt to complete it if it's an array of unknown
// bound).
if (ExprKind == UETT_AlignOf) {
if (RequireCompleteType(E->getExprLoc(),
Context.getBaseElementType(E->getType()),
diag::err_sizeof_alignof_incomplete_type, ExprKind,
E->getSourceRange()))
return true;
} else {
if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
ExprKind, E->getSourceRange()))
return true;
}
// Completing the expression's type may have changed it.
ExprTy = E->getType();
assert(!ExprTy->isReferenceType());
if (ExprTy->isFunctionType()) {
Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
<< ExprKind << E->getSourceRange();
return true;
}
// The operand for sizeof and alignof is in an unevaluated expression context,
// so side effects could result in unintended consequences.
if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
!inTemplateInstantiation() && E->HasSideEffects(Context, false))
Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
E->getSourceRange(), ExprKind))
return true;
if (ExprKind == UETT_SizeOf) {
if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
QualType OType = PVD->getOriginalType();
QualType Type = PVD->getType();
if (Type->isPointerType() && OType->isArrayType()) {
Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
<< Type << OType;
Diag(PVD->getLocation(), diag::note_declared_at);
}
}
}
// Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
// decays into a pointer and returns an unintended result. This is most
// likely a typo for "sizeof(array) op x".
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
BO->getLHS());
warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
BO->getRHS());
}
}
return false;
}
/// \brief Check the constraints on operands to unary expression and type
/// traits.
///
/// This will complete any types necessary, and validate the various constraints
/// on those operands.
///
/// The UsualUnaryConversions() function is *not* called by this routine.
/// C99 6.3.2.1p[2-4] all state:
/// Except when it is the operand of the sizeof operator ...
///
/// C++ [expr.sizeof]p4
/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
/// standard conversions are not applied to the operand of sizeof.
///
/// This policy is followed for all of the unary trait expressions.
bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind) {
if (ExprType->isDependentType())
return false;
// C++ [expr.sizeof]p2:
// When applied to a reference or a reference type, the result
// is the size of the referenced type.
// C++11 [expr.alignof]p3:
// When alignof is applied to a reference type, the result
// shall be the alignment of the referenced type.
if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
ExprType = Ref->getPointeeType();
// C11 6.5.3.4/3, C++11 [expr.alignof]p3:
// When alignof or _Alignof is applied to an array type, the result
// is the alignment of the element type.
if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
ExprType = Context.getBaseElementType(ExprType);
if (ExprKind == UETT_VecStep)
return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
// Whitelist some types as extensions
if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
ExprKind))
return false;
if (RequireCompleteType(OpLoc, ExprType,
diag::err_sizeof_alignof_incomplete_type,
ExprKind, ExprRange))
return true;
if (ExprType->isFunctionType()) {
Diag(OpLoc, diag::err_sizeof_alignof_function_type)
<< ExprKind << ExprRange;
return true;
}
if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
ExprKind))
return true;
return false;
}
static bool CheckAlignOfExpr(Sema &S, Expr *E) {
E = E->IgnoreParens();
// Cannot know anything else if the expression is dependent.
if (E->isTypeDependent())
return false;
if (E->getObjectKind() == OK_BitField) {
S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
<< 1 << E->getSourceRange();
return true;
}
ValueDecl *D = nullptr;
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
D = DRE->getDecl();
} else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
D = ME->getMemberDecl();
}
// If it's a field, require the containing struct to have a
// complete definition so that we can compute the layout.
//
// This can happen in C++11 onwards, either by naming the member
// in a way that is not transformed into a member access expression
// (in an unevaluated operand, for instance), or by naming the member
// in a trailing-return-type.
//
// For the record, since __alignof__ on expressions is a GCC
// extension, GCC seems to permit this but always gives the
// nonsensical answer 0.
//
// We don't really need the layout here --- we could instead just
// directly check for all the appropriate alignment-lowing
// attributes --- but that would require duplicating a lot of
// logic that just isn't worth duplicating for such a marginal
// use-case.
if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
// Fast path this check, since we at least know the record has a
// definition if we can find a member of it.
if (!FD->getParent()->isCompleteDefinition()) {
S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
<< E->getSourceRange();
return true;
}
// Otherwise, if it's a field, and the field doesn't have
// reference type, then it must have a complete type (or be a
// flexible array member, which we explicitly want to
// white-list anyway), which makes the following checks trivial.
if (!FD->getType()->isReferenceType())
return false;
}
return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
}
bool Sema::CheckVecStepExpr(Expr *E) {
E = E->IgnoreParens();
// Cannot know anything else if the expression is dependent.
if (E->isTypeDependent())
return false;
return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
}
static void captureVariablyModifiedType(ASTContext &Context, QualType T,
CapturingScopeInfo *CSI) {
assert(T->isVariablyModifiedType());
assert(CSI != nullptr);
// We're going to walk down into the type and look for VLA expressions.
do {
const Type *Ty = T.getTypePtr();
switch (Ty->getTypeClass()) {
#define TYPE(Class, Base)
#define ABSTRACT_TYPE(Class, Base)
#define NON_CANONICAL_TYPE(Class, Base)
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
#include "clang/AST/TypeNodes.def"
T = QualType();
break;
// These types are never variably-modified.
case Type::Builtin:
case Type::Complex:
case Type::Vector:
case Type::ExtVector:
case Type::Record:
case Type::Enum:
case Type::Elaborated:
case Type::TemplateSpecialization:
case Type::ObjCObject:
case Type::ObjCInterface:
case Type::ObjCObjectPointer:
case Type::ObjCTypeParam:
case Type::Pipe:
llvm_unreachable("type class is never variably-modified!");
case Type::Adjusted:
T = cast<AdjustedType>(Ty)->getOriginalType();
break;
case Type::Decayed:
T = cast<DecayedType>(Ty)->getPointeeType();
break;
case Type::Pointer:
T = cast<PointerType>(Ty)->getPointeeType();
break;
case Type::BlockPointer:
T = cast<BlockPointerType>(Ty)->getPointeeType();
break;
case Type::LValueReference:
case Type::RValueReference:
T = cast<ReferenceType>(Ty)->getPointeeType();
break;
case Type::MemberPointer:
T = cast<MemberPointerType>(Ty)->getPointeeType();
break;
case Type::ConstantArray:
case Type::IncompleteArray:
// Losing element qualification here is fine.
T = cast<ArrayType>(Ty)->getElementType();
break;
case Type::VariableArray: {
// Losing element qualification here is fine.
const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
// Unknown size indication requires no size computation.
// Otherwise, evaluate and record it.
if (auto Size = VAT->getSizeExpr()) {
if (!CSI->isVLATypeCaptured(VAT)) {
RecordDecl *CapRecord = nullptr;
if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
CapRecord = LSI->Lambda;
} else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
CapRecord = CRSI->TheRecordDecl;
}
if (CapRecord) {
auto ExprLoc = Size->getExprLoc();
auto SizeType = Context.getSizeType();
// Build the non-static data member.
auto Field =
FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
/*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
/*BW*/ nullptr, /*Mutable*/ false,
/*InitStyle*/ ICIS_NoInit);
Field->setImplicit(true);
Field->setAccess(AS_private);
Field->setCapturedVLAType(VAT);
CapRecord->addDecl(Field);
CSI->addVLATypeCapture(ExprLoc, SizeType);
}
}
}
T = VAT->getElementType();
break;
}
case Type::FunctionProto:
case Type::FunctionNoProto:
T = cast<FunctionType>(Ty)->getReturnType();
break;
case Type::Paren:
case Type::TypeOf:
case Type::UnaryTransform:
case Type::Attributed:
case Type::SubstTemplateTypeParm:
case Type::PackExpansion:
// Keep walking after single level desugaring.
T = T.getSingleStepDesugaredType(Context);
break;
case Type::Typedef:
T = cast<TypedefType>(Ty)->desugar();
break;
case Type::Decltype:
T = cast<DecltypeType>(Ty)->desugar();
break;
case Type::Auto:
case Type::DeducedTemplateSpecialization:
T = cast<DeducedType>(Ty)->getDeducedType();
break;
case Type::TypeOfExpr:
T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
break;
case Type::Atomic:
T = cast<AtomicType>(Ty)->getValueType();
break;
}
} while (!T.isNull() && T->isVariablyModifiedType());
}
/// \brief Build a sizeof or alignof expression given a type operand.
ExprResult
Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R) {
if (!TInfo)
return ExprError();
QualType T = TInfo->getType();
if (!T->isDependentType() &&
CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
return ExprError();
if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
if (auto *TT = T->getAs<TypedefType>()) {
for (auto I = FunctionScopes.rbegin(),
E = std::prev(FunctionScopes.rend());
I != E; ++I) {
auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
if (CSI == nullptr)
break;
DeclContext *DC = nullptr;
if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
DC = LSI->CallOperator;
else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
DC = CRSI->TheCapturedDecl;
else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
DC = BSI->TheDecl;
if (DC) {
if (DC->containsDecl(TT->getDecl()))
break;
captureVariablyModifiedType(Context, T, CSI);
}
}
}
}
// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
return new (Context) UnaryExprOrTypeTraitExpr(
ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
}
/// \brief Build a sizeof or alignof expression given an expression
/// operand.
ExprResult
Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind) {
ExprResult PE = CheckPlaceholderExpr(E);
if (PE.isInvalid())
return ExprError();
E = PE.get();
// Verify that the operand is valid.
bool isInvalid = false;
if (E->isTypeDependent()) {
// Delay type-checking for type-dependent expressions.
} else if (ExprKind == UETT_AlignOf) {
isInvalid = CheckAlignOfExpr(*this, E);
} else if (ExprKind == UETT_VecStep) {
isInvalid = CheckVecStepExpr(E);
} else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
isInvalid = true;
} else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
isInvalid = true;
} else {
isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
}
if (isInvalid)
return ExprError();
if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
PE = TransformToPotentiallyEvaluated(E);
if (PE.isInvalid()) return ExprError();
E = PE.get();
}
// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
return new (Context) UnaryExprOrTypeTraitExpr(
ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
}
/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
/// expr and the same for @c alignof and @c __alignof
/// Note that the ArgRange is invalid if isType is false.
ExprResult
Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind, bool IsType,
void *TyOrEx, SourceRange ArgRange) {
// If error parsing type, ignore.
if (!TyOrEx) return ExprError();
if (IsType) {
TypeSourceInfo *TInfo;
(void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
}
Expr *ArgEx = (Expr *)TyOrEx;
ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
return Result;
}
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
bool IsReal) {
if (V.get()->isTypeDependent())
return S.Context.DependentTy;
// _Real and _Imag are only l-values for normal l-values.
if (V.get()->getObjectKind() != OK_Ordinary) {
V = S.DefaultLvalueConversion(V.get());
if (V.isInvalid())
return QualType();
}
// These operators return the element type of a complex type.
if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
return CT->getElementType();
// Otherwise they pass through real integer and floating point types here.
if (V.get()->getType()->isArithmeticType())
return V.get()->getType();
// Test for placeholders.
ExprResult PR = S.CheckPlaceholderExpr(V.get());
if (PR.isInvalid()) return QualType();
if (PR.get() != V.get()) {
V = PR;
return CheckRealImagOperand(S, V, Loc, IsReal);
}
// Reject anything else.
S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
<< (IsReal ? "__real" : "__imag");
return QualType();
}
ExprResult
Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input) {
UnaryOperatorKind Opc;
switch (Kind) {
default: llvm_unreachable("Unknown unary op!");
case tok::plusplus: Opc = UO_PostInc; break;
case tok::minusminus: Opc = UO_PostDec; break;
}
// Since this might is a postfix expression, get rid of ParenListExprs.
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
if (Result.isInvalid()) return ExprError();
Input = Result.get();
return BuildUnaryOp(S, OpLoc, Opc, Input);
}
/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
///
/// \return true on error
static bool checkArithmeticOnObjCPointer(Sema &S,
SourceLocation opLoc,
Expr *op) {
assert(op->getType()->isObjCObjectPointerType());
if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
!S.LangOpts.ObjCSubscriptingLegacyRuntime)
return false;
S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
<< op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
<< op->getSourceRange();
return true;
}
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
auto *BaseNoParens = Base->IgnoreParens();
if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
return MSProp->getPropertyDecl()->getType()->isArrayType();
return isa<MSPropertySubscriptExpr>(BaseNoParens);
}
ExprResult
Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
Expr *idx, SourceLocation rbLoc) {
if (base && !base->getType().isNull() &&
base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
/*Length=*/nullptr, rbLoc);
// Since this might be a postfix expression, get rid of ParenListExprs.
if (isa<ParenListExpr>(base)) {
ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
if (result.isInvalid()) return ExprError();
base = result.get();
}
// Handle any non-overload placeholder types in the base and index
// expressions. We can't handle overloads here because the other
// operand might be an overloadable type, in which case the overload
// resolution for the operator overload should get the first crack
// at the overload.
bool IsMSPropertySubscript = false;
if (base->getType()->isNonOverloadPlaceholderType()) {
IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
if (!IsMSPropertySubscript) {
ExprResult result = CheckPlaceholderExpr(base);
if (result.isInvalid())
return ExprError();
base = result.get();
}
}
if (idx->getType()->isNonOverloadPlaceholderType()) {
ExprResult result = CheckPlaceholderExpr(idx);
if (result.isInvalid()) return ExprError();
idx = result.get();
}
// Build an unanalyzed expression if either operand is type-dependent.
if (getLangOpts().CPlusPlus &&
(base->isTypeDependent() || idx->isTypeDependent())) {
return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
VK_LValue, OK_Ordinary, rbLoc);
}
// MSDN, property (C++)
// https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
// This attribute can also be used in the declaration of an empty array in a
// class or structure definition. For example:
// __declspec(property(get=GetX, put=PutX)) int x[];
// The above statement indicates that x[] can be used with one or more array
// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
// and p->x[a][b] = i will be turned into p->PutX(a, b, i);
if (IsMSPropertySubscript) {
// Build MS property subscript expression if base is MS property reference
// or MS property subscript.
return new (Context) MSPropertySubscriptExpr(
base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
}
// Use C++ overloaded-operator rules if either operand has record
// type. The spec says to do this if either type is *overloadable*,
// but enum types can't declare subscript operators or conversion
// operators, so there's nothing interesting for overload resolution
// to do if there aren't any record types involved.
//
// ObjC pointers have their own subscripting logic that is not tied
// to overload resolution and so should not take this path.
if (getLangOpts().CPlusPlus &&
(base->getType()->isRecordType() ||
(!base->getType()->isObjCObjectPointerType() &&
idx->getType()->isRecordType()))) {
return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
}
return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
}
ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound,
SourceLocation ColonLoc, Expr *Length,
SourceLocation RBLoc) {
if (Base->getType()->isPlaceholderType() &&
!Base->getType()->isSpecificPlaceholderType(
BuiltinType::OMPArraySection)) {
ExprResult Result = CheckPlaceholderExpr(Base);
if (Result.isInvalid())
return ExprError();
Base = Result.get();
}
if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
ExprResult Result = CheckPlaceholderExpr(LowerBound);
if (Result.isInvalid())
return ExprError();
Result = DefaultLvalueConversion(Result.get());
if (Result.isInvalid())
return ExprError();
LowerBound = Result.get();
}
if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
ExprResult Result = CheckPlaceholderExpr(Length);
if (Result.isInvalid())
return ExprError();
Result = DefaultLvalueConversion(Result.get());
if (Result.isInvalid())
return ExprError();
Length = Result.get();
}
// Build an unanalyzed expression if either operand is type-dependent.
if (Base->isTypeDependent() ||
(LowerBound &&
(LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
(Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
return new (Context)
OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
}
// Perform default conversions.
QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
QualType ResultTy;
if (OriginalTy->isAnyPointerType()) {
ResultTy = OriginalTy->getPointeeType();
} else if (OriginalTy->isArrayType()) {
ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
} else {
return ExprError(
Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
<< Base->getSourceRange());
}
// C99 6.5.2.1p1
if (LowerBound) {
auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
LowerBound);
if (Res.isInvalid())
return ExprError(Diag(LowerBound->getExprLoc(),
diag::err_omp_typecheck_section_not_integer)
<< 0 << LowerBound->getSourceRange());
LowerBound = Res.get();
if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
<< 0 << LowerBound->getSourceRange();
}
if (Length) {
auto Res =
PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
if (Res.isInvalid())
return ExprError(Diag(Length->getExprLoc(),
diag::err_omp_typecheck_section_not_integer)
<< 1 << Length->getSourceRange());
Length = Res.get();
if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
<< 1 << Length->getSourceRange();
}
// C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
// C++ [expr.sub]p1: The type "T" shall be a completely-defined object
// type. Note that functions are not objects, and that (in C99 parlance)
// incomplete types are not object types.
if (ResultTy->isFunctionType()) {
Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
<< ResultTy << Base->getSourceRange();
return ExprError();
}
if (RequireCompleteType(Base->getExprLoc(), ResultTy,
diag::err_omp_section_incomplete_type, Base))
return ExprError();
if (LowerBound && !OriginalTy->isAnyPointerType()) {
llvm::APSInt LowerBoundValue;
if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
// OpenMP 4.5, [2.4 Array Sections]
// The array section must be a subset of the original array.
if (LowerBoundValue.isNegative()) {
Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
<< LowerBound->getSourceRange();
return ExprError();
}
}
}
if (Length) {
llvm::APSInt LengthValue;
if (Length->EvaluateAsInt(LengthValue, Context)) {
// OpenMP 4.5, [2.4 Array Sections]
// The length must evaluate to non-negative integers.
if (LengthValue.isNegative()) {
Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
<< LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
<< Length->getSourceRange();
return ExprError();
}
}
} else if (ColonLoc.isValid() &&
(OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
!OriginalTy->isVariableArrayType()))) {
// OpenMP 4.5, [2.4 Array Sections]
// When the size of the array dimension is not known, the length must be
// specified explicitly.
Diag(ColonLoc, diag::err_omp_section_length_undefined)
<< (!OriginalTy.isNull() && OriginalTy->isArrayType());
return ExprError();
}
if (!Base->getType()->isSpecificPlaceholderType(
BuiltinType::OMPArraySection)) {
ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
if (Result.isInvalid())
return ExprError();
Base = Result.get();
}
return new (Context)
OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
}
ExprResult
Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc) {
Expr *LHSExp = Base;
Expr *RHSExp = Idx;
ExprValueKind VK = VK_LValue;
ExprObjectKind OK = OK_Ordinary;
// Per C++ core issue 1213, the result is an xvalue if either operand is
// a non-lvalue array, and an lvalue otherwise.
if (getLangOpts().CPlusPlus11 &&
((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
(RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
VK = VK_XValue;
// Perform default conversions.
if (!LHSExp->getType()->getAs<VectorType>()) {
ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
if (Result.isInvalid())
return ExprError();
LHSExp = Result.get();
}
ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
if (Result.isInvalid())
return ExprError();
RHSExp = Result.get();
QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
// C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
// to the expression *((e1)+(e2)). This means the array "Base" may actually be
// in the subscript position. As a result, we need to derive the array base
// and index from the expression types.
Expr *BaseExpr, *IndexExpr;
QualType ResultType;
if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
BaseExpr = LHSExp;
IndexExpr = RHSExp;
ResultType = Context.DependentTy;
} else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
BaseExpr = LHSExp;
IndexExpr = RHSExp;
ResultType = PTy->getPointeeType();
} else if (const ObjCObjectPointerType *PTy =
LHSTy->getAs<ObjCObjectPointerType>()) {
BaseExpr = LHSExp;
IndexExpr = RHSExp;
// Use custom logic if this should be the pseudo-object subscript
// expression.
if (!LangOpts.isSubscriptPointerArithmetic())
return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
nullptr);
ResultType = PTy->getPointeeType();
} else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
// Handle the uncommon case of "123[Ptr]".
BaseExpr = RHSExp;
IndexExpr = LHSExp;
ResultType = PTy->getPointeeType();
} else if (const ObjCObjectPointerType *PTy =
RHSTy->getAs<ObjCObjectPointerType>()) {
// Handle the uncommon case of "123[Ptr]".
BaseExpr = RHSExp;
IndexExpr = LHSExp;
ResultType = PTy->getPointeeType();
if (!LangOpts.isSubscriptPointerArithmetic()) {
Diag(LLoc, diag::err_subscript_nonfragile_interface)
<< ResultType << BaseExpr->getSourceRange();
return ExprError();
}
} else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
BaseExpr = LHSExp; // vectors: V[123]
IndexExpr = RHSExp;
VK = LHSExp->getValueKind();
if (VK != VK_RValue)
OK = OK_VectorComponent;
// FIXME: need to deal with const...
ResultType = VTy->getElementType();
} else if (LHSTy->isArrayType()) {
// If we see an array that wasn't promoted by
// DefaultFunctionArrayLvalueConversion, it must be an array that
// wasn't promoted because of the C90 rule that doesn't
// allow promoting non-lvalue arrays. Warn, then
// force the promotion here.
Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
LHSExp->getSourceRange();
LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
CK_ArrayToPointerDecay).get();
LHSTy = LHSExp->getType();
BaseExpr = LHSExp;
IndexExpr = RHSExp;
ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
} else if (RHSTy->isArrayType()) {
// Same as previous, except for 123[f().a] case
Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
RHSExp->getSourceRange();
RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
CK_ArrayToPointerDecay).get();
RHSTy = RHSExp->getType();
BaseExpr = RHSExp;
IndexExpr = LHSExp;
ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
} else {
return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
<< LHSExp->getSourceRange() << RHSExp->getSourceRange());
}
// C99 6.5.2.1p1
if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
<< IndexExpr->getSourceRange());
if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
&& !IndexExpr->isTypeDependent())
Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
// C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
// C++ [expr.sub]p1: The type "T" shall be a completely-defined object
// type. Note that Functions are not objects, and that (in C99 parlance)
// incomplete types are not object types.
if (ResultType->isFunctionType()) {
Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
<< ResultType << BaseExpr->getSourceRange();
return ExprError();
}
if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
// GNU extension: subscripting on pointer to void
Diag(LLoc, diag::ext_gnu_subscript_void_type)
<< BaseExpr->getSourceRange();
// C forbids expressions of unqualified void type from being l-values.
// See IsCForbiddenLValueType.
if (!ResultType.hasQualifiers()) VK = VK_RValue;
} else if (!ResultType->isDependentType() &&
RequireCompleteType(LLoc, ResultType,
diag::err_subscript_incomplete_type, BaseExpr))
return ExprError();
assert(VK == VK_RValue || LangOpts.CPlusPlus ||
!ResultType.isCForbiddenLValueType());
return new (Context)
ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
}
bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param) {
if (Param->hasUnparsedDefaultArg()) {
Diag(CallLoc,
diag::err_use_of_default_argument_to_function_declared_later) <<
FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Diag(UnparsedDefaultArgLocs[Param],
diag::note_default_argument_declared_here);
return true;
}
if (Param->hasUninstantiatedDefaultArg()) {
Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
EnterExpressionEvaluationContext EvalContext(
*this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
// Instantiate the expression.
MultiLevelTemplateArgumentList MutiLevelArgList
= getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
InstantiatingTemplate Inst(*this, CallLoc, Param,
MutiLevelArgList.getInnermost());
if (Inst.isInvalid())
return true;
if (Inst.isAlreadyInstantiating()) {
Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
Param->setInvalidDecl();
return true;
}
ExprResult Result;
{
// C++ [dcl.fct.default]p5:
// The names in the [default argument] expression are bound, and
// the semantic constraints are checked, at the point where the
// default argument expression appears.
ContextRAII SavedContext(*this, FD);
LocalInstantiationScope Local(*this);
Result = SubstInitializer(UninstExpr, MutiLevelArgList,
/*DirectInit*/false);
}
if (Result.isInvalid())
return true;
// Check the expression as an initializer for the parameter.
InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context, Param);
InitializationKind Kind
= InitializationKind::CreateCopy(Param->getLocation(),
/*FIXME:EqualLoc*/UninstExpr->getLocStart());
Expr *ResultE = Result.getAs<Expr>();
InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
if (Result.isInvalid())
return true;
Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
Param->getOuterLocStart());
if (Result.isInvalid())
return true;
// Remember the instantiated default argument.
Param->setDefaultArg(Result.getAs<Expr>());
if (ASTMutationListener *L = getASTMutationListener()) {
L->DefaultArgumentInstantiated(Param);
}
}
// If the default argument expression is not set yet, we are building it now.
if (!Param->hasInit()) {
Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
Param->setInvalidDecl();
return true;
}
// If the default expression creates temporaries, we need to
// push them to the current stack of expression temporaries so they'll
// be properly destroyed.
// FIXME: We should really be rebuilding the default argument with new
// bound temporaries; see the comment in PR5810.
// We don't need to do that with block decls, though, because
// blocks in default argument expression can never capture anything.
if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
// Set the "needs cleanups" bit regardless of whether there are
// any explicit objects.
Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
// Append all the objects to the cleanup list. Right now, this
// should always be a no-op, because blocks in default argument
// expressions should never be able to capture anything.
assert(!Init->getNumObjects() &&
"default argument expression has capturing blocks?");
}
// We already type-checked the argument, so we know it works.
// Just mark all of the declarations in this potentially-evaluated expression
// as being "referenced".
MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
/*SkipLocalVariables=*/true);
return false;
}
ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD, ParmVarDecl *Param) {
if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
return ExprError();
return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
}
Sema::VariadicCallType
Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
Expr *Fn) {
if (Proto && Proto->isVariadic()) {
if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
return VariadicConstructor;
else if (Fn && Fn->getType()->isBlockPointerType())
return VariadicBlock;
else if (FDecl) {
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
if (Method->isInstance())
return VariadicMethod;
} else if (Fn && Fn->getType() == Context.BoundMemberTy)
return VariadicMethod;
return VariadicFunction;
}
return VariadicDoesNotApply;
}
namespace {
class FunctionCallCCC : public FunctionCallFilterCCC {
public:
FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
unsigned NumArgs, MemberExpr *ME)
: FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
FunctionName(FuncName) {}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (!candidate.getCorrectionSpecifier() ||
candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
return false;
}
return FunctionCallFilterCCC::ValidateCandidate(candidate);
}
private:
const IdentifierInfo *const FunctionName;
};
}
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
FunctionDecl *FDecl,
ArrayRef<Expr *> Args) {
MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
DeclarationName FuncName = FDecl->getDeclName();
SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
if (TypoCorrection Corrected = S.CorrectTypo(
DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
S.getScopeForContext(S.CurContext), nullptr,
llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
Args.size(), ME),
Sema::CTK_ErrorRecovery)) {
if (NamedDecl *ND = Corrected.getFoundDecl()) {
if (Corrected.isOverloaded()) {
OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
OverloadCandidateSet::iterator Best;
for (NamedDecl *CD : Corrected) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
OCS);
}
switch (OCS.BestViableFunction(S, NameLoc, Best)) {
case OR_Success:
ND = Best->FoundDecl;
Corrected.setCorrectionDecl(ND);
break;
default:
break;
}
}
ND = ND->getUnderlyingDecl();
if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
return Corrected;
}
}
return TypoCorrection();
}
/// ConvertArgumentsForCall - Converts the arguments specified in
/// Args/NumArgs to the parameter types of the function FDecl with
/// function prototype Proto. Call is the call expression itself, and
/// Fn is the function expression. For a C++ member function, this
/// routine does not attempt to convert the object argument. Returns
/// true if the call is ill-formed.
bool
Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool IsExecConfig) {
// Bail out early if calling a builtin with custom typechecking.
if (FDecl)
if (unsigned ID = FDecl->getBuiltinID())
if (Context.BuiltinInfo.hasCustomTypechecking(ID))
return false;
// C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
// assignment, to the types of the corresponding parameter, ...
unsigned NumParams = Proto->getNumParams();
bool Invalid = false;
unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
unsigned FnKind = Fn->getType()->isBlockPointerType()
? 1 /* block */
: (IsExecConfig ? 3 /* kernel function (exec config) */
: 0 /* function */);
// If too few arguments are available (and we don't have default
// arguments for the remaining parameters), don't make the call.
if (Args.size() < NumParams) {
if (Args.size() < MinArgs) {
TypoCorrection TC;
if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
unsigned diag_id =
MinArgs == NumParams && !Proto->isVariadic()
? diag::err_typecheck_call_too_few_args_suggest
: diag::err_typecheck_call_too_few_args_at_least_suggest;
diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
<< static_cast<unsigned>(Args.size())
<< TC.getCorrectionRange());
} else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Diag(RParenLoc,
MinArgs == NumParams && !Proto->isVariadic()
? diag::err_typecheck_call_too_few_args_one
: diag::err_typecheck_call_too_few_args_at_least_one)
<< FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
else
Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
? diag::err_typecheck_call_too_few_args
: diag::err_typecheck_call_too_few_args_at_least)
<< FnKind << MinArgs << static_cast<unsigned>(Args.size())
<< Fn->getSourceRange();
// Emit the location of the prototype.
if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Diag(FDecl->getLocStart(), diag::note_callee_decl)
<< FDecl;
return true;
}
Call->setNumArgs(Context, NumParams);
}
// If too many are passed and not variadic, error on the extras and drop
// them.
if (Args.size() > NumParams) {
if (!Proto->isVariadic()) {
TypoCorrection TC;
if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
unsigned diag_id =
MinArgs == NumParams && !Proto->isVariadic()
? diag::err_typecheck_call_too_many_args_suggest
: diag::err_typecheck_call_too_many_args_at_most_suggest;
diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
<< static_cast<unsigned>(Args.size())
<< TC.getCorrectionRange());
} else if (NumParams == 1 && FDecl &&
FDecl->getParamDecl(0)->getDeclName())
Diag(Args[NumParams]->getLocStart(),
MinArgs == NumParams
? diag::err_typecheck_call_too_many_args_one
: diag::err_typecheck_call_too_many_args_at_most_one)
<< FnKind << FDecl->getParamDecl(0)
<< static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
<< SourceRange(Args[NumParams]->getLocStart(),
Args.back()->getLocEnd());
else
Diag(Args[NumParams]->getLocStart(),
MinArgs == NumParams
? diag::err_typecheck_call_too_many_args
: diag::err_typecheck_call_too_many_args_at_most)
<< FnKind << NumParams << static_cast<unsigned>(Args.size())
<< Fn->getSourceRange()
<< SourceRange(Args[NumParams]->getLocStart(),
Args.back()->getLocEnd());
// Emit the location of the prototype.
if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Diag(FDecl->getLocStart(), diag::note_callee_decl)
<< FDecl;
// This deletes the extra arguments.
Call->setNumArgs(Context, NumParams);
return true;
}
}
SmallVector<Expr *, 8> AllArgs;
VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Proto, 0, Args, AllArgs, CallType);
if (Invalid)
return true;
unsigned TotalNumArgs = AllArgs.size();
for (unsigned i = 0; i < TotalNumArgs; ++i)
Call->setArg(i, AllArgs[i]);
return false;
}
bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType, bool AllowExplicit,
bool IsListInitialization) {
unsigned NumParams = Proto->getNumParams();
bool Invalid = false;
size_t ArgIx = 0;
// Continue to check argument types (even if we have too few/many args).
for (unsigned i = FirstParam; i < NumParams; i++) {
QualType ProtoArgType = Proto->getParamType(i);
Expr *Arg;
ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
if (ArgIx < Args.size()) {
Arg = Args[ArgIx++];
if (RequireCompleteType(Arg->getLocStart(),
ProtoArgType,
diag::err_call_incomplete_argument, Arg))
return true;
// Strip the unbridged-cast placeholder expression off, if applicable.
bool CFAudited = false;
if (Arg->getType() == Context.ARCUnbridgedCastTy &&
FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
(!Param || !Param->hasAttr<CFConsumedAttr>()))
Arg = stripARCUnbridgedCast(Arg);
else if (getLangOpts().ObjCAutoRefCount &&
FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
(!Param || !Param->hasAttr<CFConsumedAttr>()))
CFAudited = true;
InitializedEntity Entity =
Param ? InitializedEntity::InitializeParameter(Context, Param,
ProtoArgType)
: InitializedEntity::InitializeParameter(
Context, ProtoArgType, Proto->isParamConsumed(i));
// Remember that parameter belongs to a CF audited API.
if (CFAudited)
Entity.setParameterCFAudited();
ExprResult ArgE = PerformCopyInitialization(
Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
if (ArgE.isInvalid())
return true;
Arg = ArgE.getAs<Expr>();
} else {
assert(Param && "can't use default arguments without a known callee");
ExprResult ArgExpr =
BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
if (ArgExpr.isInvalid())
return true;
Arg = ArgExpr.getAs<Expr>();
}
// Check for array bounds violations for each argument to the call. This
// check only triggers warnings when the argument isn't a more complex Expr
// with its own checking, such as a BinaryOperator.
CheckArrayAccess(Arg);
// Check for violations of C99 static array rules (C99 6.7.5.3p7).
CheckStaticArrayArgument(CallLoc, Param, Arg);
AllArgs.push_back(Arg);
}
// If this is a variadic call, handle args passed through "...".
if (CallType != VariadicDoesNotApply) {
// Assume that extern "C" functions with variadic arguments that
// return __unknown_anytype aren't *really* variadic.
if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
FDecl->isExternC()) {
for (Expr *A : Args.slice(ArgIx)) {
QualType paramType; // ignored
ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
Invalid |= arg.isInvalid();
AllArgs.push_back(arg.get());
}
// Otherwise do argument promotion, (C99 6.5.2.2p7).
} else {
for (Expr *A : Args.slice(ArgIx)) {
ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
Invalid |= Arg.isInvalid();
AllArgs.push_back(Arg.get());
}
}
// Check for array bounds violations.
for (Expr *A : Args.slice(ArgIx))
CheckArrayAccess(A);
}
return Invalid;
}
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
TL = DTL.getOriginalLoc();
if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
S.Diag(PVD->getLocation(), diag::note_callee_static_array)
<< ATL.getLocalSourceRange();
}
/// CheckStaticArrayArgument - If the given argument corresponds to a static
/// array parameter, check that it is non-null, and that if it is formed by
/// array-to-pointer decay, the underlying array is sufficiently large.
///
/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
/// array type derivation, then for each call to the function, the value of the
/// corresponding actual argument shall provide access to the first element of
/// an array with at least as many elements as specified by the size expression.
void
Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr) {
// Static array parameters are not supported in C++.
if (!Param || getLangOpts().CPlusPlus)
return;
QualType OrigTy = Param->getOriginalType();
const ArrayType *AT = Context.getAsArrayType(OrigTy);
if (!AT || AT->getSizeModifier() != ArrayType::Static)
return;
if (ArgExpr->isNullPointerConstant(Context,
Expr::NPC_NeverValueDependent)) {
Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
DiagnoseCalleeStaticArrayParam(*this, Param);
return;
}
const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
if (!CAT)
return;
const ConstantArrayType *ArgCAT =
Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
if (!ArgCAT)
return;
if (ArgCAT->getSize().ult(CAT->getSize())) {
Diag(CallLoc, diag::warn_static_array_too_small)
<< ArgExpr->getSourceRange()
<< (unsigned) ArgCAT->getSize().getZExtValue()
<< (unsigned) CAT->getSize().getZExtValue();
DiagnoseCalleeStaticArrayParam(*this, Param);
}
}
/// Given a function expression of unknown-any type, try to rebuild it
/// to have a function type.
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
/// Is the given type a placeholder that we need to lower out
/// immediately during argument processing?
static bool isPlaceholderToRemoveAsArg(QualType type) {
// Placeholders are never sugared.
const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
if (!placeholder) return false;
switch (placeholder->getKind()) {
// Ignore all the non-placeholder types.
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
case BuiltinType::Id:
#include "clang/Basic/OpenCLImageTypes.def"
#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
#include "clang/AST/BuiltinTypes.def"
return false;
// We cannot lower out overload sets; they might validly be resolved
// by the call machinery.
case BuiltinType::Overload:
return false;
// Unbridged casts in ARC can be handled in some call positions and
// should be left in place.
case BuiltinType::ARCUnbridgedCast:
return false;
// Pseudo-objects should be converted as soon as possible.
case BuiltinType::PseudoObject:
return true;
// The debugger mode could theoretically but currently does not try
// to resolve unknown-typed arguments based on known parameter types.
case BuiltinType::UnknownAny:
return true;
// These are always invalid as call arguments and should be reported.
case BuiltinType::BoundMember:
case BuiltinType::BuiltinFn:
case BuiltinType::OMPArraySection:
return true;
}
llvm_unreachable("bad builtin type kind");
}
/// Check an argument list for placeholders that we won't try to
/// handle later.
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
// Apply this processing to all the arguments at once instead of
// dying at the first failure.
bool hasInvalid = false;
for (size_t i = 0, e = args.size(); i != e; i++) {
if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
ExprResult result = S.CheckPlaceholderExpr(args[i]);
if (result.isInvalid()) hasInvalid = true;
else args[i] = result.get();
} else if (hasInvalid) {
(void)S.CorrectDelayedTyposInExpr(args[i]);
}
}
return hasInvalid;
}
/// If a builtin function has a pointer argument with no explicit address
/// space, then it should be able to accept a pointer to any address
/// space as input. In order to do this, we need to replace the
/// standard builtin declaration with one that uses the same address space
/// as the call.
///
/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
/// it does not contain any pointer arguments without
/// an address space qualifer. Otherwise the rewritten
/// FunctionDecl is returned.
/// TODO: Handle pointer return types.
static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
const FunctionDecl *FDecl,
MultiExprArg ArgExprs) {
QualType DeclType = FDecl->getType();
const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
!FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
return nullptr;
bool NeedsNewDecl = false;
unsigned i = 0;
SmallVector<QualType, 8> OverloadParams;
for (QualType ParamType : FT->param_types()) {
// Convert array arguments to pointer to simplify type lookup.
ExprResult ArgRes =
Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
if (ArgRes.isInvalid())
return nullptr;
Expr *Arg = ArgRes.get();
QualType ArgType = Arg->getType();
if (!ParamType->isPointerType() ||
ParamType.getQualifiers().hasAddressSpace() ||
!ArgType->isPointerType() ||
!ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
OverloadParams.push_back(ParamType);
continue;
}
NeedsNewDecl = true;
unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
QualType PointeeType = ParamType->getPointeeType();
PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
OverloadParams.push_back(Context.getPointerType(PointeeType));
}
if (!NeedsNewDecl)
return nullptr;
FunctionProtoType::ExtProtoInfo EPI;
QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
OverloadParams, EPI);
DeclContext *Parent = Context.getTranslationUnitDecl();
FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
FDecl->getLocation(),
FDecl->getLocation(),
FDecl->getIdentifier(),
OverloadTy,
/*TInfo=*/nullptr,
SC_Extern, false,
/*hasPrototype=*/true);
SmallVector<ParmVarDecl*, 16> Params;
FT = cast<FunctionProtoType>(OverloadTy);
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
QualType ParamType = FT->getParamType(i);
ParmVarDecl *Parm =
ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
SourceLocation(), nullptr, ParamType,
/*TInfo=*/nullptr, SC_None, nullptr);
Parm->setScopeInfo(0, i);
Params.push_back(Parm);
}
OverloadDecl->setParams(Params);
return OverloadDecl;
}
static void checkDirectCallValidity(Sema &S, const Expr *Fn,
FunctionDecl *Callee,
MultiExprArg ArgExprs) {
// `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
// similar attributes) really don't like it when functions are called with an
// invalid number of args.
if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
/*PartialOverloading=*/false) &&
!Callee->isVariadic())
return;
if (Callee->getMinRequiredArguments() > ArgExprs.size())
return;
if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
S.Diag(Fn->getLocStart(),
isa<CXXMethodDecl>(Callee)
? diag::err_ovl_no_viable_member_function_in_call
: diag::err_ovl_no_viable_function_in_call)
<< Callee << Callee->getSourceRange();
S.Diag(Callee->getLocation(),
diag::note_ovl_candidate_disabled_by_function_cond_attr)
<< Attr->getCond()->getSourceRange() << Attr->getMessage();
return;
}
}
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig, bool IsExecConfig) {
// Since this might be a postfix expression, get rid of ParenListExprs.
ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
if (Result.isInvalid()) return ExprError();
Fn = Result.get();
if (checkArgsForPlaceholders(*this, ArgExprs))
return ExprError();
if (getLangOpts().CPlusPlus) {
// If this is a pseudo-destructor expression, build the call immediately.
if (isa<CXXPseudoDestructorExpr>(Fn)) {
if (!ArgExprs.empty()) {
// Pseudo-destructor calls should not have any arguments.
Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
<< FixItHint::CreateRemoval(
SourceRange(ArgExprs.front()->getLocStart(),
ArgExprs.back()->getLocEnd()));
}
return new (Context)
CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
}
if (Fn->getType() == Context.PseudoObjectTy) {
ExprResult result = CheckPlaceholderExpr(Fn);
if (result.isInvalid()) return ExprError();
Fn = result.get();
}
// Determine whether this is a dependent call inside a C++ template,
// in which case we won't do any semantic analysis now.
bool Dependent = false;
if (Fn->isTypeDependent())
Dependent = true;
else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Dependent = true;
if (Dependent) {
if (ExecConfig) {
return new (Context) CUDAKernelCallExpr(
Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Context.DependentTy, VK_RValue, RParenLoc);
} else {
return new (Context) CallExpr(
Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
}
}
// Determine whether this is a call to an object (C++ [over.call.object]).
if (Fn->getType()->isRecordType())
return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
RParenLoc);
if (Fn->getType() == Context.UnknownAnyTy) {
ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
if (result.isInvalid()) return ExprError();
Fn = result.get();
}
if (Fn->getType() == Context.BoundMemberTy) {
return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
RParenLoc);
}
}
// Check for overloaded calls. This can happen even in C due to extensions.
if (Fn->getType() == Context.OverloadTy) {
OverloadExpr::FindResult find = OverloadExpr::find(Fn);
// We aren't supposed to apply this logic for if there'Scope an '&'
// involved.
if (!find.HasFormOfMemberPointer) {
OverloadExpr *ovl = find.Expression;
if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
return BuildOverloadedCallExpr(
Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
/*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
RParenLoc);
}
}
// If we're directly calling a function, get the appropriate declaration.
if (Fn->getType() == Context.UnknownAnyTy) {
ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
if (result.isInvalid()) return ExprError();
Fn = result.get();
}
Expr *NakedFn = Fn->IgnoreParens();
bool CallingNDeclIndirectly = false;
NamedDecl *NDecl = nullptr;
if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
if (UnOp->getOpcode() == UO_AddrOf) {
CallingNDeclIndirectly = true;
NakedFn = UnOp->getSubExpr()->IgnoreParens();
}
}
if (isa<DeclRefExpr>(NakedFn)) {
NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
if (FDecl && FDecl->getBuiltinID()) {
// Rewrite the function decl for this builtin by replacing parameters
// with no explicit address space with the address space of the arguments
// in ArgExprs.
if ((FDecl =
rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
NDecl = FDecl;
Fn = DeclRefExpr::Create(
Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
}
}
} else if (isa<MemberExpr>(NakedFn))
NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
if (CallingNDeclIndirectly &&
!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Fn->getLocStart()))
return ExprError();
if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
return ExprError();
checkDirectCallValidity(*this, Fn, FD, ArgExprs);
}
return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
ExecConfig, IsExecConfig);
}
/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
///
/// __builtin_astype( value, dst type )
///
ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc) {
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
QualType DstTy = GetTypeFromParser(ParsedDestTy);
QualType SrcTy = E->getType();
if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
return ExprError(Diag(BuiltinLoc,
diag::err_invalid_astype_of_different_size)
<< DstTy
<< SrcTy
<< E->getSourceRange());
return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
}
/// ActOnConvertVectorExpr - create a new convert-vector expression from the
/// provided arguments.
///
/// __builtin_convertvector( value, dst type )
///
ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc) {
TypeSourceInfo *TInfo;
GetTypeFromParser(ParsedDestTy, &TInfo);
return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
}
/// BuildResolvedCallExpr - Build a call to a resolved expression,
/// i.e. an expression not of \p OverloadTy. The expression should
/// unary-convert to an expression of function-pointer or
/// block-pointer type.
///
/// \param NDecl the declaration being called, if available
ExprResult
Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
Expr *Config, bool IsExecConfig) {
FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
// Functions with 'interrupt' attribute cannot be called directly.
if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
return ExprError();
}
// Interrupt handlers don't save off the VFP regs automatically on ARM,
// so there's some risk when calling out to non-interrupt handler functions
// that the callee might not preserve them. This is easy to diagnose here,
// but can be very challenging to debug.
if (auto *Caller = getCurFunctionDecl())
if (Caller->hasAttr<ARMInterruptAttr>())
if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
// Promote the function operand.
// We special-case function promotion here because we only allow promoting
// builtin functions to function pointers in the callee of a call.
ExprResult Result;
if (BuiltinID &&
Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
CK_BuiltinFnToFnPtr).get();
} else {
Result = CallExprUnaryConversions(Fn);
}
if (Result.isInvalid())
return ExprError();
Fn = Result.get();
// Make the call expr early, before semantic checks. This guarantees cleanup
// of arguments and function on error.
CallExpr *TheCall;
if (Config)
TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
cast<CallExpr>(Config), Args,
Context.BoolTy, VK_RValue,
RParenLoc);
else
TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
VK_RValue, RParenLoc);
if (!getLangOpts().CPlusPlus) {
// C cannot always handle TypoExpr nodes in builtin calls and direct
// function calls as their argument checking don't necessarily handle
// dependent types properly, so make sure any TypoExprs have been
// dealt with.
ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
if (!Result.isUsable()) return ExprError();
TheCall = dyn_cast<CallExpr>(Result.get());
if (!TheCall) return Result;
Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
}
// Bail out early if calling a builtin with custom typechecking.
if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
retry:
const FunctionType *FuncT;
if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
// C99 6.5.2.2p1 - "The expression that denotes the called function shall
// have type pointer to function".
FuncT = PT->getPointeeType()->getAs<FunctionType>();
if (!FuncT)
return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
<< Fn->getType() << Fn->getSourceRange());
} else if (const BlockPointerType *BPT =
Fn->getType()->getAs<BlockPointerType>()) {
FuncT = BPT->getPointeeType()->castAs<FunctionType>();
} else {
// Handle calls to expressions of unknown-any type.
if (Fn->getType() == Context.UnknownAnyTy) {
ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
if (rewrite.isInvalid()) return ExprError();
Fn = rewrite.get();
TheCall->setCallee(Fn);
goto retry;
}
return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
<< Fn->getType() << Fn->getSourceRange());
}
if (getLangOpts().CUDA) {
if (Config) {
// CUDA: Kernel calls must be to global functions
if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
<< FDecl->getName() << Fn->getSourceRange());
// CUDA: Kernel function must have 'void' return type
if (!FuncT->getReturnType()->isVoidType())
return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
<< Fn->getType() << Fn->getSourceRange());
} else {
// CUDA: Calls to global functions must be configured
if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
<< FDecl->getName() << Fn->getSourceRange());
}
}
// Check for a valid return type
if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
FDecl))
return ExprError();
// We know the result type of the call, set it.
TheCall->setType(FuncT->getCallResultType(Context));
TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
if (Proto) {
if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
IsExecConfig))
return ExprError();
} else {
assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
if (FDecl) {
// Check if we have too few/too many template arguments, based
// on our knowledge of the function definition.
const FunctionDecl *Def = nullptr;
if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Proto = Def->getType()->getAs<FunctionProtoType>();
if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
<< (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
}
// If the function we're calling isn't a function prototype, but we have
// a function prototype from a prior declaratiom, use that prototype.
if (!FDecl->hasPrototype())
Proto = FDecl->getType()->getAs<FunctionProtoType>();
}
// Promote the arguments (C99 6.5.2.2p6).
for (unsigned i = 0, e = Args.size(); i != e; i++) {
Expr *Arg = Args[i];
if (Proto && i < Proto->getNumParams()) {
InitializedEntity Entity = InitializedEntity::InitializeParameter(
Context, Proto->getParamType(i), Proto->isParamConsumed(i));
ExprResult ArgE =
PerformCopyInitialization(Entity, SourceLocation(), Arg);
if (ArgE.isInvalid())
return true;
Arg = ArgE.getAs<Expr>();
} else {
ExprResult ArgE = DefaultArgumentPromotion(Arg);
if (ArgE.isInvalid())
return true;
Arg = ArgE.getAs<Expr>();
}
if (RequireCompleteType(Arg->getLocStart(),
Arg->getType(),
diag::err_call_incomplete_argument, Arg))
return ExprError();
TheCall->setArg(i, Arg);
}
}
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
if (!Method->isStatic())
return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
<< Fn->getSourceRange());
// Check for sentinels
if (NDecl)
DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
// Do special checking on direct calls to functions.
if (FDecl) {
if (CheckFunctionCall(FDecl, TheCall, Proto))
return ExprError();
if (BuiltinID)
return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
} else if (NDecl) {
if (CheckPointerCall(NDecl, TheCall, Proto))
return ExprError();
} else {
if (CheckOtherCall(TheCall, Proto))
return ExprError();
}
return MaybeBindToTemporary(TheCall);
}
ExprResult
Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
SourceLocation RParenLoc, Expr *InitExpr) {
assert(Ty && "ActOnCompoundLiteral(): missing type");
assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
TypeSourceInfo *TInfo;
QualType literalType = GetTypeFromParser(Ty, &TInfo);
if (!TInfo)
TInfo = Context.getTrivialTypeSourceInfo(literalType);
return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
}
ExprResult
Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
SourceLocation RParenLoc, Expr *LiteralExpr) {
QualType literalType = TInfo->getType();
if (literalType->isArrayType()) {
if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
diag::err_illegal_decl_array_incomplete_type,
SourceRange(LParenLoc,
LiteralExpr->getSourceRange().getEnd())))
return ExprError();
if (literalType->isVariableArrayType())
return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
<< SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
} else if (!literalType->isDependentType() &&
RequireCompleteType(LParenLoc, literalType,
diag::err_typecheck_decl_incomplete_type,
SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
return ExprError();
InitializedEntity Entity
= InitializedEntity::InitializeCompoundLiteralInit(TInfo);
InitializationKind Kind
= InitializationKind::CreateCStyleCast(LParenLoc,
SourceRange(LParenLoc, RParenLoc),
/*InitList=*/true);
InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
&literalType);
if (Result.isInvalid())
return ExprError();
LiteralExpr = Result.get();
bool isFileScope = !CurContext->isFunctionOrMethod();
if (isFileScope &&
!LiteralExpr->isTypeDependent() &&
!LiteralExpr->isValueDependent() &&
!literalType->isDependentType()) { // 6.5.2.5p3
if (CheckForConstantInitializer(LiteralExpr, literalType))
return ExprError();
}
// In C, compound literals are l-values for some reason.
// For GCC compatibility, in C++, file-scope array compound literals with
// constant initializers are also l-values, and compound literals are
// otherwise prvalues.
//
// (GCC also treats C++ list-initialized file-scope array prvalues with
// constant initializers as l-values, but that's non-conforming, so we don't
// follow it there.)
//
// FIXME: It would be better to handle the lvalue cases as materializing and
// lifetime-extending a temporary object, but our materialized temporaries
// representation only supports lifetime extension from a variable, not "out
// of thin air".
// FIXME: For C++, we might want to instead lifetime-extend only if a pointer
// is bound to the result of applying array-to-pointer decay to the compound
// literal.
// FIXME: GCC supports compound literals of reference type, which should
// obviously have a value kind derived from the kind of reference involved.
ExprValueKind VK =
(getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
? VK_RValue
: VK_LValue;
return MaybeBindToTemporary(
new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
VK, LiteralExpr, isFileScope));
}
ExprResult
Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
SourceLocation RBraceLoc) {
// Immediately handle non-overload placeholders. Overloads can be
// resolved contextually, but everything else here can't.
for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
// Ignore failures; dropping the entire initializer list because
// of one failure would be terrible for indexing/etc.
if (result.isInvalid()) continue;
InitArgList[I] = result.get();
}
}
// Semantic analysis for initializers is done by ActOnDeclarator() and
// CheckInitializer() - it requires knowledge of the object being intialized.
InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
RBraceLoc);
E->setType(Context.VoidTy); // FIXME: just a place holder for now.
return E;
}
/// Do an explicit extend of the given block pointer if we're in ARC.
void Sema::maybeExtendBlockObject(ExprResult &E) {
assert(E.get()->getType()->isBlockPointerType());
assert(E.get()->isRValue());
// Only do this in an r-value context.
if (!getLangOpts().ObjCAutoRefCount) return;
E = ImplicitCastExpr::Create(Context, E.get()->getType(),
CK_ARCExtendBlockObject, E.get(),
/*base path*/ nullptr, VK_RValue);
Cleanup.setExprNeedsCleanups(true);
}
/// Prepare a conversion of the given expression to an ObjC object
/// pointer type.
CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
QualType type = E.get()->getType();
if (type->isObjCObjectPointerType()) {
return CK_BitCast;
} else if (type->isBlockPointerType()) {
maybeExtendBlockObject(E);
return CK_BlockPointerToObjCPointerCast;
} else {
assert(type->isPointerType());
return CK_CPointerToObjCPointerCast;
}
}
/// Prepares for a scalar cast, performing all the necessary stages
/// except the final cast and returning the kind required.
CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
// Both Src and Dest are scalar types, i.e. arithmetic or pointer.
// Also, callers should have filtered out the invalid cases with
// pointers. Everything else should be possible.
QualType SrcTy = Src.get()->getType();
if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
return CK_NoOp;
switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
case Type::STK_MemberPointer:
llvm_unreachable("member pointer type in C");
case Type::STK_CPointer:
case Type::STK_BlockPointer:
case Type::STK_ObjCObjectPointer:
switch (DestTy->getScalarTypeKind()) {
case Type::STK_CPointer: {
unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
if (SrcAS != DestAS)
return CK_AddressSpaceConversion;
return CK_BitCast;
}
case Type::STK_BlockPointer:
return (SrcKind == Type::STK_BlockPointer
? CK_BitCast : CK_AnyPointerToBlockPointerCast);
case Type::STK_ObjCObjectPointer:
if (SrcKind == Type::STK_ObjCObjectPointer)
return CK_BitCast;
if (SrcKind == Type::STK_CPointer)
return CK_CPointerToObjCPointerCast;
maybeExtendBlockObject(Src);
return CK_BlockPointerToObjCPointerCast;
case Type::STK_Bool:
return CK_PointerToBoolean;
case Type::STK_Integral:
return CK_PointerToIntegral;
case Type::STK_Floating:
case Type::STK_FloatingComplex:
case Type::STK_IntegralComplex:
case Type::STK_MemberPointer:
llvm_unreachable("illegal cast from pointer");
}
llvm_unreachable("Should have returned before this");
case Type::STK_Bool: // casting from bool is like casting from an integer
case Type::STK_Integral:
switch (DestTy->getScalarTypeKind()) {
case Type::STK_CPointer:
case Type::STK_ObjCObjectPointer:
case Type::STK_BlockPointer:
if (Src.get()->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull))
return CK_NullToPointer;
return CK_IntegralToPointer;
case Type::STK_Bool:
return CK_IntegralToBoolean;
case Type::STK_Integral:
return CK_IntegralCast;
case Type::STK_Floating:
return CK_IntegralToFloating;
case Type::STK_IntegralComplex:
Src = ImpCastExprToType(Src.get(),
DestTy->castAs<ComplexType>()->getElementType(),
CK_IntegralCast);
return CK_IntegralRealToComplex;
case Type::STK_FloatingComplex:
Src = ImpCastExprToType(Src.get(),
DestTy->castAs<ComplexType>()->getElementType(),
CK_IntegralToFloating);
return CK_FloatingRealToComplex;
case Type::STK_MemberPointer:
llvm_unreachable("member pointer type in C");
}
llvm_unreachable("Should have returned before this");
case Type::STK_Floating:
switch (DestTy->getScalarTypeKind()) {
case Type::STK_Floating:
return CK_FloatingCast;
case Type::STK_Bool:
return CK_FloatingToBoolean;
case Type::STK_Integral:
return CK_FloatingToIntegral;
case Type::STK_FloatingComplex:
Src = ImpCastExprToType(Src.get(),
DestTy->castAs<ComplexType>()->getElementType(),
CK_FloatingCast);
return CK_FloatingRealToComplex;
case Type::STK_IntegralComplex:
Src = ImpCastExprToType(Src.get(),
DestTy->castAs<ComplexType>()->getElementType(),
CK_FloatingToIntegral);
return CK_IntegralRealToComplex;
case Type::STK_CPointer:
case Type::STK_ObjCObjectPointer:
case Type::STK_BlockPointer:
llvm_unreachable("valid float->pointer cast?");
case Type::STK_MemberPointer:
llvm_unreachable("member pointer type in C");
}
llvm_unreachable("Should have returned before this");
case Type::STK_FloatingComplex:
switch (DestTy->getScalarTypeKind()) {
case Type::STK_FloatingComplex:
return CK_FloatingComplexCast;
case Type::STK_IntegralComplex:
return CK_FloatingComplexToIntegralComplex;
case Type::STK_Floating: {
QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
if (Context.hasSameType(ET, DestTy))
return CK_FloatingComplexToReal;
Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
return CK_FloatingCast;
}
case Type::STK_Bool:
return CK_FloatingComplexToBoolean;
case Type::STK_Integral:
Src = ImpCastExprToType(Src.get(),
SrcTy->castAs<ComplexType>()->getElementType(),
CK_FloatingComplexToReal);
return CK_FloatingToIntegral;
case Type::STK_CPointer:
case Type::STK_ObjCObjectPointer:
case Type::STK_BlockPointer:
llvm_unreachable("valid complex float->pointer cast?");
case Type::STK_MemberPointer:
llvm_unreachable("member pointer type in C");
}
llvm_unreachable("Should have returned before this");
case Type::STK_IntegralComplex:
switch (DestTy->getScalarTypeKind()) {
case Type::STK_FloatingComplex:
return CK_IntegralComplexToFloatingComplex;
case Type::STK_IntegralComplex:
return CK_IntegralComplexCast;
case Type::STK_Integral: {
QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
if (Context.hasSameType(ET, DestTy))
return CK_IntegralComplexToReal;
Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
return CK_IntegralCast;
}
case Type::STK_Bool:
return CK_IntegralComplexToBoolean;
case Type::STK_Floating:
Src = ImpCastExprToType(Src.get(),
SrcTy->castAs<ComplexType>()->getElementType(),
CK_IntegralComplexToReal);
return CK_IntegralToFloating;
case Type::STK_CPointer:
case Type::STK_ObjCObjectPointer:
case Type::STK_BlockPointer:
llvm_unreachable("valid complex int->pointer cast?");
case Type::STK_MemberPointer:
llvm_unreachable("member pointer type in C");
}
llvm_unreachable("Should have returned before this");
}
llvm_unreachable("Unhandled scalar cast");
}
static bool breakDownVectorType(QualType type, uint64_t &len,
QualType &eltType) {
// Vectors are simple.
if (const VectorType *vecType = type->getAs<VectorType>()) {
len = vecType->getNumElements();
eltType = vecType->getElementType();
assert(eltType->isScalarType());
return true;
}
// We allow lax conversion to and from non-vector types, but only if
// they're real types (i.e. non-complex, non-pointer scalar types).
if (!type->isRealType()) return false;
len = 1;
eltType = type;
return true;
}
/// Are the two types lax-compatible vector types? That is, given
/// that one of them is a vector, do they have equal storage sizes,
/// where the storage size is the number of elements times the element
/// size?
///
/// This will also return false if either of the types is neither a
/// vector nor a real type.
bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
assert(destTy->isVectorType() || srcTy->isVectorType());
// Disallow lax conversions between scalars and ExtVectors (these
// conversions are allowed for other vector types because common headers
// depend on them). Most scalar OP ExtVector cases are handled by the
// splat path anyway, which does what we want (convert, not bitcast).
// What this rules out for ExtVectors is crazy things like char4*float.
if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
uint64_t srcLen, destLen;
QualType srcEltTy, destEltTy;
if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
// ASTContext::getTypeSize will return the size rounded up to a
// power of 2, so instead of using that, we need to use the raw
// element size multiplied by the element count.
uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
uint64_t destEltSize = Context.getTypeSize(destEltTy);
return (srcLen * srcEltSize == destLen * destEltSize);
}
/// Is this a legal conversion between two types, one of which is
/// known to be a vector type?
bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
assert(destTy->isVectorType() || srcTy->isVectorType());
if (!Context.getLangOpts().LaxVectorConversions)
return false;
return areLaxCompatibleVectorTypes(srcTy, destTy);
}
bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind) {
assert(VectorTy->isVectorType() && "Not a vector type!");
if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
return Diag(R.getBegin(),
Ty->isVectorType() ?
diag::err_invalid_conversion_between_vectors :
diag::err_invalid_conversion_between_vector_and_integer)
<< VectorTy << Ty << R;
} else
return Diag(R.getBegin(),
diag::err_invalid_conversion_between_vector_and_scalar)
<< VectorTy << Ty << R;
Kind = CK_BitCast;
return false;
}
ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
if (DestElemTy == SplattedExpr->getType())
return SplattedExpr;
assert(DestElemTy->isFloatingType() ||
DestElemTy->isIntegralOrEnumerationType());
CastKind CK;
if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
// OpenCL requires that we convert `true` boolean expressions to -1, but
// only when splatting vectors.
if (DestElemTy->isFloatingType()) {
// To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
// in two steps: boolean to signed integral, then to floating.
ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
CK_BooleanToSignedIntegral);
SplattedExpr = CastExprRes.get();
CK = CK_IntegralToFloating;
} else {
CK = CK_BooleanToSignedIntegral;
}
} else {
ExprResult CastExprRes = SplattedExpr;
CK = PrepareScalarCast(CastExprRes, DestElemTy);
if (CastExprRes.isInvalid())
return ExprError();
SplattedExpr = CastExprRes.get();
}
return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
}
ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
Expr *CastExpr, CastKind &Kind) {
assert(DestTy->isExtVectorType() && "Not an extended vector type!");
QualType SrcTy = CastExpr->getType();
// If SrcTy is a VectorType, the total size must match to explicitly cast to
// an ExtVectorType.
// In OpenCL, casts between vectors of different types are not allowed.
// (See OpenCL 6.2).
if (SrcTy->isVectorType()) {
if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
|| (getLangOpts().OpenCL &&
(DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
<< DestTy << SrcTy << R;
return ExprError();
}
Kind = CK_BitCast;
return CastExpr;
}
// All non-pointer scalars can be cast to ExtVector type. The appropriate
// conversion will take place first from scalar to elt type, and then
// splat from elt type to vector.
if (SrcTy->isPointerType())
return Diag(R.getBegin(),
diag::err_invalid_conversion_between_vector_and_scalar)
<< DestTy << SrcTy << R;
Kind = CK_VectorSplat;
return prepareVectorSplat(DestTy, CastExpr);
}
ExprResult
Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr) {
assert(!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr");
TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
if (D.isInvalidType())
return ExprError();
if (getLangOpts().CPlusPlus) {
// Check that there are no default arguments (C++ only).
CheckExtraCXXDefaultArguments(D);
} else {
// Make sure any TypoExprs have been dealt with.
ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
if (!Res.isUsable())
return ExprError();
CastExpr = Res.get();
}
checkUnusedDeclAttributes(D);
QualType castType = castTInfo->getType();
Ty = CreateParsedType(castType, castTInfo);
bool isVectorLiteral = false;
// Check for an altivec or OpenCL literal,
// i.e. all the elements are integer constants.
ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
&& castType->isVectorType() && (PE || PLE)) {
if (PLE && PLE->getNumExprs() == 0) {
Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
return ExprError();
}
if (PE || PLE->getNumExprs() == 1) {
Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
if (!E->getType()->isVectorType())
isVectorLiteral = true;
}
else
isVectorLiteral = true;
}
// If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
// then handle it as such.
if (isVectorLiteral)
return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
// If the Expr being casted is a ParenListExpr, handle it specially.
// This is not an AltiVec-style cast, so turn the ParenListExpr into a
// sequence of BinOp comma operators.
if (isa<ParenListExpr>(CastExpr)) {
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
if (Result.isInvalid()) return ExprError();
CastExpr = Result.get();
}
if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
!getSourceManager().isInSystemMacro(LParenLoc))
Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
CheckTollFreeBridgeCast(castType, CastExpr);
CheckObjCBridgeRelatedCast(castType, CastExpr);
DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
}
ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo) {
assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression");
Expr **exprs;
unsigned numExprs;
Expr *subExpr;
SourceLocation LiteralLParenLoc, LiteralRParenLoc;
if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
LiteralLParenLoc = PE->getLParenLoc();
LiteralRParenLoc = PE->getRParenLoc();
exprs = PE->getExprs();
numExprs = PE->getNumExprs();
} else { // isa<ParenExpr> by assertion at function entrance
LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
subExpr = cast<ParenExpr>(E)->getSubExpr();
exprs = &subExpr;
numExprs = 1;
}
QualType Ty = TInfo->getType();
assert(Ty->isVectorType() && "Expected vector type");
SmallVector<Expr *, 8> initExprs;
const VectorType *VTy = Ty->getAs<VectorType>();
unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
// '(...)' form of vector initialization in AltiVec: the number of
// initializers must be one or must match the size of the vector.
// If a single value is specified in the initializer then it will be
// replicated to all the components of the vector
if (VTy->getVectorKind() == VectorType::AltiVecVector) {
// The number of initializers must be one or must match the size of the
// vector. If a single value is specified in the initializer then it will
// be replicated to all the components of the vector
if (numExprs == 1) {
QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
ExprResult Literal = DefaultLvalueConversion(exprs[0]);
if (Literal.isInvalid())
return ExprError();
Literal = ImpCastExprToType(Literal.get(), ElemTy,
PrepareScalarCast(Literal, ElemTy));
return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
}
else if (numExprs < numElems) {
Diag(E->getExprLoc(),
diag::err_incorrect_number_of_vector_initializers);
return ExprError();
}
else
initExprs.append(exprs, exprs + numExprs);
}
else {
// For OpenCL, when the number of initializers is a single value,
// it will be replicated to all components of the vector.
if (getLangOpts().OpenCL &&
VTy->getVectorKind() == VectorType::GenericVector &&
numExprs == 1) {
QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
ExprResult Literal = DefaultLvalueConversion(exprs[0]);
if (Literal.isInvalid())
return ExprError();
Literal = ImpCastExprToType(Literal.get(), ElemTy,
PrepareScalarCast(Literal, ElemTy));
return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
}
initExprs.append(exprs, exprs + numExprs);
}
// FIXME: This means that pretty-printing the final AST will produce curly
// braces instead of the original commas.
InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
initExprs, LiteralRParenLoc);
initE->setType(Ty);
return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
}
/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
/// the ParenListExpr into a sequence of comma binary operators.
ExprResult
Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
if (!E)
return OrigExpr;
ExprResult Result(E->getExpr(0));
for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
E->getExpr(i));
if (Result.isInvalid()) return ExprError();
return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
}
ExprResult Sema::ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val) {
Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
return expr;
}
/// \brief Emit a specialized diagnostic when one expression is a null pointer
/// constant and the other is not a pointer. Returns true if a diagnostic is
/// emitted.
bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc) {
Expr *NullExpr = LHSExpr;
Expr *NonPointerExpr = RHSExpr;
Expr::NullPointerConstantKind NullKind =
NullExpr->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNotNull);
if (NullKind == Expr::NPCK_NotNull) {
NullExpr = RHSExpr;
NonPointerExpr = LHSExpr;
NullKind =
NullExpr->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNotNull);
}
if (NullKind == Expr::NPCK_NotNull)
return false;
if (NullKind == Expr::NPCK_ZeroExpression)
return false;
if (NullKind == Expr::NPCK_ZeroLiteral) {
// In this case, check to make sure that we got here from a "NULL"
// string in the source code.
NullExpr = NullExpr->IgnoreParenImpCasts();
SourceLocation loc = NullExpr->getExprLoc();
if (!findMacroSpelling(loc, "NULL"))
return false;
}
int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
<< NonPointerExpr->getType() << DiagType
<< NonPointerExpr->getSourceRange();
return true;
}
/// \brief Return false if the condition expression is valid, true otherwise.
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
QualType CondTy = Cond->getType();
// OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
<< CondTy << Cond->getSourceRange();
return true;
}
// C99 6.5.15p2
if (CondTy->isScalarType()) return false;
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
<< CondTy << Cond->getSourceRange();
return true;
}
/// \brief Handle when one or both operands are void type.
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
ExprResult &RHS) {
Expr *LHSExpr = LHS.get();
Expr *RHSExpr = RHS.get();
if (!LHSExpr->getType()->isVoidType())
S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
<< RHSExpr->getSourceRange();
if (!RHSExpr->getType()->isVoidType())
S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
<< LHSExpr->getSourceRange();
LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
return S.Context.VoidTy;
}
/// \brief Return false if the NullExpr can be promoted to PointerTy,
/// true otherwise.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
QualType PointerTy) {
if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
!NullExpr.get()->isNullPointerConstant(S.Context,
Expr::NPC_ValueDependentIsNull))
return true;
NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
return false;
}
/// \brief Checks compatibility between two pointers and return the resulting
/// type.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
ExprResult &RHS,
SourceLocation Loc) {
QualType LHSTy = LHS.get()->getType();
QualType RHSTy = RHS.get()->getType();
if (S.Context.hasSameType(LHSTy, RHSTy)) {
// Two identical pointers types are always compatible.
return LHSTy;
}
QualType lhptee, rhptee;
// Get the pointee types.
bool IsBlockPointer = false;
if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
lhptee = LHSBTy->getPointeeType();
rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
IsBlockPointer = true;
} else {
lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
}
// C99 6.5.15p6: If both operands are pointers to compatible types or to
// differently qualified versions of compatible types, the result type is
// a pointer to an appropriately qualified version of the composite
// type.
// Only CVR-qualifiers exist in the standard, and the differently-qualified
// clause doesn't make sense for our extensions. E.g. address space 2 should
// be incompatible with address space 3: they may live on different devices or
// anything.
Qualifiers lhQual = lhptee.getQualifiers();
Qualifiers rhQual = rhptee.getQualifiers();
unsigned ResultAddrSpace = 0;
unsigned LAddrSpace = lhQual.getAddressSpace();
unsigned RAddrSpace = rhQual.getAddressSpace();
if (S.getLangOpts().OpenCL) {
// OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
// spaces is disallowed.
if (lhQual.isAddressSpaceSupersetOf(rhQual))
ResultAddrSpace = LAddrSpace;
else if (rhQual.isAddressSpaceSupersetOf(lhQual))
ResultAddrSpace = RAddrSpace;
else {
S.Diag(Loc,
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
<< LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
return QualType();
}
}
unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
lhQual.removeCVRQualifiers();
rhQual.removeCVRQualifiers();
// OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
// (C99 6.7.3) for address spaces. We assume that the check should behave in
// the same manner as it's defined for CVR qualifiers, so for OpenCL two
// qual types are compatible iff
// * corresponded types are compatible
// * CVR qualifiers are equal
// * address spaces are equal
// Thus for conditional operator we merge CVR and address space unqualified
// pointees and if there is a composite type we return a pointer to it with
// merged qualifiers.
if (S.getLangOpts().OpenCL) {
LHSCastKind = LAddrSpace == ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion;
RHSCastKind = RAddrSpace == ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion;
lhQual.removeAddressSpace();
rhQual.removeAddressSpace();
}
lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
if (CompositeTy.isNull()) {
// In this situation, we assume void* type. No especially good
// reason, but this is what gcc does, and we do have to pick
// to get a consistent AST.
QualType incompatTy;
incompatTy = S.Context.getPointerType(
S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
// FIXME: For OpenCL the warning emission and cast to void* leaves a room
// for casts between types with incompatible address space qualifiers.
// For the following code the compiler produces casts between global and
// local address spaces of the corresponded innermost pointees:
// local int *global *a;
// global int *global *b;
// a = (0 ? a : b); // see C99 6.5.16.1.p1.
S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
return incompatTy;
}
// The pointer types are compatible.
// In case of OpenCL ResultTy should have the address space qualifier
// which is a superset of address spaces of both the 2nd and the 3rd
// operands of the conditional operator.
QualType ResultTy = [&, ResultAddrSpace]() {
if (S.getLangOpts().OpenCL) {
Qualifiers CompositeQuals = CompositeTy.getQualifiers();
CompositeQuals.setAddressSpace(ResultAddrSpace);
return S.Context
.getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
.withCVRQualifiers(MergedCVRQual);
} else
return CompositeTy.withCVRQualifiers(MergedCVRQual);
}();
if (IsBlockPointer)
ResultTy = S.Context.getBlockPointerType(ResultTy);
else {
ResultTy = S.Context.getPointerType(ResultTy);
}
LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
return ResultTy;
}
/// \brief Return the resulting type when the operands are both block pointers.
static QualType checkConditionalBlockPointerCompatibility(Sema &S,
ExprResult &LHS,
ExprResult &RHS,
SourceLocation Loc) {
QualType LHSTy = LHS.get()->getType();
QualType RHSTy = RHS.get()->getType();
if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
QualType destType = S.Context.getPointerType(S.Context.VoidTy);
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
return destType;
}
S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
return QualType();
}
// We have 2 block pointer types.
return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
}
/// \brief Return the resulting type when the operands are both pointers.
static QualType
checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
ExprResult &RHS,
SourceLocation Loc) {
// get the pointer types
QualType LHSTy = LHS.get()->getType();
QualType RHSTy = RHS.get()->getType();
// get the "pointed to" types
QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
// ignore qualifiers on void (C99 6.5.15p3, clause 6)
if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
// Figure out necessary qualifiers (C99 6.5.15p6)
QualType destPointee
= S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
QualType destType = S.Context.getPointerType(destPointee);
// Add qualifiers if necessary.
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
// Promote to void*.
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
return destType;
}
if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
QualType destPointee
= S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
QualType destType = S.Context.getPointerType(destPointee);
// Add qualifiers if necessary.
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
// Promote to void*.
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
return destType;
}
return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
}
/// \brief Return false if the first expression is not an integer and the second
/// expression is not a pointer, true otherwise.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
Expr* PointerExpr, SourceLocation Loc,
bool IsIntFirstExpr) {
if (!PointerExpr->getType()->isPointerType() ||
!Int.get()->getType()->isIntegerType())
return false;
Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
<< Expr1->getType() << Expr2->getType()
<< Expr1->getSourceRange() << Expr2->getSourceRange();
Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
CK_IntegralToPointer);
return true;
}
/// \brief Simple conversion between integer and floating point types.
///
/// Used when handling the OpenCL conditional operator where the
/// condition is a vector while the other operands are scalar.
///
/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
/// types are either integer or floating type. Between the two
/// operands, the type with the higher rank is defined as the "result
/// type". The other operand needs to be promoted to the same type. No
/// other type promotion is allowed. We cannot use
/// UsualArithmeticConversions() for this purpose, since it always
/// promotes promotable types.
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
ExprResult &RHS,
SourceLocation QuestionLoc) {
LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
if (LHS.isInvalid())
return QualType();
RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
if (RHS.isInvalid())
return QualType();
// For conversion purposes, we ignore any qualifiers.
// For example, "const float" and "float" are equivalent.
QualType LHSType =
S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
QualType RHSType =
S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
<< LHSType << LHS.get()->getSourceRange();
return QualType();
}
if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
<< RHSType << RHS.get()->getSourceRange();
return QualType();
}
// If both types are identical, no conversion is needed.
if (LHSType == RHSType)
return LHSType;
// Now handle "real" floating types (i.e. float, double, long double).
if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
/*IsCompAssign = */ false);
// Finally, we have two differing integer types.
return handleIntegerConversion<doIntegralCast, doIntegralCast>
(S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
}
/// \brief Convert scalar operands to a vector that matches the
/// condition in length.
///
/// Used when handling the OpenCL conditional operator where the
/// condition is a vector while the other operands are scalar.
///
/// We first compute the "result type" for the scalar operands
/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
/// into a vector of that type where the length matches the condition
/// vector type. s6.11.6 requires that the element types of the result
/// and the condition must have the same number of bits.
static QualType
OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
QualType CondTy, SourceLocation QuestionLoc) {
QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
if (ResTy.isNull()) return QualType();
const VectorType *CV = CondTy->getAs<VectorType>();
assert(CV);
// Determine the vector result type
unsigned NumElements = CV->getNumElements();
QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
// Ensure that all types have the same number of bits
if (S.Context.getTypeSize(CV->getElementType())
!= S.Context.getTypeSize(ResTy)) {
// Since VectorTy is created internally, it does not pretty print
// with an OpenCL name. Instead, we just print a description.
std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
SmallString<64> Str;
llvm::raw_svector_ostream OS(Str);
OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
<< CondTy << OS.str();
return QualType();
}
// Convert operands to the vector result type
LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
return VectorTy;
}
/// \brief Return false if this is a valid OpenCL condition vector
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
SourceLocation QuestionLoc) {
// OpenCL v1.1 s6.11.6 says the elements of the vector must be of
// integral type.
const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
assert(CondTy);
QualType EleTy = CondTy->getElementType();
if (EleTy->isIntegerType()) return false;
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
<< Cond->getType() << Cond->getSourceRange();
return true;
}
/// \brief Return false if the vector condition type and the vector
/// result type are compatible.
///
/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
/// number of elements, and their element types have the same number
/// of bits.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
SourceLocation QuestionLoc) {
const VectorType *CV = CondTy->getAs<VectorType>();
const VectorType *RV = VecResTy->getAs<VectorType>();
assert(CV && RV);
if (CV->getNumElements() != RV->getNumElements()) {
S.Diag(QuestionLoc, diag::err_conditional_vector_size)
<< CondTy << VecResTy;
return true;
}
QualType CVE = CV->getElementType();
QualType RVE = RV->getElementType();
if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
<< CondTy << VecResTy;
return true;
}
return false;
}
/// \brief Return the resulting type for the conditional operator in
/// OpenCL (aka "ternary selection operator", OpenCL v1.1
/// s6.3.i) when the condition is a vector type.
static QualType
OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc) {
Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
if (Cond.isInvalid())
return QualType();
QualType CondTy = Cond.get()->getType();
if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
return QualType();
// If either operand is a vector then find the vector type of the
// result as specified in OpenCL v1.1 s6.3.i.
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
/*isCompAssign*/false,
/*AllowBothBool*/true,
/*AllowBoolConversions*/false);
if (VecResTy.isNull()) return QualType();
// The result type must match the condition type as specified in
// OpenCL v1.1 s6.11.6.
if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
return QualType();
return VecResTy;
}
// Both operands are scalar.
return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
}
/// \brief Return true if the Expr is block type
static bool checkBlockType(Sema &S, const Expr *E) {
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
QualType Ty = CE->getCallee()->getType();
if (Ty->isBlockPointerType()) {
S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
return true;
}
}
return false;
}
/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
/// In that case, LHS = cond.
/// C99 6.5.15
QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
ExprResult &RHS, ExprValueKind &VK,
ExprObjectKind &OK,
SourceLocation QuestionLoc) {
ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
if (!LHSResult.isUsable()) return QualType();
LHS = LHSResult;
ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
if (!RHSResult.isUsable()) return QualType();
RHS = RHSResult;
// C++ is sufficiently different to merit its own checker.
if (getLangOpts().CPlusPlus)
return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
VK = VK_RValue;
OK = OK_Ordinary;
// The OpenCL operator with a vector condition is sufficiently
// different to merit its own checker.
if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
// First, check the condition.
Cond = UsualUnaryConversions(Cond.get());
if (Cond.isInvalid())
return QualType();
if (checkCondition(*this, Cond.get(), QuestionLoc))
return QualType();
// Now check the two expressions.
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType())
return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
/*AllowBothBool*/true,
/*AllowBoolConversions*/false);
QualType ResTy = UsualArithmeticConversions(LHS, RHS);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
QualType LHSTy = LHS.get()->getType();
QualType RHSTy = RHS.get()->getType();
// Diagnose attempts to convert between __float128 and long double where
// such conversions currently can't be handled.
if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
Diag(QuestionLoc,
diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
// OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
// selection operator (?:).
if (getLangOpts().OpenCL &&
(checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
return QualType();
}
// If both operands have arithmetic type, do the usual arithmetic conversions
// to find a common type: C99 6.5.15p3,5.
if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
return ResTy;
}
// If both operands are the same structure or union type, the result is that
// type.
if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
if (LHSRT->getDecl() == RHSRT->getDecl())
// "If both the operands have structure or union type, the result has
// that type." This implies that CV qualifiers are dropped.
return LHSTy.getUnqualifiedType();
// FIXME: Type of conditional expression must be complete in C mode.
}
// C99 6.5.15p5: "If both operands have void type, the result has void type."
// The following || allows only one side to be void (a GCC-ism).
if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
return checkConditionalVoidType(*this, LHS, RHS);
}
// C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
// the type of the other operand."
if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
// All objective-c pointer type analysis is done here.
QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
QuestionLoc);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
if (!compositeType.isNull())
return compositeType;
// Handle block pointer types.
if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
QuestionLoc);
// Check constraints for C object pointers types (C99 6.5.15p3,6).
if (LHSTy->isPointerType() && RHSTy->isPointerType())
return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
QuestionLoc);
// GCC compatibility: soften pointer/integer mismatch. Note that
// null pointers have been filtered out by this point.
if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
/*isIntFirstExpr=*/true))
return RHSTy;
if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
/*isIntFirstExpr=*/false))
return LHSTy;
// Emit a better diagnostic if one of the expressions is a null pointer
// constant and the other is not a pointer type. In this case, the user most
// likely forgot to take the address of the other expression.
if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
return QualType();
// Otherwise, the operands are not compatible.
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
return QualType();
}
/// FindCompositeObjCPointerType - Helper method to find composite type of
/// two objective-c pointer types of the two input expressions.
QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc) {
QualType LHSTy = LHS.get()->getType();
QualType RHSTy = RHS.get()->getType();
// Handle things like Class and struct objc_class*. Here we case the result
// to the pseudo-builtin, because that will be implicitly cast back to the
// redefinition type if an attempt is made to access its fields.
if (LHSTy->isObjCClassType() &&
(Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
return LHSTy;
}
if (RHSTy->isObjCClassType() &&
(Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
return RHSTy;
}
// And the same for struct objc_object* / id
if (LHSTy->isObjCIdType() &&
(Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
return LHSTy;
}
if (RHSTy->isObjCIdType() &&
(Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
return RHSTy;
}
// And the same for struct objc_selector* / SEL
if (Context.isObjCSelType(LHSTy) &&
(Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
return LHSTy;
}
if (Context.isObjCSelType(RHSTy) &&
(Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
return RHSTy;
}
// Check constraints for Objective-C object pointers types.
if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
// Two identical object pointer types are always compatible.
return LHSTy;
}
const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
QualType compositeType = LHSTy;
// If both operands are interfaces and either operand can be
// assigned to the other, use that type as the composite
// type. This allows
// xxx ? (A*) a : (B*) b
// where B is a subclass of A.
//
// Additionally, as for assignment, if either type is 'id'
// allow silent coercion. Finally, if the types are
// incompatible then make sure to use 'id' as the composite
// type so the result is acceptable for sending messages to.
// FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
// It could return the composite type.
if (!(compositeType =
Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
// Nothing more to do.
} else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
} else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
} else if ((LHSTy->isObjCQualifiedIdType() ||
RHSTy->isObjCQualifiedIdType()) &&
Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
// Need to handle "id<xx>" explicitly.
// GCC allows qualified id and any Objective-C type to devolve to
// id. Currently localizing to here until clear this should be
// part of ObjCQualifiedIdTypesAreCompatible.
compositeType = Context.getObjCIdType();
} else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
compositeType = Context.getObjCIdType();
} else {
Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
<< LHSTy << RHSTy
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
QualType incompatTy = Context.getObjCIdType();
LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
return incompatTy;
}
// The object pointer types are compatible.
LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
return compositeType;
}
// Check Objective-C object pointer types and 'void *'
if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
if (getLangOpts().ObjCAutoRefCount) {
// ARC forbids the implicit conversion of object pointers to 'void *',
// so these types are not compatible.
Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
LHS = RHS = true;
return QualType();
}
QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
QualType destPointee
= Context.getQualifiedType(lhptee, rhptee.getQualifiers());
QualType destType = Context.getPointerType(destPointee);
// Add qualifiers if necessary.
LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
// Promote to void*.
RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
return destType;
}
if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
if (getLangOpts().ObjCAutoRefCount) {
// ARC forbids the implicit conversion of object pointers to 'void *',
// so these types are not compatible.
Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
LHS = RHS = true;
return QualType();
}
QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
QualType destPointee
= Context.getQualifiedType(rhptee, lhptee.getQualifiers());
QualType destType = Context.getPointerType(destPointee);
// Add qualifiers if necessary.
RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
// Promote to void*.
LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
return destType;
}
return QualType();
}
/// SuggestParentheses - Emit a note with a fixit hint that wraps
/// ParenRange in parentheses.
static void SuggestParentheses(Sema &Self, SourceLocation Loc,
const PartialDiagnostic &Note,
SourceRange ParenRange) {
SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
EndLoc.isValid()) {
Self.Diag(Loc, Note)
<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
<< FixItHint::CreateInsertion(EndLoc, ")");
} else {
// We can't display the parentheses, so just show the bare note.
Self.Diag(Loc, Note) << ParenRange;
}
}
static bool IsArithmeticOp(BinaryOperatorKind Opc) {
return BinaryOperator::isAdditiveOp(Opc) ||
BinaryOperator::isMultiplicativeOp(Opc) ||
BinaryOperator::isShiftOp(Opc);
}
/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
/// expression, either using a built-in or overloaded operator,
/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
/// expression.
static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Expr **RHSExprs) {
// Don't strip parenthesis: we should not warn if E is in parenthesis.
E = E->IgnoreImpCasts();
E = E->IgnoreConversionOperator();
E = E->IgnoreImpCasts();
// Built-in binary operator.
if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
if (IsArithmeticOp(OP->getOpcode())) {
*Opcode = OP->getOpcode();
*RHSExprs = OP->getRHS();
return true;
}
}
// Overloaded operator.
if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
if (Call->getNumArgs() != 2)
return false;
// Make sure this is really a binary operator that is safe to pass into
// BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
OverloadedOperatorKind OO = Call->getOperator();
if (OO < OO_Plus || OO > OO_Arrow ||
OO == OO_PlusPlus || OO == OO_MinusMinus)
return false;
BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
if (IsArithmeticOp(OpKind)) {
*Opcode = OpKind;
*RHSExprs = Call->getArg(1);
return true;
}
}
return false;
}
/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
/// or is a logical expression such as (x==y) which has int type, but is
/// commonly interpreted as boolean.
static bool ExprLooksBoolean(Expr *E) {
E = E->IgnoreParenImpCasts();
if (E->getType()->isBooleanType())
return true;
if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
return OP->isComparisonOp() || OP->isLogicalOp();
if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
return OP->getOpcode() == UO_LNot;
if (E->getType()->isPointerType())
return true;
return false;
}
/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
/// and binary operator are mixed in a way that suggests the programmer assumed
/// the conditional operator has higher precedence, for example:
/// "int x = a + someBinaryCondition ? 1 : 2".
static void DiagnoseConditionalPrecedence(Sema &Self,
SourceLocation OpLoc,
Expr *Condition,
Expr *LHSExpr,
Expr *RHSExpr) {
BinaryOperatorKind CondOpcode;
Expr *CondRHS;
if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
return;
if (!ExprLooksBoolean(CondRHS))
return;
// The condition is an arithmetic binary expression, with a right-
// hand side that looks boolean, so warn.
Self.Diag(OpLoc, diag::warn_precedence_conditional)
<< Condition->getSourceRange()
<< BinaryOperator::getOpcodeStr(CondOpcode);
SuggestParentheses(Self, OpLoc,
Self.PDiag(diag::note_precedence_silence)
<< BinaryOperator::getOpcodeStr(CondOpcode),
SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
SuggestParentheses(Self, OpLoc,
Self.PDiag(diag::note_precedence_conditional_first),
SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
}
/// Compute the nullability of a conditional expression.
static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
QualType LHSTy, QualType RHSTy,
ASTContext &Ctx) {
if (!ResTy->isAnyPointerType())
return ResTy;
auto GetNullability = [&Ctx](QualType Ty) {
Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
if (Kind)
return *Kind;
return NullabilityKind::Unspecified;
};
auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
NullabilityKind MergedKind;
// Compute nullability of a binary conditional expression.
if (IsBin) {
if (LHSKind == NullabilityKind::NonNull)
MergedKind = NullabilityKind::NonNull;
else
MergedKind = RHSKind;
// Compute nullability of a normal conditional expression.
} else {
if (LHSKind == NullabilityKind::Nullable ||
RHSKind == NullabilityKind::Nullable)
MergedKind = NullabilityKind::Nullable;
else if (LHSKind == NullabilityKind::NonNull)
MergedKind = RHSKind;
else if (RHSKind == NullabilityKind::NonNull)
MergedKind = LHSKind;
else
MergedKind = NullabilityKind::Unspecified;
}
// Return if ResTy already has the correct nullability.
if (GetNullability(ResTy) == MergedKind)
return ResTy;
// Strip all nullability from ResTy.
while (ResTy->getNullability(Ctx))
ResTy = ResTy.getSingleStepDesugaredType(Ctx);
// Create a new AttributedType with the new nullability kind.
auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
}
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr) {
if (!getLangOpts().CPlusPlus) {
// C cannot handle TypoExpr nodes in the condition because it
// doesn't handle dependent types properly, so make sure any TypoExprs have
// been dealt with before checking the operands.
ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
if (!CondResult.isUsable())
return ExprError();
if (LHSExpr) {
if (!LHSResult.isUsable())
return ExprError();
}
if (!RHSResult.isUsable())
return ExprError();
CondExpr = CondResult.get();
LHSExpr = LHSResult.get();
RHSExpr = RHSResult.get();
}
// If this is the gnu "x ?: y" extension, analyze the types as though the LHS
// was the condition.
OpaqueValueExpr *opaqueValue = nullptr;
Expr *commonExpr = nullptr;
if (!LHSExpr) {
commonExpr = CondExpr;
// Lower out placeholder types first. This is important so that we don't
// try to capture a placeholder. This happens in few cases in C++; such
// as Objective-C++'s dictionary subscripting syntax.
if (commonExpr->hasPlaceholderType()) {
ExprResult result = CheckPlaceholderExpr(commonExpr);
if (!result.isUsable()) return ExprError();
commonExpr = result.get();
}
// We usually want to apply unary conversions *before* saving, except
// in the special case of a C++ l-value conditional.
if (!(getLangOpts().CPlusPlus
&& !commonExpr->isTypeDependent()
&& commonExpr->getValueKind() == RHSExpr->getValueKind()
&& commonExpr->isGLValue()
&& commonExpr->isOrdinaryOrBitFieldObject()
&& RHSExpr->isOrdinaryOrBitFieldObject()
&& Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
ExprResult commonRes = UsualUnaryConversions(commonExpr);
if (commonRes.isInvalid())
return ExprError();
commonExpr = commonRes.get();
}
opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
commonExpr->getType(),
commonExpr->getValueKind(),
commonExpr->getObjectKind(),
commonExpr);
LHSExpr = CondExpr = opaqueValue;
}
QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
QualType result = CheckConditionalOperands(Cond, LHS, RHS,
VK, OK, QuestionLoc);
if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
RHS.isInvalid())
return ExprError();
DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
RHS.get());
CheckBoolLikeConversion(Cond.get(), QuestionLoc);
result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
Context);
if (!commonExpr)
return new (Context)
ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
RHS.get(), result, VK, OK);
return new (Context) BinaryConditionalOperator(
commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
ColonLoc, result, VK, OK);
}
// checkPointerTypesForAssignment - This is a very tricky routine (despite
// being closely modeled after the C99 spec:-). The odd characteristic of this
// routine is it effectively iqnores the qualifiers on the top level pointee.
// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
// FIXME: add a couple examples in this comment.
static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
assert(LHSType.isCanonical() && "LHS not canonicalized!");
assert(RHSType.isCanonical() && "RHS not canonicalized!");
// get the "pointed to" type (ignoring qualifiers at the top level)
const Type *lhptee, *rhptee;
Qualifiers lhq, rhq;
std::tie(lhptee, lhq) =
cast<PointerType>(LHSType)->getPointeeType().split().asPair();
std::tie(rhptee, rhq) =
cast<PointerType>(RHSType)->getPointeeType().split().asPair();
Sema::AssignConvertType ConvTy = Sema::Compatible;
// C99 6.5.16.1p1: This following citation is common to constraints
// 3 & 4 (below). ...and the type *pointed to* by the left has all the
// qualifiers of the type *pointed to* by the right;
// As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
lhq.compatiblyIncludesObjCLifetime(rhq)) {
// Ignore lifetime for further calculation.
lhq.removeObjCLifetime();
rhq.removeObjCLifetime();
}
if (!lhq.compatiblyIncludes(rhq)) {
// Treat address-space mismatches as fatal. TODO: address subspaces
if (!lhq.isAddressSpaceSupersetOf(rhq))
ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
// It's okay to add or remove GC or lifetime qualifiers when converting to
// and from void*.
else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
.compatiblyIncludes(
rhq.withoutObjCGCAttr().withoutObjCLifetime())
&& (lhptee->isVoidType() || rhptee->isVoidType()))
; // keep old
// Treat lifetime mismatches as fatal.
else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
// For GCC/MS compatibility, other qualifier mismatches are treated
// as still compatible in C.
else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
}
// C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
// incomplete type and the other is a pointer to a qualified or unqualified
// version of void...
if (lhptee->isVoidType()) {
if (rhptee->isIncompleteOrObjectType())
return ConvTy;
// As an extension, we allow cast to/from void* to function pointer.
assert(rhptee->isFunctionType());
return Sema::FunctionVoidPointer;
}
if (rhptee->isVoidType()) {
if (lhptee->isIncompleteOrObjectType())
return ConvTy;
// As an extension, we allow cast to/from void* to function pointer.
assert(lhptee->isFunctionType());
return Sema::FunctionVoidPointer;
}
// C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
// unqualified versions of compatible types, ...
QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
// Check if the pointee types are compatible ignoring the sign.
// We explicitly check for char so that we catch "char" vs
// "unsigned char" on systems where "char" is unsigned.
if (lhptee->isCharType())
ltrans = S.Context.UnsignedCharTy;
else if (lhptee->hasSignedIntegerRepresentation())
ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
if (rhptee->isCharType())
rtrans = S.Context.UnsignedCharTy;
else if (rhptee->hasSignedIntegerRepresentation())
rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
if (ltrans == rtrans) {
// Types are compatible ignoring the sign. Qualifier incompatibility
// takes priority over sign incompatibility because the sign
// warning can be disabled.
if (ConvTy != Sema::Compatible)
return ConvTy;
return Sema::IncompatiblePointerSign;
}
// If we are a multi-level pointer, it's possible that our issue is simply
// one of qualification - e.g. char ** -> const char ** is not allowed. If
// the eventual target type is the same and the pointers have the same
// level of indirection, this must be the issue.
if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
do {
lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
} while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
if (lhptee == rhptee)
return Sema::IncompatibleNestedPointerQualifiers;
}
// General pointer incompatibility takes priority over qualifiers.
return Sema::IncompatiblePointer;
}
if (!S.getLangOpts().CPlusPlus &&
S.IsFunctionConversion(ltrans, rtrans, ltrans))
return Sema::IncompatiblePointer;
return ConvTy;
}
/// checkBlockPointerTypesForAssignment - This routine determines whether two
/// block pointer types are compatible or whether a block and normal pointer
/// are compatible. It is more restrict than comparing two function pointer
// types.
static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
QualType RHSType) {
assert(LHSType.isCanonical() && "LHS not canonicalized!");
assert(RHSType.isCanonical() && "RHS not canonicalized!");
QualType lhptee, rhptee;
// get the "pointed to" type (ignoring qualifiers at the top level)
lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
// In C++, the types have to match exactly.
if (S.getLangOpts().CPlusPlus)
return Sema::IncompatibleBlockPointer;
Sema::AssignConvertType ConvTy = Sema::Compatible;
// For blocks we enforce that qualifiers are identical.
Qualifiers LQuals = lhptee.getLocalQualifiers();
Qualifiers RQuals = rhptee.getLocalQualifiers();
if (S.getLangOpts().OpenCL) {
LQuals.removeAddressSpace();
RQuals.removeAddressSpace();
}
if (LQuals != RQuals)
ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
// FIXME: OpenCL doesn't define the exact compile time semantics for a block
// assignment.
// The current behavior is similar to C++ lambdas. A block might be
// assigned to a variable iff its return type and parameters are compatible
// (C99 6.2.7) with the corresponding return type and parameters of the LHS of
// an assignment. Presumably it should behave in way that a function pointer
// assignment does in C, so for each parameter and return type:
// * CVR and address space of LHS should be a superset of CVR and address
// space of RHS.
// * unqualified types should be compatible.
if (S.getLangOpts().OpenCL) {
if (!S.Context.typesAreBlockPointerCompatible(
S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
return Sema::IncompatibleBlockPointer;
} else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
return Sema::IncompatibleBlockPointer;
return ConvTy;
}
/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
/// for assignment compatibility.
static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
QualType RHSType) {
assert(LHSType.isCanonical() && "LHS was not canonicalized!");
assert(RHSType.isCanonical() && "RHS was not canonicalized!");
if (LHSType->isObjCBuiltinType()) {
// Class is not compatible with ObjC object pointers.
if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
!RHSType->isObjCQualifiedClassType())
return Sema::IncompatiblePointer;
return Sema::Compatible;
}
if (RHSType->isObjCBuiltinType()) {
if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
!LHSType->isObjCQualifiedClassType())
return Sema::IncompatiblePointer;
return Sema::Compatible;
}
QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
// make an exception for id<P>
!LHSType->isObjCQualifiedIdType())
return Sema::CompatiblePointerDiscardsQualifiers;
if (S.Context.typesAreCompatible(LHSType, RHSType))
return Sema::Compatible;
if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
return Sema::IncompatibleObjCQualifiedId;
return Sema::IncompatiblePointer;
}
Sema::AssignConvertType
Sema::CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType, QualType RHSType) {
// Fake up an opaque expression. We don't actually care about what
// cast operations are required, so if CheckAssignmentConstraints
// adds casts to this they'll be wasted, but fortunately that doesn't
// usually happen on valid code.
OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
ExprResult RHSPtr = &RHSExpr;
CastKind K = CK_Invalid;
return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
}
/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
/// has code to accommodate several GCC extensions when type checking
/// pointers. Here are some objectionable examples that GCC considers warnings:
///
/// int a, *pint;
/// short *pshort;
/// struct foo *pfoo;
///
/// pint = pshort; // warning: assignment from incompatible pointer type
/// a = pint; // warning: assignment makes integer from pointer without a cast
/// pint = a; // warning: assignment makes pointer from integer without a cast
/// pint = pfoo; // warning: assignment from incompatible pointer type
///
/// As a result, the code for dealing with pointers is more complex than the
/// C99 spec dictates.
///
/// Sets 'Kind' for any result kind except Incompatible.
Sema::AssignConvertType
Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
CastKind &Kind, bool ConvertRHS) {
QualType RHSType = RHS.get()->getType();
QualType OrigLHSType = LHSType;
// Get canonical types. We're not formatting these types, just comparing
// them.
LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
// Common case: no conversion required.
if (LHSType == RHSType) {
Kind = CK_NoOp;
return Compatible;
}
// If we have an atomic type, try a non-atomic assignment, then just add an
// atomic qualification step.
if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Sema::AssignConvertType result =
CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
if (result != Compatible)
return result;
if (Kind != CK_NoOp && ConvertRHS)
RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
Kind = CK_NonAtomicToAtomic;
return Compatible;
}
// If the left-hand side is a reference type, then we are in a
// (rare!) case where we've allowed the use of references in C,
// e.g., as a parameter type in a built-in function. In this case,
// just make sure that the type referenced is compatible with the
// right-hand side type. The caller is responsible for adjusting
// LHSType so that the resulting expression does not have reference
// type.
if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
Kind = CK_LValueBitCast;
return Compatible;
}
return Incompatible;
}
// Allow scalar to ExtVector assignments, and assignments of an ExtVector type
// to the same ExtVector type.
if (LHSType->isExtVectorType()) {
if (RHSType->isExtVectorType())
return Incompatible;
if (RHSType->isArithmeticType()) {
// CK_VectorSplat does T -> vector T, so first cast to the element type.
if (ConvertRHS)
RHS = prepareVectorSplat(LHSType, RHS.get());
Kind = CK_VectorSplat;
return Compatible;
}
}
// Conversions to or from vector type.
if (LHSType->isVectorType() || RHSType->isVectorType()) {
if (LHSType->isVectorType() && RHSType->isVectorType()) {
// Allow assignments of an AltiVec vector type to an equivalent GCC
// vector type and vice versa
if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Kind = CK_BitCast;
return Compatible;
}
// If we are allowing lax vector conversions, and LHS and RHS are both
// vectors, the total size only needs to be the same. This is a bitcast;
// no bits are changed but the result type is different.
if (isLaxVectorConversion(RHSType, LHSType)) {
Kind = CK_BitCast;
return IncompatibleVectors;
}
}
// When the RHS comes from another lax conversion (e.g. binops between
// scalars and vectors) the result is canonicalized as a vector. When the
// LHS is also a vector, the lax is allowed by the condition above. Handle
// the case where LHS is a scalar.
if (LHSType->isScalarType()) {
const VectorType *VecType = RHSType->getAs<VectorType>();
if (VecType && VecType->getNumElements() == 1 &&
isLaxVectorConversion(RHSType, LHSType)) {
ExprResult *VecExpr = &RHS;
*VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
Kind = CK_BitCast;
return Compatible;
}
}
return Incompatible;
}
// Diagnose attempts to convert between __float128 and long double where
// such conversions currently can't be handled.
if (unsupportedTypeConversion(*this, LHSType, RHSType))
return Incompatible;
// Arithmetic conversions.
if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
!(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
if (ConvertRHS)
Kind = PrepareScalarCast(RHS, LHSType);
return Compatible;
}
// Conversions to normal pointers.
if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
// U* -> T*
if (isa<PointerType>(RHSType)) {
unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
return checkPointerTypesForAssignment(*this, LHSType, RHSType);
}
// int -> T*
if (RHSType->isIntegerType()) {
Kind = CK_IntegralToPointer; // FIXME: null?
return IntToPointer;
}
// C pointers are not compatible with ObjC object pointers,
// with two exceptions:
if (isa<ObjCObjectPointerType>(RHSType)) {
// - conversions to void*
if (LHSPointer->getPointeeType()->isVoidType()) {
Kind = CK_BitCast;
return Compatible;
}
// - conversions from 'Class' to the redefinition type
if (RHSType->isObjCClassType() &&
Context.hasSameType(LHSType,
Context.getObjCClassRedefinitionType())) {
Kind = CK_BitCast;
return Compatible;
}
Kind = CK_BitCast;
return IncompatiblePointer;
}
// U^ -> void*
if (RHSType->getAs<BlockPointerType>()) {
if (LHSPointer->getPointeeType()->isVoidType()) {
unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
->getPointeeType()
.getAddressSpace();
Kind =
AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
return Compatible;
}
}
return Incompatible;
}
// Conversions to block pointers.
if (isa<BlockPointerType>(LHSType)) {
// U^ -> T^
if (RHSType->isBlockPointerType()) {
unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
->getPointeeType()
.getAddressSpace();
unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
->getPointeeType()
.getAddressSpace();
Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
}
// int or null -> T^
if (RHSType->isIntegerType()) {
Kind = CK_IntegralToPointer; // FIXME: null
return IntToBlockPointer;
}
// id -> T^
if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
Kind = CK_AnyPointerToBlockPointerCast;
return Compatible;
}
// void* -> T^
if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
if (RHSPT->getPointeeType()->isVoidType()) {
Kind = CK_AnyPointerToBlockPointerCast;
return Compatible;
}
return Incompatible;
}
// Conversions to Objective-C pointers.
if (isa<ObjCObjectPointerType>(LHSType)) {
// A* -> B*
if (RHSType->isObjCObjectPointerType()) {
Kind = CK_BitCast;
Sema::AssignConvertType result =
checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
result == Compatible &&
!CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
result = IncompatibleObjCWeakRef;
return result;
}
// int or null -> A*
if (RHSType->isIntegerType()) {
Kind = CK_IntegralToPointer; // FIXME: null
return IntToPointer;
}
// In general, C pointers are not compatible with ObjC object pointers,
// with two exceptions:
if (isa<PointerType>(RHSType)) {
Kind = CK_CPointerToObjCPointerCast;
// - conversions from 'void*'
if (RHSType->isVoidPointerType()) {
return Compatible;
}
// - conversions to 'Class' from its redefinition type
if (LHSType->isObjCClassType() &&
Context.hasSameType(RHSType,
Context.getObjCClassRedefinitionType())) {
return Compatible;
}
return IncompatiblePointer;
}
// Only under strict condition T^ is compatible with an Objective-C pointer.
if (RHSType->isBlockPointerType() &&
LHSType->isBlockCompatibleObjCPointerType(Context)) {
if (ConvertRHS)
maybeExtendBlockObject(RHS);
Kind = CK_BlockPointerToObjCPointerCast;
return Compatible;
}
return Incompatible;
}
// Conversions from pointers that are not covered by the above.
if (isa<PointerType>(RHSType)) {
// T* -> _Bool
if (LHSType == Context.BoolTy) {
Kind = CK_PointerToBoolean;
return Compatible;
}
// T* -> int
if (LHSType->isIntegerType()) {
Kind = CK_PointerToIntegral;
return PointerToInt;
}
return Incompatible;
}
// Conversions from Objective-C pointers that are not covered by the above.
if (isa<ObjCObjectPointerType>(RHSType)) {
// T* -> _Bool
if (LHSType == Context.BoolTy) {
Kind = CK_PointerToBoolean;
return Compatible;
}
// T* -> int
if (LHSType->isIntegerType()) {
Kind = CK_PointerToIntegral;
return PointerToInt;
}
return Incompatible;
}
// struct A -> struct B
if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
if (Context.typesAreCompatible(LHSType, RHSType)) {
Kind = CK_NoOp;
return Compatible;
}
}
if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
Kind = CK_IntToOCLSampler;
return Compatible;
}
return Incompatible;
}
/// \brief Constructs a transparent union from an expression that is
/// used to initialize the transparent union.
static void ConstructTransparentUnion(Sema &S, ASTContext &C,
ExprResult &EResult, QualType UnionType,
FieldDecl *Field) {
// Build an initializer list that designates the appropriate member
// of the transparent union.
Expr *E = EResult.get();
InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
E, SourceLocation());
Initializer->setType(UnionType);
Initializer->setInitializedFieldInUnion(Field);
// Build a compound literal constructing a value of the transparent
// union type from this initializer list.
TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
VK_RValue, Initializer, false);
}
Sema::AssignConvertType
Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS) {
QualType RHSType = RHS.get()->getType();
// If the ArgType is a Union type, we want to handle a potential
// transparent_union GCC extension.
const RecordType *UT = ArgType->getAsUnionType();
if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
return Incompatible;
// The field to initialize within the transparent union.
RecordDecl *UD = UT->getDecl();
FieldDecl *InitField = nullptr;
// It's compatible if the expression matches any of the fields.
for (auto *it : UD->fields()) {
if (it->getType()->isPointerType()) {
// If the transparent union contains a pointer type, we allow:
// 1) void pointer
// 2) null pointer constant
if (RHSType->isPointerType())
if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
InitField = it;
break;
}
if (RHS.get()->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull)) {
RHS = ImpCastExprToType(RHS.get(), it->getType(),
CK_NullToPointer);
InitField = it;
break;
}
}
CastKind Kind = CK_Invalid;
if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
== Compatible) {
RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
InitField = it;
break;
}
}
if (!InitField)
return Incompatible;
ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
return Compatible;
}
Sema::AssignConvertType
Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
bool Diagnose,
bool DiagnoseCFAudited,
bool ConvertRHS) {
// We need to be able to tell the caller whether we diagnosed a problem, if
// they ask us to issue diagnostics.
assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
// If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
// we can't avoid *all* modifications at the moment, so we need some somewhere
// to put the updated value.
ExprResult LocalRHS = CallerRHS;
ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
if (getLangOpts().CPlusPlus) {
if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
// C++ 5.17p3: If the left operand is not of class type, the
// expression is implicitly converted (C++ 4) to the
// cv-unqualified type of the left operand.
QualType RHSType = RHS.get()->getType();
if (Diagnose) {
RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
AA_Assigning);
} else {
ImplicitConversionSequence ICS =
TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
/*SuppressUserConversions=*/false,
/*AllowExplicit=*/false,
/*InOverloadResolution=*/false,
/*CStyle=*/false,
/*AllowObjCWritebackConversion=*/false);
if (ICS.isFailure())
return Incompatible;
RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
ICS, AA_Assigning);
}
if (RHS.isInvalid())
return Incompatible;
Sema::AssignConvertType result = Compatible;
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
!CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
result = IncompatibleObjCWeakRef;
return result;
}
// FIXME: Currently, we fall through and treat C++ classes like C
// structures.
// FIXME: We also fall through for atomics; not sure what should
// happen there, though.
} else if (RHS.get()->getType() == Context.OverloadTy) {
// As a set of extensions to C, we support overloading on functions. These
// functions need to be resolved here.
DeclAccessPair DAP;
if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
RHS.get(), LHSType, /*Complain=*/false, DAP))
RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
else
return Incompatible;
}
// C99 6.5.16.1p1: the left operand is a pointer and the right is
// a null pointer constant.
if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
LHSType->isBlockPointerType()) &&
RHS.get()->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull)) {
if (Diagnose || ConvertRHS) {
CastKind Kind;
CXXCastPath Path;
CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
/*IgnoreBaseAccess=*/false, Diagnose);
if (ConvertRHS)
RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
}
return Compatible;
}
// This check seems unnatural, however it is necessary to ensure the proper
// conversion of functions/arrays. If the conversion were done for all
// DeclExpr's (created by ActOnIdExpression), it would mess up the unary
// expressions that suppress this implicit conversion (&, sizeof).
//
// Suppress this for references: C++ 8.5.3p5.
if (!LHSType->isReferenceType()) {
// FIXME: We potentially allocate here even if ConvertRHS is false.
RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
if (RHS.isInvalid())
return Incompatible;
}
Expr *PRE = RHS.get()->IgnoreParenCasts();
if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
if (PDecl && !PDecl->hasDefinition()) {
Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
}
}
CastKind Kind = CK_Invalid;
Sema::AssignConvertType result =
CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
// C99 6.5.16.1p2: The value of the right operand is converted to the
// type of the assignment expression.
// CheckAssignmentConstraints allows the left-hand side to be a reference,
// so that we can use references in built-in functions even in C.
// The getNonReferenceType() call makes sure that the resulting expression
// does not have reference type.
if (result != Incompatible && RHS.get()->getType() != LHSType) {
QualType Ty = LHSType.getNonLValueExprType(Context);
Expr *E = RHS.get();
// Check for various Objective-C errors. If we are not reporting
// diagnostics and just checking for errors, e.g., during overload
// resolution, return Incompatible to indicate the failure.
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
Diagnose, DiagnoseCFAudited) != ACR_okay) {
if (!Diagnose)
return Incompatible;
}
if (getLangOpts().ObjC1 &&
(CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
E->getType(), E, Diagnose) ||
ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
if (!Diagnose)
return Incompatible;
// Replace the expression with a corrected version and continue so we
// can find further errors.
RHS = E;
return Compatible;
}
if (ConvertRHS)
RHS = ImpCastExprToType(E, Ty, Kind);
}
return result;
}
QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS) {
Diag(Loc, diag::err_typecheck_invalid_operands)
<< LHS.get()->getType() << RHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
/// Try to convert a value of non-vector type to a vector type by converting
/// the type to the element type of the vector and then performing a splat.
/// If the language is OpenCL, we only use conversions that promote scalar
/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
/// for float->int.
///
/// \param scalar - if non-null, actually perform the conversions
/// \return true if the operation fails (but without diagnosing the failure)
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
QualType scalarTy,
QualType vectorEltTy,
QualType vectorTy) {
// The conversion to apply to the scalar before splatting it,
// if necessary.
CastKind scalarCast = CK_Invalid;
if (vectorEltTy->isIntegralType(S.Context)) {
if (!scalarTy->isIntegralType(S.Context))
return true;
if (S.getLangOpts().OpenCL &&
S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
return true;
scalarCast = CK_IntegralCast;
} else if (vectorEltTy->isRealFloatingType()) {
if (scalarTy->isRealFloatingType()) {
if (S.getLangOpts().OpenCL &&
S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
return true;
scalarCast = CK_FloatingCast;
}
else if (scalarTy->isIntegralType(S.Context))
scalarCast = CK_IntegralToFloating;
else
return true;
} else {
return true;
}
// Adjust scalar if desired.
if (scalar) {
if (scalarCast != CK_Invalid)
*scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
*scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
}
return false;
}
QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool,
bool AllowBoolConversions) {
if (!IsCompAssign) {
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
if (LHS.isInvalid())
return QualType();
}
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
if (RHS.isInvalid())
return QualType();
// For conversion purposes, we ignore any qualifiers.
// For example, "const float" and "float" are equivalent.
QualType LHSType = LHS.get()->getType().getUnqualifiedType();
QualType RHSType = RHS.get()->getType().getUnqualifiedType();
const VectorType *LHSVecType = LHSType->getAs<VectorType>();
const VectorType *RHSVecType = RHSType->getAs<VectorType>();
assert(LHSVecType || RHSVecType);
// AltiVec-style "vector bool op vector bool" combinations are allowed
// for some operators but not others.
if (!AllowBothBool &&
LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
return InvalidOperands(Loc, LHS, RHS);
// If the vector types are identical, return.
if (Context.hasSameType(LHSType, RHSType))
return LHSType;
// If we have compatible AltiVec and GCC vector types, use the AltiVec type.
if (LHSVecType && RHSVecType &&
Context.areCompatibleVectorTypes(LHSType, RHSType)) {
if (isa<ExtVectorType>(LHSVecType)) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
return LHSType;
}
if (!IsCompAssign)
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
return RHSType;
}
// AllowBoolConversions says that bool and non-bool AltiVec vectors
// can be mixed, with the result being the non-bool type. The non-bool
// operand must have integer element type.
if (AllowBoolConversions && LHSVecType && RHSVecType &&
LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
(Context.getTypeSize(LHSVecType->getElementType()) ==
Context.getTypeSize(RHSVecType->getElementType()))) {
if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
LHSVecType->getElementType()->isIntegerType() &&
RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
return LHSType;
}
if (!IsCompAssign &&
LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
RHSVecType->getElementType()->isIntegerType()) {
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
return RHSType;
}
}
// If there's an ext-vector type and a scalar, try to convert the scalar to
// the vector element type and splat.
// FIXME: this should also work for regular vector types as supported in GCC.
if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
LHSVecType->getElementType(), LHSType))
return LHSType;
}
if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
LHSType, RHSVecType->getElementType(),
RHSType))
return RHSType;
}
// FIXME: The code below also handles conversion between vectors and
// non-scalars, we should break this down into fine grained specific checks
// and emit proper diagnostics.
QualType VecType = LHSVecType ? LHSType : RHSType;
const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
QualType OtherType = LHSVecType ? RHSType : LHSType;
ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
if (isLaxVectorConversion(OtherType, VecType)) {
// If we're allowing lax vector conversions, only the total (data) size
// needs to be the same. For non compound assignment, if one of the types is
// scalar, the result is always the vector type.
if (!IsCompAssign) {
*OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
return VecType;
// In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
// any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
// type. Note that this is already done by non-compound assignments in
// CheckAssignmentConstraints. If it's a scalar type, only bitcast for
// <1 x T> -> T. The result is also a vector type.
} else if (OtherType->isExtVectorType() ||
(OtherType->isScalarType() && VT->getNumElements() == 1)) {
ExprResult *RHSExpr = &RHS;
*RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
return VecType;
}
}
// Okay, the expression is invalid.
// If there's a non-vector, non-real operand, diagnose that.
if ((!RHSVecType && !RHSType->isRealType()) ||
(!LHSVecType && !LHSType->isRealType())) {
Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
<< LHSType << RHSType
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
// OpenCL V1.1 6.2.6.p1:
// If the operands are of more than one vector type, then an error shall
// occur. Implicit conversions between vector types are not permitted, per
// section 6.2.1.
if (getLangOpts().OpenCL &&
RHSVecType && isa<ExtVectorType>(RHSVecType) &&
LHSVecType && isa<ExtVectorType>(LHSVecType)) {
Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
<< RHSType;
return QualType();
}
// Otherwise, use the generic diagnostic.
Diag(Loc, diag::err_typecheck_vector_not_convertable)
<< LHSType << RHSType
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
// checkArithmeticNull - Detect when a NULL constant is used improperly in an
// expression. These are mainly cases where the null pointer is used as an
// integer instead of a pointer.
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompare) {
// The canonical way to check for a GNU null is with isNullPointerConstant,
// but we use a bit of a hack here for speed; this is a relatively
// hot path, and isNullPointerConstant is slow.
bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
// Avoid analyzing cases where the result will either be invalid (and
// diagnosed as such) or entirely valid and not something to warn about.
if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
return;
// Comparison operations would not make sense with a null pointer no matter
// what the other expression is.
if (!IsCompare) {
S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
<< (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
<< (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
return;
}
// The rest of the operations only make sense with a null pointer
// if the other expression is a pointer.
if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
NonNullType->canDecayToPointerType())
return;
S.Diag(Loc, diag::warn_null_in_comparison_operation)
<< LHSNull /* LHS is NULL */ << NonNullType
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
ExprResult &RHS,
SourceLocation Loc, bool IsDiv) {
// Check for division/remainder by zero.
llvm::APSInt RHSValue;
if (!RHS.get()->isValueDependent() &&
RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
S.DiagRuntimeBehavior(Loc, RHS.get(),
S.PDiag(diag::warn_remainder_division_by_zero)
<< IsDiv << RHS.get()->getSourceRange());
}
QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
bool IsCompAssign, bool IsDiv) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType())
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
/*AllowBothBool*/getLangOpts().AltiVec,
/*AllowBoolConversions*/false);
QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
if (compType.isNull() || !compType->isArithmeticType())
return InvalidOperands(Loc, LHS, RHS);
if (IsDiv)
DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
return compType;
}
QualType Sema::CheckRemainderOperands(
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
if (LHS.get()->getType()->hasIntegerRepresentation() &&
RHS.get()->getType()->hasIntegerRepresentation())
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
/*AllowBothBool*/getLangOpts().AltiVec,
/*AllowBoolConversions*/false);
return InvalidOperands(Loc, LHS, RHS);
}
QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
if (compType.isNull() || !compType->isIntegerType())
return InvalidOperands(Loc, LHS, RHS);
DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
return compType;
}
/// \brief Diagnose invalid arithmetic on two void pointers.
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Expr *LHSExpr, Expr *RHSExpr) {
S.Diag(Loc, S.getLangOpts().CPlusPlus
? diag::err_typecheck_pointer_arith_void_type
: diag::ext_gnu_void_ptr)
<< 1 /* two pointers */ << LHSExpr->getSourceRange()
<< RHSExpr->getSourceRange();
}
/// \brief Diagnose invalid arithmetic on a void pointer.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
Expr *Pointer) {
S.Diag(Loc, S.getLangOpts().CPlusPlus
? diag::err_typecheck_pointer_arith_void_type
: diag::ext_gnu_void_ptr)
<< 0 /* one pointer */ << Pointer->getSourceRange();
}
/// \brief Diagnose invalid arithmetic on two function pointers.
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
Expr *LHS, Expr *RHS) {
assert(LHS->getType()->isAnyPointerType());
assert(RHS->getType()->isAnyPointerType());
S.Diag(Loc, S.getLangOpts().CPlusPlus
? diag::err_typecheck_pointer_arith_function_type
: diag::ext_gnu_ptr_func_arith)
<< 1 /* two pointers */ << LHS->getType()->getPointeeType()
// We only show the second type if it differs from the first.
<< (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
RHS->getType())
<< RHS->getType()->getPointeeType()
<< LHS->getSourceRange() << RHS->getSourceRange();
}
/// \brief Diagnose invalid arithmetic on a function pointer.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
Expr *Pointer) {
assert(Pointer->getType()->isAnyPointerType());
S.Diag(Loc, S.getLangOpts().CPlusPlus
? diag::err_typecheck_pointer_arith_function_type
: diag::ext_gnu_ptr_func_arith)
<< 0 /* one pointer */ << Pointer->getType()->getPointeeType()
<< 0 /* one pointer, so only one type */
<< Pointer->getSourceRange();
}
/// \brief Emit error if Operand is incomplete pointer type
///
/// \returns True if pointer has incomplete type
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
Expr *Operand) {
QualType ResType = Operand->getType();
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
ResType = ResAtomicType->getValueType();
assert(ResType->isAnyPointerType() && !ResType->isDependentType());
QualType PointeeTy = ResType->getPointeeType();
return S.RequireCompleteType(Loc, PointeeTy,
diag::err_typecheck_arithmetic_incomplete_type,
PointeeTy, Operand->getSourceRange());
}
/// \brief Check the validity of an arithmetic pointer operand.
///
/// If the operand has pointer type, this code will check for pointer types
/// which are invalid in arithmetic operations. These will be diagnosed
/// appropriately, including whether or not the use is supported as an
/// extension.
///
/// \returns True when the operand is valid to use (even if as an extension).
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
Expr *Operand) {
QualType ResType = Operand->getType();
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
ResType = ResAtomicType->getValueType();
if (!ResType->isAnyPointerType()) return true;
QualType PointeeTy = ResType->getPointeeType();
if (PointeeTy->isVoidType()) {
diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
return !S.getLangOpts().CPlusPlus;
}
if (PointeeTy->isFunctionType()) {
diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
return !S.getLangOpts().CPlusPlus;
}
if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
return true;
}
/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
/// operands.
///
/// This routine will diagnose any invalid arithmetic on pointer operands much
/// like \see checkArithmeticOpPointerOperand. However, it has special logic
/// for emitting a single diagnostic even for operations where both LHS and RHS
/// are (potentially problematic) pointers.
///
/// \returns True when the operand is valid to use (even if as an extension).
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Expr *LHSExpr, Expr *RHSExpr) {
bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
if (!isLHSPointer && !isRHSPointer) return true;
QualType LHSPointeeTy, RHSPointeeTy;
if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
// if both are pointers check if operation is valid wrt address spaces
if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
S.Diag(Loc,
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
<< LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
return false;
}
}
// Check for arithmetic on pointers to incomplete types.
bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
if (isLHSVoidPtr || isRHSVoidPtr) {
if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
return !S.getLangOpts().CPlusPlus;
}
bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
if (isLHSFuncPtr || isRHSFuncPtr) {
if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
RHSExpr);
else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
return !S.getLangOpts().CPlusPlus;
}
if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
return false;
if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
return false;
return true;
}
/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
/// literal.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
Expr *LHSExpr, Expr *RHSExpr) {
StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
Expr* IndexExpr = RHSExpr;
if (!StrExpr) {
StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
IndexExpr = LHSExpr;
}
bool IsStringPlusInt = StrExpr &&
IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
if (!IsStringPlusInt || IndexExpr->isValueDependent())
return;
llvm::APSInt index;
if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
unsigned StrLenWithNull = StrExpr->getLength() + 1;
if (index.isNonNegative() &&
index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
index.isUnsigned()))
return;
}
SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
Self.Diag(OpLoc, diag::warn_string_plus_int)
<< DiagRange << IndexExpr->IgnoreImpCasts()->getType();
// Only print a fixit for "str" + int, not for int + "str".
if (IndexExpr == RHSExpr) {
SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
<< FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
<< FixItHint::CreateInsertion(EndLoc, "]");
} else
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
}
/// \brief Emit a warning when adding a char literal to a string.
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
Expr *LHSExpr, Expr *RHSExpr) {
const Expr *StringRefExpr = LHSExpr;
const CharacterLiteral *CharExpr =
dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
if (!CharExpr) {
CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
StringRefExpr = RHSExpr;
}
if (!CharExpr || !StringRefExpr)
return;
const QualType StringType = StringRefExpr->getType();
// Return if not a PointerType.
if (!StringType->isAnyPointerType())
return;
// Return if not a CharacterType.
if (!StringType->getPointeeType()->isAnyCharacterType())
return;
ASTContext &Ctx = Self.getASTContext();
SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
const QualType CharType = CharExpr->getType();
if (!CharType->isAnyCharacterType() &&
CharType->isIntegerType() &&
llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
Self.Diag(OpLoc, diag::warn_string_plus_char)
<< DiagRange << Ctx.CharTy;
} else {
Self.Diag(OpLoc, diag::warn_string_plus_char)
<< DiagRange << CharExpr->getType();
}
// Only print a fixit for str + char, not for char + str.
if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
<< FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
<< FixItHint::CreateInsertion(EndLoc, "]");
} else {
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
}
}
/// \brief Emit error when two pointers are incompatible.
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Expr *LHSExpr, Expr *RHSExpr) {
assert(LHSExpr->getType()->isAnyPointerType());
assert(RHSExpr->getType()->isAnyPointerType());
S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
<< LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
<< RHSExpr->getSourceRange();
}
// C99 6.5.6
QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, BinaryOperatorKind Opc,
QualType* CompLHSTy) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
QualType compType = CheckVectorOperands(
LHS, RHS, Loc, CompLHSTy,
/*AllowBothBool*/getLangOpts().AltiVec,
/*AllowBoolConversions*/getLangOpts().ZVector);
if (CompLHSTy) *CompLHSTy = compType;
return compType;
}
QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
// Diagnose "string literal" '+' int and string '+' "char literal".
if (Opc == BO_Add) {
diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
}
// handle the common case first (both operands are arithmetic).
if (!compType.isNull() && compType->isArithmeticType()) {
if (CompLHSTy) *CompLHSTy = compType;
return compType;
}
// Type-checking. Ultimately the pointer's going to be in PExp;
// note that we bias towards the LHS being the pointer.
Expr *PExp = LHS.get(), *IExp = RHS.get();
bool isObjCPointer;
if (PExp->getType()->isPointerType()) {
isObjCPointer = false;
} else if (PExp->getType()->isObjCObjectPointerType()) {
isObjCPointer = true;
} else {
std::swap(PExp, IExp);
if (PExp->getType()->isPointerType()) {
isObjCPointer = false;
} else if (PExp->getType()->isObjCObjectPointerType()) {
isObjCPointer = true;
} else {
return InvalidOperands(Loc, LHS, RHS);
}
}
assert(PExp->getType()->isAnyPointerType());
if (!IExp->getType()->isIntegerType())
return InvalidOperands(Loc, LHS, RHS);
if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
return QualType();
if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
return QualType();
// Check array bounds for pointer arithemtic
CheckArrayAccess(PExp, IExp);
if (CompLHSTy) {
QualType LHSTy = Context.isPromotableBitField(LHS.get());
if (LHSTy.isNull()) {
LHSTy = LHS.get()->getType();
if (LHSTy->isPromotableIntegerType())
LHSTy = Context.getPromotedIntegerType(LHSTy);
}
*CompLHSTy = LHSTy;
}
return PExp->getType();
}
// C99 6.5.6
QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
QualType* CompLHSTy) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
QualType compType = CheckVectorOperands(
LHS, RHS, Loc, CompLHSTy,
/*AllowBothBool*/getLangOpts().AltiVec,
/*AllowBoolConversions*/getLangOpts().ZVector);
if (CompLHSTy) *CompLHSTy = compType;
return compType;
}
QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
// Enforce type constraints: C99 6.5.6p3.
// Handle the common case first (both operands are arithmetic).
if (!compType.isNull() && compType->isArithmeticType()) {
if (CompLHSTy) *CompLHSTy = compType;
return compType;
}
// Either ptr - int or ptr - ptr.
if (LHS.get()->getType()->isAnyPointerType()) {
QualType lpointee = LHS.get()->getType()->getPointeeType();
// Diagnose bad cases where we step over interface counts.
if (LHS.get()->getType()->isObjCObjectPointerType() &&
checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
return QualType();
// The result type of a pointer-int computation is the pointer type.
if (RHS.get()->getType()->isIntegerType()) {
if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
return QualType();
// Check array bounds for pointer arithemtic
CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
/*AllowOnePastEnd*/true, /*IndexNegated*/true);
if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
return LHS.get()->getType();
}
// Handle pointer-pointer subtractions.
if (const PointerType *RHSPTy
= RHS.get()->getType()->getAs<PointerType>()) {
QualType rpointee = RHSPTy->getPointeeType();
if (getLangOpts().CPlusPlus) {
// Pointee types must be the same: C++ [expr.add]
if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
}
} else {
// Pointee types must be compatible C99 6.5.6p3
if (!Context.typesAreCompatible(
Context.getCanonicalType(lpointee).getUnqualifiedType(),
Context.getCanonicalType(rpointee).getUnqualifiedType())) {
diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
return QualType();
}
}
if (!checkArithmeticBinOpPointerOperands(*this, Loc,
LHS.get(), RHS.get()))
return QualType();
// The pointee type may have zero size. As an extension, a structure or
// union may have zero size or an array may have zero length. In this
// case subtraction does not make sense.
if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
if (ElementSize.isZero()) {
Diag(Loc,diag::warn_sub_ptr_zero_size_types)
<< rpointee.getUnqualifiedType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
}
if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
return Context.getPointerDiffType();
}
}
return InvalidOperands(Loc, LHS, RHS);
}
static bool isScopedEnumerationType(QualType T) {
if (const EnumType *ET = T->getAs<EnumType>())
return ET->getDecl()->isScoped();
return false;
}
static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, BinaryOperatorKind Opc,
QualType LHSType) {
// OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
// so skip remaining warnings as we don't want to modify values within Sema.
if (S.getLangOpts().OpenCL)
return;
llvm::APSInt Right;
// Check right/shifter operand
if (RHS.get()->isValueDependent() ||
!RHS.get()->EvaluateAsInt(Right, S.Context))
return;
if (Right.isNegative()) {
S.DiagRuntimeBehavior(Loc, RHS.get(),
S.PDiag(diag::warn_shift_negative)
<< RHS.get()->getSourceRange());
return;
}
llvm::APInt LeftBits(Right.getBitWidth(),
S.Context.getTypeSize(LHS.get()->getType()));
if (Right.uge(LeftBits)) {
S.DiagRuntimeBehavior(Loc, RHS.get(),
S.PDiag(diag::warn_shift_gt_typewidth)
<< RHS.get()->getSourceRange());
return;
}
if (Opc != BO_Shl)
return;
// When left shifting an ICE which is signed, we can check for overflow which
// according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
// integers have defined behavior modulo one more than the maximum value
// representable in the result type, so never warn for those.
llvm::APSInt Left;
if (LHS.get()->isValueDependent() ||
LHSType->hasUnsignedIntegerRepresentation() ||
!LHS.get()->EvaluateAsInt(Left, S.Context))
return;
// If LHS does not have a signed type and non-negative value
// then, the behavior is undefined. Warn about it.
if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
S.DiagRuntimeBehavior(Loc, LHS.get(),
S.PDiag(diag::warn_shift_lhs_negative)
<< LHS.get()->getSourceRange());
return;
}
llvm::APInt ResultBits =
static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
if (LeftBits.uge(ResultBits))
return;
llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
Result = Result.shl(Right);
// Print the bit representation of the signed integer as an unsigned
// hexadecimal number.
SmallString<40> HexResult;
Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
// If we are only missing a sign bit, this is less likely to result in actual
// bugs -- if the result is cast back to an unsigned type, it will have the
// expected value. Thus we place this behind a different warning that can be
// turned off separately if needed.
if (LeftBits == ResultBits - 1) {
S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
<< HexResult << LHSType
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return;
}
S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
<< HexResult.str() << Result.getMinSignedBits() << LHSType
<< Left.getBitWidth() << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
}
/// \brief Return the resulting type when a vector is shifted
/// by a scalar or vector shift amount.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign) {
// OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
!LHS.get()->getType()->isVectorType()) {
S.Diag(Loc, diag::err_shift_rhs_only_vector)
<< RHS.get()->getType() << LHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
if (!IsCompAssign) {
LHS = S.UsualUnaryConversions(LHS.get());
if (LHS.isInvalid()) return QualType();
}
RHS = S.UsualUnaryConversions(RHS.get());
if (RHS.isInvalid()) return QualType();
QualType LHSType = LHS.get()->getType();
// Note that LHS might be a scalar because the routine calls not only in
// OpenCL case.
const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
// Note that RHS might not be a vector.
QualType RHSType = RHS.get()->getType();
const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
// The operands need to be integers.
if (!LHSEleType->isIntegerType()) {
S.Diag(Loc, diag::err_typecheck_expect_int)
<< LHS.get()->getType() << LHS.get()->getSourceRange();
return QualType();
}
if (!RHSEleType->isIntegerType()) {
S.Diag(Loc, diag::err_typecheck_expect_int)
<< RHS.get()->getType() << RHS.get()->getSourceRange();
return QualType();
}
if (!LHSVecTy) {
assert(RHSVecTy);
if (IsCompAssign)
return RHSType;
if (LHSEleType != RHSEleType) {
LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
LHSEleType = RHSEleType;
}
QualType VecTy =
S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
LHSType = VecTy;
} else if (RHSVecTy) {
// OpenCL v1.1 s6.3.j says that for vector types, the operators
// are applied component-wise. So if RHS is a vector, then ensure
// that the number of elements is the same as LHS...
if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
<< LHS.get()->getType() << RHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
return QualType();
}
if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
if (LHSBT != RHSBT &&
S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
<< LHS.get()->getType() << RHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
}
} else {
// ...else expand RHS to match the number of elements in LHS.
QualType VecTy =
S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
}
return LHSType;
}
// C99 6.5.7
QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, BinaryOperatorKind Opc,
bool IsCompAssign) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
// Vector shifts promote their scalar inputs to vector type.
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
if (LangOpts.ZVector) {
// The shift operators for the z vector extensions work basically
// like general shifts, except that neither the LHS nor the RHS is
// allowed to be a "vector bool".
if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
return InvalidOperands(Loc, LHS, RHS);
if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
return InvalidOperands(Loc, LHS, RHS);
}
return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
}
// Shifts don't perform usual arithmetic conversions, they just do integer
// promotions on each operand. C99 6.5.7p3
// For the LHS, do usual unary conversions, but then reset them away
// if this is a compound assignment.
ExprResult OldLHS = LHS;
LHS = UsualUnaryConversions(LHS.get());
if (LHS.isInvalid())
return QualType();
QualType LHSType = LHS.get()->getType();
if (IsCompAssign) LHS = OldLHS;
// The RHS is simpler.
RHS = UsualUnaryConversions(RHS.get());
if (RHS.isInvalid())
return QualType();
QualType RHSType = RHS.get()->getType();
// C99 6.5.7p2: Each of the operands shall have integer type.
if (!LHSType->hasIntegerRepresentation() ||
!RHSType->hasIntegerRepresentation())
return InvalidOperands(Loc, LHS, RHS);
// C++0x: Don't allow scoped enums. FIXME: Use something better than
// hasIntegerRepresentation() above instead of this.
if (isScopedEnumerationType(LHSType) ||
isScopedEnumerationType(RHSType)) {
return InvalidOperands(Loc, LHS, RHS);
}
// Sanity-check shift operands
DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
// "The type of the result is that of the promoted left operand."
return LHSType;
}
static bool IsWithinTemplateSpecialization(Decl *D) {
if (DeclContext *DC = D->getDeclContext()) {
if (isa<ClassTemplateSpecializationDecl>(DC))
return true;
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
return FD->isFunctionTemplateSpecialization();
}
return false;
}
/// If two different enums are compared, raise a warning.
static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
Expr *RHS) {
QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
if (!LHSEnumType)
return;
const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
if (!RHSEnumType)
return;
// Ignore anonymous enums.
if (!LHSEnumType->getDecl()->getIdentifier())
return;
if (!RHSEnumType->getDecl()->getIdentifier())
return;
if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
return;
S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
<< LHSStrippedType << RHSStrippedType
<< LHS->getSourceRange() << RHS->getSourceRange();
}
/// \brief Diagnose bad pointer comparisons.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
ExprResult &LHS, ExprResult &RHS,
bool IsError) {
S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
: diag::ext_typecheck_comparison_of_distinct_pointers)
<< LHS.get()->getType() << RHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
/// \brief Returns false if the pointers are converted to a composite type,
/// true otherwise.
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
ExprResult &LHS, ExprResult &RHS) {
// C++ [expr.rel]p2:
// [...] Pointer conversions (4.10) and qualification
// conversions (4.4) are performed on pointer operands (or on
// a pointer operand and a null pointer constant) to bring
// them to their composite pointer type. [...]
//
// C++ [expr.eq]p1 uses the same notion for (in)equality
// comparisons of pointers.
QualType LHSType = LHS.get()->getType();
QualType RHSType = RHS.get()->getType();
assert(LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
if (T.isNull()) {
if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
(RHSType->isPointerType() || RHSType->isMemberPointerType()))
diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
else
S.InvalidOperands(Loc, LHS, RHS);
return true;
}
LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
return false;
}
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
ExprResult &LHS,
ExprResult &RHS,
bool IsError) {
S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
: diag::ext_typecheck_comparison_of_fptr_to_void)
<< LHS.get()->getType() << RHS.get()->getType()
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
static bool isObjCObjectLiteral(ExprResult &E) {
switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
case Stmt::ObjCArrayLiteralClass:
case Stmt::ObjCDictionaryLiteralClass:
case Stmt::ObjCStringLiteralClass:
case Stmt::ObjCBoxedExprClass:
return true;
default:
// Note that ObjCBoolLiteral is NOT an object literal!
return false;
}
}
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
const ObjCObjectPointerType *Type =
LHS->getType()->getAs<ObjCObjectPointerType>();
// If this is not actually an Objective-C object, bail out.
if (!Type)
return false;
// Get the LHS object's interface type.
QualType InterfaceType = Type->getPointeeType();
// If the RHS isn't an Objective-C object, bail out.
if (!RHS->getType()->isObjCObjectPointerType())
return false;
// Try to find the -isEqual: method.
Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
InterfaceType,
/*instance=*/true);
if (!Method) {
if (Type->isObjCIdType()) {
// For 'id', just check the global pool.
Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
/*receiverId=*/true);
} else {
// Check protocols.
Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
/*instance=*/true);
}
}
if (!Method)
return false;
QualType T = Method->parameters()[0]->getType();
if (!T->isObjCObjectPointerType())
return false;
QualType R = Method->getReturnType();
if (!R->isScalarType())
return false;
return true;
}
Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
FromE = FromE->IgnoreParenImpCasts();
switch (FromE->getStmtClass()) {
default:
break;
case Stmt::ObjCStringLiteralClass:
// "string literal"
return LK_String;
case Stmt::ObjCArrayLiteralClass:
// "array literal"
return LK_Array;
case Stmt::ObjCDictionaryLiteralClass:
// "dictionary literal"
return LK_Dictionary;
case Stmt::BlockExprClass:
return LK_Block;
case Stmt::ObjCBoxedExprClass: {
Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
switch (Inner->getStmtClass()) {
case Stmt::IntegerLiteralClass:
case Stmt::FloatingLiteralClass:
case Stmt::CharacterLiteralClass:
case Stmt::ObjCBoolLiteralExprClass:
case Stmt::CXXBoolLiteralExprClass:
// "numeric literal"
return LK_Numeric;
case Stmt::ImplicitCastExprClass: {
CastKind CK = cast<CastExpr>(Inner)->getCastKind();
// Boolean literals can be represented by implicit casts.
if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
return LK_Numeric;
break;
}
default:
break;
}
return LK_Boxed;
}
}
return LK_None;
}
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
ExprResult &LHS, ExprResult &RHS,
BinaryOperator::Opcode Opc){
Expr *Literal;
Expr *Other;
if (isObjCObjectLiteral(LHS)) {
Literal = LHS.get();
Other = RHS.get();
} else {
Literal = RHS.get();
Other = LHS.get();
}
// Don't warn on comparisons against nil.
Other = Other->IgnoreParenCasts();
if (Other->isNullPointerConstant(S.getASTContext(),
Expr::NPC_ValueDependentIsNotNull))
return;
// This should be kept in sync with warn_objc_literal_comparison.
// LK_String should always be after the other literals, since it has its own
// warning flag.
Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
assert(LiteralKind != Sema::LK_Block);
if (LiteralKind == Sema::LK_None) {
llvm_unreachable("Unknown Objective-C object literal kind");
}
if (LiteralKind == Sema::LK_String)
S.Diag(Loc, diag::warn_objc_string_literal_comparison)
<< Literal->getSourceRange();
else
S.Diag(Loc, diag::warn_objc_literal_comparison)
<< LiteralKind << Literal->getSourceRange();
if (BinaryOperator::isEqualityOp(Opc) &&
hasIsEqualMethod(S, LHS.get(), RHS.get())) {
SourceLocation Start = LHS.get()->getLocStart();
SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
CharSourceRange OpRange =
CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
<< FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
<< FixItHint::CreateReplacement(OpRange, " isEqual:")
<< FixItHint::CreateInsertion(End, "]");
}
}
/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc) {
// Check that left hand side is !something.
UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
if (!UO || UO->getOpcode() != UO_LNot) return;
// Only check if the right hand side is non-bool arithmetic type.
if (RHS.get()->isKnownToHaveBooleanValue()) return;
// Make sure that the something in !something is not bool.
Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
if (SubExpr->isKnownToHaveBooleanValue()) return;
// Emit warning.
bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
<< Loc << IsBitwiseOp;
// First note suggest !(x < y)
SourceLocation FirstOpen = SubExpr->getLocStart();
SourceLocation FirstClose = RHS.get()->getLocEnd();
FirstClose = S.getLocForEndOfToken(FirstClose);
if (FirstClose.isInvalid())
FirstOpen = SourceLocation();
S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
<< IsBitwiseOp
<< FixItHint::CreateInsertion(FirstOpen, "(")
<< FixItHint::CreateInsertion(FirstClose, ")");
// Second note suggests (!x) < y
SourceLocation SecondOpen = LHS.get()->getLocStart();
SourceLocation SecondClose = LHS.get()->getLocEnd();
SecondClose = S.getLocForEndOfToken(SecondClose);
if (SecondClose.isInvalid())
SecondOpen = SourceLocation();
S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
<< FixItHint::CreateInsertion(SecondOpen, "(")
<< FixItHint::CreateInsertion(SecondClose, ")");
}
// Get the decl for a simple expression: a reference to a variable,
// an implicit C++ field reference, or an implicit ObjC ivar reference.
static ValueDecl *getCompareDecl(Expr *E) {
if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
return DR->getDecl();
if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
if (Ivar->isFreeIvar())
return Ivar->getDecl();
}
if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
if (Mem->isImplicitAccess())
return Mem->getMemberDecl();
}
return nullptr;
}
// C99 6.5.8, C++ [expr.rel]
QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, BinaryOperatorKind Opc,
bool IsRelational) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
// Handle vector comparisons separately.
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType())
return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
QualType LHSType = LHS.get()->getType();
QualType RHSType = RHS.get()->getType();
Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
if (!LHSType->hasFloatingRepresentation() &&
!(LHSType->isBlockPointerType() && IsRelational) &&
!LHS.get()->getLocStart().isMacroID() &&
!RHS.get()->getLocStart().isMacroID() &&
!inTemplateInstantiation()) {
// For non-floating point types, check for self-comparisons of the form
// x == x, x != x, x < x, etc. These always evaluate to a constant, and
// often indicate logic errors in the program.
//
// NOTE: Don't warn about comparison expressions resulting from macro
// expansion. Also don't warn about comparisons which are only self
// comparisons within a template specialization. The warnings should catch
// obvious cases in the definition of the template anyways. The idea is to
// warn when the typed comparison operator will always evaluate to the same
// result.
ValueDecl *DL = getCompareDecl(LHSStripped);
ValueDecl *DR = getCompareDecl(RHSStripped);
if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
<< 0 // self-
<< (Opc == BO_EQ
|| Opc == BO_LE
|| Opc == BO_GE));
} else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
!DL->getType()->isReferenceType() &&
!DR->getType()->isReferenceType()) {
// what is it always going to eval to?
char always_evals_to;
switch(Opc) {
case BO_EQ: // e.g. array1 == array2
always_evals_to = 0; // false
break;
case BO_NE: // e.g. array1 != array2
always_evals_to = 1; // true
break;
default:
// best we can say is 'a constant'
always_evals_to = 2; // e.g. array1 <= array2
break;
}
DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
<< 1 // array
<< always_evals_to);
}
if (isa<CastExpr>(LHSStripped))
LHSStripped = LHSStripped->IgnoreParenCasts();
if (isa<CastExpr>(RHSStripped))
RHSStripped = RHSStripped->IgnoreParenCasts();
// Warn about comparisons against a string constant (unless the other
// operand is null), the user probably wants strcmp.
Expr *literalString = nullptr;
Expr *literalStringStripped = nullptr;
if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
!RHSStripped->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull)) {
literalString = LHS.get();
literalStringStripped = LHSStripped;
} else if ((isa<StringLiteral>(RHSStripped) ||
isa<ObjCEncodeExpr>(RHSStripped)) &&
!LHSStripped->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull)) {
literalString = RHS.get();
literalStringStripped = RHSStripped;
}
if (literalString) {
DiagRuntimeBehavior(Loc, nullptr,
PDiag(diag::warn_stringcompare)
<< isa<ObjCEncodeExpr>(literalStringStripped)
<< literalString->getSourceRange());
}
}
// C99 6.5.8p3 / C99 6.5.9p4
UsualArithmeticConversions(LHS, RHS);
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
LHSType = LHS.get()->getType();
RHSType = RHS.get()->getType();
// The result of comparisons is 'bool' in C++, 'int' in C.
QualType ResultTy = Context.getLogicalOperationType();
if (IsRelational) {
if (LHSType->isRealType() && RHSType->isRealType())
return ResultTy;
} else {
// Check for comparisons of floating point operands using != and ==.
if (LHSType->hasFloatingRepresentation())
CheckFloatComparison(Loc, LHS.get(), RHS.get());
if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
return ResultTy;
}
const Expr::NullPointerConstantKind LHSNullKind =
LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
const Expr::NullPointerConstantKind RHSNullKind =
RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
if (!IsRelational && LHSIsNull != RHSIsNull) {
bool IsEquality = Opc == BO_EQ;
if (RHSIsNull)
DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
RHS.get()->getSourceRange());
else
DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
LHS.get()->getSourceRange());
}
if ((LHSType->isIntegerType() && !LHSIsNull) ||
(RHSType->isIntegerType() && !RHSIsNull)) {
// Skip normal pointer conversion checks in this case; we have better
// diagnostics for this below.
} else if (getLangOpts().CPlusPlus) {
// Equality comparison of a function pointer to a void pointer is invalid,
// but we allow it as an extension.
// FIXME: If we really want to allow this, should it be part of composite
// pointer type computation so it works in conditionals too?
if (!IsRelational &&
((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
(RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
// This is a gcc extension compatibility comparison.
// In a SFINAE context, we treat this as a hard error to maintain
// conformance with the C++ standard.
diagnoseFunctionPointerToVoidComparison(
*this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
if (isSFINAEContext())
return QualType();
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
return ResultTy;
}
// C++ [expr.eq]p2:
// If at least one operand is a pointer [...] bring them to their
// composite pointer type.
// C++ [expr.rel]p2:
// If both operands are pointers, [...] bring them to their composite
// pointer type.
if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
(IsRelational ? 2 : 1) &&
(!LangOpts.ObjCAutoRefCount ||
!(LHSType->isObjCObjectPointerType() ||
RHSType->isObjCObjectPointerType()))) {
if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
return QualType();
else
return ResultTy;
}
} else if (LHSType->isPointerType() &&
RHSType->isPointerType()) { // C99 6.5.8p2
// All of the following pointer-related warnings are GCC extensions, except
// when handling null pointer constants.
QualType LCanPointeeTy =
LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
QualType RCanPointeeTy =
RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
// C99 6.5.9p2 and C99 6.5.8p2
if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
// Valid unless a relational comparison of function pointers
if (IsRelational && LCanPointeeTy->isFunctionType()) {
Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
<< LHSType << RHSType << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
}
} else if (!IsRelational &&
(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
// Valid unless comparison between non-null pointer and function pointer
if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
&& !LHSIsNull && !RHSIsNull)
diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
/*isError*/false);
} else {
// Invalid
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
}
if (LCanPointeeTy != RCanPointeeTy) {
// Treat NULL constant as a special case in OpenCL.
if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
const PointerType *LHSPtr = LHSType->getAs<PointerType>();
if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
Diag(Loc,
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
<< LHSType << RHSType << 0 /* comparison */
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
}
}
unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
: CK_BitCast;
if (LHSIsNull && !RHSIsNull)
LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
else
RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
}
return ResultTy;
}
if (getLangOpts().CPlusPlus) {
// C++ [expr.eq]p4:
// Two operands of type std::nullptr_t or one operand of type
// std::nullptr_t and the other a null pointer constant compare equal.
if (!IsRelational && LHSIsNull && RHSIsNull) {
if (LHSType->isNullPtrType()) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
return ResultTy;
}
if (RHSType->isNullPtrType()) {
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
return ResultTy;
}
}
// Comparison of Objective-C pointers and block pointers against nullptr_t.
// These aren't covered by the composite pointer type rules.
if (!IsRelational && RHSType->isNullPtrType() &&
(LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
return ResultTy;
}
if (!IsRelational && LHSType->isNullPtrType() &&
(RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
return ResultTy;
}
if (IsRelational &&
((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
(RHSType->isNullPtrType() && LHSType->isPointerType()))) {
// HACK: Relational comparison of nullptr_t against a pointer type is
// invalid per DR583, but we allow it within std::less<> and friends,
// since otherwise common uses of it break.
// FIXME: Consider removing this hack once LWG fixes std::less<> and
// friends to have std::nullptr_t overload candidates.
DeclContext *DC = CurContext;
if (isa<FunctionDecl>(DC))
DC = DC->getParent();
if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
if (CTSD->isInStdNamespace() &&
llvm::StringSwitch<bool>(CTSD->getName())
.Cases("less", "less_equal", "greater", "greater_equal", true)
.Default(false)) {
if (RHSType->isNullPtrType())
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
else
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
return ResultTy;
}
}
}
// C++ [expr.eq]p2:
// If at least one operand is a pointer to member, [...] bring them to
// their composite pointer type.
if (!IsRelational &&
(LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
return QualType();
else
return ResultTy;
}
// Handle scoped enumeration types specifically, since they don't promote
// to integers.
if (LHS.get()->getType()->isEnumeralType() &&
Context.hasSameUnqualifiedType(LHS.get()->getType(),
RHS.get()->getType()))
return ResultTy;
}
// Handle block pointer types.
if (!IsRelational && LHSType->isBlockPointerType() &&
RHSType->isBlockPointerType()) {
QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
if (!LHSIsNull && !RHSIsNull &&
!Context.typesAreCompatible(lpointee, rpointee)) {
Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
<< LHSType << RHSType << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
}
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
return ResultTy;
}
// Allow block pointers to be compared with null pointer constants.
if (!IsRelational
&& ((LHSType->isBlockPointerType() && RHSType->isPointerType())
|| (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
if (!LHSIsNull && !RHSIsNull) {
if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
->getPointeeType()->isVoidType())
|| (LHSType->isPointerType() && LHSType->castAs<PointerType>()
->getPointeeType()->isVoidType())))
Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
<< LHSType << RHSType << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
}
if (LHSIsNull && !RHSIsNull)
LHS = ImpCastExprToType(LHS.get(), RHSType,
RHSType->isPointerType() ? CK_BitCast
: CK_AnyPointerToBlockPointerCast);
else
RHS = ImpCastExprToType(RHS.get(), LHSType,
LHSType->isPointerType() ? CK_BitCast
: CK_AnyPointerToBlockPointerCast);
return ResultTy;
}
if (LHSType->isObjCObjectPointerType() ||
RHSType->isObjCObjectPointerType()) {
const PointerType *LPT = LHSType->getAs<PointerType>();
const PointerType *RPT = RHSType->getAs<PointerType>();
if (LPT || RPT) {
bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
if (!LPtrToVoid && !RPtrToVoid &&
!Context.typesAreCompatible(LHSType, RHSType)) {
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
/*isError*/false);
}
if (LHSIsNull && !RHSIsNull) {
Expr *E = LHS.get();
if (getLangOpts().ObjCAutoRefCount)
CheckObjCConversion(SourceRange(), RHSType, E,
CCK_ImplicitConversion);
LHS = ImpCastExprToType(E, RHSType,
RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
}
else {
Expr *E = RHS.get();
if (getLangOpts().ObjCAutoRefCount)
CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
/*Diagnose=*/true,
/*DiagnoseCFAudited=*/false, Opc);
RHS = ImpCastExprToType(E, LHSType,
LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
}
return ResultTy;
}
if (LHSType->isObjCObjectPointerType() &&
RHSType->isObjCObjectPointerType()) {
if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
/*isError*/false);
if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
if (LHSIsNull && !RHSIsNull)
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
else
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
return ResultTy;
}
}
if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
(LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
unsigned DiagID = 0;
bool isError = false;
if (LangOpts.DebuggerSupport) {
// Under a debugger, allow the comparison of pointers to integers,
// since users tend to want to compare addresses.
} else if ((LHSIsNull && LHSType->isIntegerType()) ||
(RHSIsNull && RHSType->isIntegerType())) {
if (IsRelational) {
isError = getLangOpts().CPlusPlus;
DiagID =
isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
: diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
}
} else if (getLangOpts().CPlusPlus) {
DiagID = diag::err_typecheck_comparison_of_pointer_integer;
isError = true;
} else if (IsRelational)
DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
else
DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
if (DiagID) {
Diag(Loc, DiagID)
<< LHSType << RHSType << LHS.get()->getSourceRange()
<< RHS.get()->getSourceRange();
if (isError)
return QualType();
}
if (LHSType->isIntegerType())
LHS = ImpCastExprToType(LHS.get(), RHSType,
LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
else
RHS = ImpCastExprToType(RHS.get(), LHSType,
RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
return ResultTy;
}
// Handle block pointers.
if (!IsRelational && RHSIsNull
&& LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
return ResultTy;
}
if (!IsRelational && LHSIsNull
&& LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
return ResultTy;
}
if (getLangOpts().OpenCLVersion >= 200) {
if (LHSIsNull && RHSType->isQueueT()) {
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
return ResultTy;
}
if (LHSType->isQueueT() && RHSIsNull) {
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
return ResultTy;
}
}
return InvalidOperands(Loc, LHS, RHS);
}
// Return a signed ext_vector_type that is of identical size and number of
// elements. For floating point vectors, return an integer type of identical
// size and number of elements. In the non ext_vector_type case, search from
// the largest type to the smallest type to avoid cases where long long == long,
// where long gets picked over long long.
QualType Sema::GetSignedVectorType(QualType V) {
const VectorType *VTy = V->getAs<VectorType>();
unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
if (isa<ExtVectorType>(VTy)) {
if (TypeSize == Context.getTypeSize(Context.CharTy))
return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
else if (TypeSize == Context.getTypeSize(Context.ShortTy))
return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
else if (TypeSize == Context.getTypeSize(Context.IntTy))
return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
else if (TypeSize == Context.getTypeSize(Context.LongTy))
return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare");
return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
}
if (TypeSize == Context.getTypeSize(Context.LongLongTy))
return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
VectorType::GenericVector);
else if (TypeSize == Context.getTypeSize(Context.LongTy))
return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
VectorType::GenericVector);
else if (TypeSize == Context.getTypeSize(Context.IntTy))
return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
VectorType::GenericVector);
else if (TypeSize == Context.getTypeSize(Context.ShortTy))
return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
VectorType::GenericVector);
assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
"Unhandled vector element size in vector compare");
return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
VectorType::GenericVector);
}
/// CheckVectorCompareOperands - vector comparisons are a clang extension that
/// operates on extended vector types. Instead of producing an IntTy result,
/// like a scalar comparison, a vector comparison produces a vector of integer
/// types.
QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
bool IsRelational) {
// Check to make sure we're operating on vectors of the same type and width,
// Allowing one side to be a scalar of element type.
QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
/*AllowBothBool*/true,
/*AllowBoolConversions*/getLangOpts().ZVector);
if (vType.isNull())
return vType;
QualType LHSType = LHS.get()->getType();
// If AltiVec, the comparison results in a numeric type, i.e.
// bool for C++, int for C
if (getLangOpts().AltiVec &&
vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
return Context.getLogicalOperationType();
// For non-floating point types, check for self-comparisons of the form
// x == x, x != x, x < x, etc. These always evaluate to a constant, and
// often indicate logic errors in the program.
if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
if (DeclRefExpr* DRL
= dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
if (DeclRefExpr* DRR
= dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
if (DRL->getDecl() == DRR->getDecl())
DiagRuntimeBehavior(Loc, nullptr,
PDiag(diag::warn_comparison_always)
<< 0 // self-
<< 2 // "a constant"
);
}
// Check for comparisons of floating point operands using != and ==.
if (!IsRelational && LHSType->hasFloatingRepresentation()) {
assert (RHS.get()->getType()->hasFloatingRepresentation());
CheckFloatComparison(Loc, LHS.get(), RHS.get());
}
// Return a signed type for the vector.
return GetSignedVectorType(vType);
}
QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc) {
// Ensure that either both operands are of the same vector type, or
// one operand is of a vector type and the other is of its element type.
QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
/*AllowBothBool*/true,
/*AllowBoolConversions*/false);
if (vType.isNull())
return InvalidOperands(Loc, LHS, RHS);
if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
vType->hasFloatingRepresentation())
return InvalidOperands(Loc, LHS, RHS);
return GetSignedVectorType(LHS.get()->getType());
}
inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc) {
checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
bool IsCompAssign =
Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
if (LHS.get()->getType()->isVectorType() ||
RHS.get()->getType()->isVectorType()) {
if (LHS.get()->getType()->hasIntegerRepresentation() &&
RHS.get()->getType()->hasIntegerRepresentation())
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
/*AllowBothBool*/true,
/*AllowBoolConversions*/getLangOpts().ZVector);
return InvalidOperands(Loc, LHS, RHS);
}
if (Opc == BO_And)
diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
ExprResult LHSResult = LHS, RHSResult = RHS;
QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
IsCompAssign);
if (LHSResult.isInvalid() || RHSResult.isInvalid())
return QualType();
LHS = LHSResult.get();
RHS = RHSResult.get();
if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
return compType;
return InvalidOperands(Loc, LHS, RHS);
}
// C99 6.5.[13,14]
inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc) {
// Check vector operands differently.
if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
return CheckVectorLogicalOperands(LHS, RHS, Loc);
// Diagnose cases where the user write a logical and/or but probably meant a
// bitwise one. We do this when the LHS is a non-bool integer and the RHS
// is a constant.
if (LHS.get()->getType()->isIntegerType() &&
!LHS.get()->getType()->isBooleanType() &&
RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
// Don't warn in macros or template instantiations.
!Loc.isMacroID() && !inTemplateInstantiation()) {
// If the RHS can be constant folded, and if it constant folds to something
// that isn't 0 or 1 (which indicate a potential logical operation that
// happened to fold to true/false) then warn.
// Parens on the RHS are ignored.
llvm::APSInt Result;
if (RHS.get()->EvaluateAsInt(Result, Context))
if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
!RHS.get()->getExprLoc().isMacroID()) ||
(Result != 0 && Result != 1)) {
Diag(Loc, diag::warn_logical_instead_of_bitwise)
<< RHS.get()->getSourceRange()
<< (Opc == BO_LAnd ? "&&" : "||");
// Suggest replacing the logical operator with the bitwise version
Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
<< (Opc == BO_LAnd ? "&" : "|")
<< FixItHint::CreateReplacement(SourceRange(
Loc, getLocForEndOfToken(Loc)),
Opc == BO_LAnd ? "&" : "|");
if (Opc == BO_LAnd)
// Suggest replacing "Foo() && kNonZero" with "Foo()"
Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
<< FixItHint::CreateRemoval(
SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
RHS.get()->getLocEnd()));
}
}
if (!Context.getLangOpts().CPlusPlus) {
// OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
// not operate on the built-in scalar and vector float types.
if (Context.getLangOpts().OpenCL &&
Context.getLangOpts().OpenCLVersion < 120) {
if (LHS.get()->getType()->isFloatingType() ||
RHS.get()->getType()->isFloatingType())
return InvalidOperands(Loc, LHS, RHS);
}
LHS = UsualUnaryConversions(LHS.get());
if (LHS.isInvalid())
return QualType();
RHS = UsualUnaryConversions(RHS.get());
if (RHS.isInvalid())
return QualType();
if (!LHS.get()->getType()->isScalarType() ||
!RHS.get()->getType()->isScalarType())
return InvalidOperands(Loc, LHS, RHS);
return Context.IntTy;
}
// The following is safe because we only use this method for
// non-overloadable operands.
// C++ [expr.log.and]p1
// C++ [expr.log.or]p1
// The operands are both contextually converted to type bool.
ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
if (LHSRes.isInvalid())
return InvalidOperands(Loc, LHS, RHS);
LHS = LHSRes;
ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
if (RHSRes.isInvalid())
return InvalidOperands(Loc, LHS, RHS);
RHS = RHSRes;
// C++ [expr.log.and]p2
// C++ [expr.log.or]p2
// The result is a bool.
return Context.BoolTy;
}
static bool IsReadonlyMessage(Expr *E, Sema &S) {
const MemberExpr *ME = dyn_cast<MemberExpr>(E);
if (!ME) return false;
if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
if (!Base) return false;
return Base->getMethodDecl() != nullptr;
}
/// Is the given expression (which must be 'const') a reference to a
/// variable which was originally non-const, but which has become
/// 'const' due to being captured within a block?
enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
assert(E->isLValue() && E->getType().isConstQualified());
E = E->IgnoreParens();
// Must be a reference to a declaration from an enclosing scope.
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
if (!DRE) return NCCK_None;
if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
// The declaration must be a variable which is not declared 'const'.
VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
if (!var) return NCCK_None;
if (var->getType().isConstQualified()) return NCCK_None;
assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
// Decide whether the first capture was for a block or a lambda.
DeclContext *DC = S.CurContext, *Prev = nullptr;
// Decide whether the first capture was for a block or a lambda.
while (DC) {
// For init-capture, it is possible that the variable belongs to the
// template pattern of the current context.
if (auto *FD = dyn_cast<FunctionDecl>(DC))
if (var->isInitCapture() &&
FD->getTemplateInstantiationPattern() == var->getDeclContext())
break;
if (DC == var->getDeclContext())
break;
Prev = DC;
DC = DC->getParent();
}
// Unless we have an init-capture, we've gone one step too far.
if (!var->isInitCapture())
DC = Prev;
return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
}
static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
Ty = Ty.getNonReferenceType();
if (IsDereference && Ty->isPointerType())
Ty = Ty->getPointeeType();
return !Ty.isConstQualified();
}
/// Emit the "read-only variable not assignable" error and print notes to give
/// more information about why the variable is not assignable, such as pointing
/// to the declaration of a const variable, showing that a method is const, or
/// that the function is returning a const reference.
static void DiagnoseConstAssignment(Sema &S, const Expr *E,
SourceLocation Loc) {
// Update err_typecheck_assign_const and note_typecheck_assign_const
// when this enum is changed.
enum {
ConstFunction,
ConstVariable,
ConstMember,
ConstMethod,
ConstUnknown, // Keep as last element
};
SourceRange ExprRange = E->getSourceRange();
// Only emit one error on the first const found. All other consts will emit
// a note to the error.
bool DiagnosticEmitted = false;
// Track if the current expression is the result of a dereference, and if the
// next checked expression is the result of a dereference.
bool IsDereference = false;
bool NextIsDereference = false;
// Loop to process MemberExpr chains.
while (true) {
IsDereference = NextIsDereference;
E = E->IgnoreImplicit()->IgnoreParenImpCasts();
if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
NextIsDereference = ME->isArrow();
const ValueDecl *VD = ME->getMemberDecl();
if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
// Mutable fields can be modified even if the class is const.
if (Field->isMutable()) {
assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
break;
}
if (!IsTypeModifiable(Field->getType(), IsDereference)) {
if (!DiagnosticEmitted) {
S.Diag(Loc, diag::err_typecheck_assign_const)
<< ExprRange << ConstMember << false /*static*/ << Field
<< Field->getType();
DiagnosticEmitted = true;
}
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
<< ConstMember << false /*static*/ << Field << Field->getType()
<< Field->getSourceRange();
}
E = ME->getBase();
continue;
} else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
if (VDecl->getType().isConstQualified()) {
if (!DiagnosticEmitted) {
S.Diag(Loc, diag::err_typecheck_assign_const)
<< ExprRange << ConstMember << true /*static*/ << VDecl
<< VDecl->getType();
DiagnosticEmitted = true;
}
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
<< ConstMember << true /*static*/ << VDecl << VDecl->getType()
<< VDecl->getSourceRange();
}
// Static fields do not inherit constness from parents.
break;
}
break;
} // End MemberExpr
break;
}
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
// Function calls
const FunctionDecl *FD = CE->getDirectCallee();
if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
if (!DiagnosticEmitted) {
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
<< ConstFunction << FD;
DiagnosticEmitted = true;
}
S.Diag(FD->getReturnTypeSourceRange().getBegin(),
diag::note_typecheck_assign_const)
<< ConstFunction << FD << FD->getReturnType()
<< FD->getReturnTypeSourceRange();
}
} else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
// Point to variable declaration.
if (const ValueDecl *VD = DRE->getDecl()) {
if (!IsTypeModifiable(VD->getType(), IsDereference)) {
if (!DiagnosticEmitted) {
S.Diag(Loc, diag::err_typecheck_assign_const)
<< ExprRange << ConstVariable << VD << VD->getType();
DiagnosticEmitted = true;
}
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
<< ConstVariable << VD << VD->getType() << VD->getSourceRange();
}
}
} else if (isa<CXXThisExpr>(E)) {
if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
if (MD->isConst()) {
if (!DiagnosticEmitted) {
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
<< ConstMethod << MD;
DiagnosticEmitted = true;
}
S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
<< ConstMethod << MD << MD->getSourceRange();
}
}
}
}
if (DiagnosticEmitted)
return;
// Can't determine a more specific message, so display the generic error.
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
}
/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
/// emit an error and return true. If so, return false.
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
S.CheckShadowingDeclModification(E, Loc);
SourceLocation OrigLoc = Loc;
Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
&Loc);
if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
IsLV = Expr::MLV_InvalidMessageExpression;
if (IsLV == Expr::MLV_Valid)
return false;
unsigned DiagID = 0;
bool NeedType = false;
switch (IsLV) { // C99 6.5.16p2
case Expr::MLV_ConstQualified:
// Use a specialized diagnostic when we're assigning to an object
// from an enclosing function or block.
if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
if (NCCK == NCCK_Block)
DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
else
DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
break;
}
// In ARC, use some specialized diagnostics for occasions where we
// infer 'const'. These are always pseudo-strong variables.
if (S.getLangOpts().ObjCAutoRefCount) {
DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
if (declRef && isa<VarDecl>(declRef->getDecl())) {
VarDecl *var = cast<VarDecl>(declRef->getDecl());
// Use the normal diagnostic if it's pseudo-__strong but the
// user actually wrote 'const'.
if (var->isARCPseudoStrong() &&
(!var->getTypeSourceInfo() ||
!var->getTypeSourceInfo()->getType().isConstQualified())) {
// There are two pseudo-strong cases:
// - self
ObjCMethodDecl *method = S.getCurMethodDecl();
if (method && var == method->getSelfDecl())
DiagID = method->isClassMethod()
? diag::err_typecheck_arc_assign_self_class_method
: diag::err_typecheck_arc_assign_self;
// - fast enumeration variables
else
DiagID = diag::err_typecheck_arr_assign_enumeration;
SourceRange Assign;
if (Loc != OrigLoc)
Assign = SourceRange(OrigLoc, OrigLoc);
S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
// We need to preserve the AST regardless, so migration tool
// can do its job.
return false;
}
}
}
// If none of the special cases above are triggered, then this is a
// simple const assignment.
if (DiagID == 0) {
DiagnoseConstAssignment(S, E, Loc);
return true;
}
break;
case Expr::MLV_ConstAddrSpace:
DiagnoseConstAssignment(S, E, Loc);
return true;
case Expr::MLV_ArrayType:
case Expr::MLV_ArrayTemporary:
DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
NeedType = true;
break;
case Expr::MLV_NotObjectType:
DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
NeedType = true;
break;
case Expr::MLV_LValueCast:
DiagID = diag::err_typecheck_lvalue_casts_not_supported;
break;
case Expr::MLV_Valid:
llvm_unreachable("did not take early return for MLV_Valid");
case Expr::MLV_InvalidExpression:
case Expr::MLV_MemberFunction:
case Expr::MLV_ClassTemporary:
DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
break;
case Expr::MLV_IncompleteType:
case Expr::MLV_IncompleteVoidType:
return S.RequireCompleteType(Loc, E->getType(),
diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
case Expr::MLV_DuplicateVectorComponents:
DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
break;
case Expr::MLV_NoSetterProperty:
llvm_unreachable("readonly properties should be processed differently");
case Expr::MLV_InvalidMessageExpression:
DiagID = diag::err_readonly_message_assignment;
break;
case Expr::MLV_SubObjCPropertySetting:
DiagID = diag::err_no_subobject_property_setting;
break;
}
SourceRange Assign;
if (Loc != OrigLoc)
Assign = SourceRange(OrigLoc, OrigLoc);
if (NeedType)
S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
else
S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
return true;
}
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation Loc,
Sema &Sema) {
// C / C++ fields
MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
}
// Objective-C instance variables
ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
if (OL && OR && OL->getDecl() == OR->getDecl()) {
DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
if (RL && RR && RL->getDecl() == RR->getDecl())
Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
}
}
// C99 6.5.16.1
QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
SourceLocation Loc,
QualType CompoundType) {
assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
// Verify that LHS is a modifiable lvalue, and emit error if not.
if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
return QualType();
QualType LHSType = LHSExpr->getType();
QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
CompoundType;
// OpenCL v1.2 s6.1.1.1 p2:
// The half data type can only be used to declare a pointer to a buffer that
// contains half values
if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
LHSType->isHalfType()) {
Diag(Loc, diag::err_opencl_half_load_store) << 1
<< LHSType.getUnqualifiedType();
return QualType();
}
AssignConvertType ConvTy;
if (CompoundType.isNull()) {
Expr *RHSCheck = RHS.get();
CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
QualType LHSTy(LHSType);
ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
if (RHS.isInvalid())
return QualType();
// Special case of NSObject attributes on c-style pointer types.
if (ConvTy == IncompatiblePointer &&
((Context.isObjCNSObjectType(LHSType) &&
RHSType->isObjCObjectPointerType()) ||
(Context.isObjCNSObjectType(RHSType) &&
LHSType->isObjCObjectPointerType())))
ConvTy = Compatible;
if (ConvTy == Compatible &&
LHSType->isObjCObjectType())
Diag(Loc, diag::err_objc_object_assignment)
<< LHSType;
// If the RHS is a unary plus or minus, check to see if they = and + are
// right next to each other. If so, the user may have typo'd "x =+ 4"
// instead of "x += 4".
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
RHSCheck = ICE->getSubExpr();
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
if ((UO->getOpcode() == UO_Plus ||
UO->getOpcode() == UO_Minus) &&
Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
// Only if the two operators are exactly adjacent.
Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
// And there is a space or other character before the subexpr of the
// unary +/-. We don't want to warn on "x=-1".
Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
UO->getSubExpr()->getLocStart().isFileID()) {
Diag(Loc, diag::warn_not_compound_assign)
<< (UO->getOpcode() == UO_Plus ? "+" : "-")
<< SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
}
}
if (ConvTy == Compatible) {
if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
// Warn about retain cycles where a block captures the LHS, but
// not if the LHS is a simple variable into which the block is
// being stored...unless that variable can be captured by reference!
const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
checkRetainCycles(LHSExpr, RHS.get());
}
if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
// It is safe to assign a weak reference into a strong variable.
// Although this code can still have problems:
// id x = self.weakProp;
// id y = self.weakProp;
// we do not warn to warn spuriously when 'x' and 'y' are on separate
// paths through the function. This should be revisited if
// -Wrepeated-use-of-weak is made flow-sensitive.
// For ObjCWeak only, we do not warn if the assign is to a non-weak
// variable, which will be valid for the current autorelease scope.
if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
RHS.get()->getLocStart()))
getCurFunction()->markSafeWeakUse(RHS.get());
} else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
}
}
} else {
// Compound assignment "x += y"
ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
}
if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
RHS.get(), AA_Assigning))
return QualType();
CheckForNullPointerDereference(*this, LHSExpr);
// C99 6.5.16p3: The type of an assignment expression is the type of the
// left operand unless the left operand has qualified type, in which case
// it is the unqualified version of the type of the left operand.
// C99 6.5.16.1p2: In simple assignment, the value of the right operand
// is converted to the type of the assignment expression (above).
// C++ 5.17p1: the type of the assignment expression is that of its left
// operand.
return (getLangOpts().CPlusPlus
? LHSType : LHSType.getUnqualifiedType());
}
// Only ignore explicit casts to void.
static bool IgnoreCommaOperand(const Expr *E) {
E = E->IgnoreParens();
if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
if (CE->getCastKind() == CK_ToVoid) {
return true;
}
}
return false;
}
// Look for instances where it is likely the comma operator is confused with
// another operator. There is a whitelist of acceptable expressions for the
// left hand side of the comma operator, otherwise emit a warning.
void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
// No warnings in macros
if (Loc.isMacroID())
return;
// Don't warn in template instantiations.
if (inTemplateInstantiation())
return;
// Scope isn't fine-grained enough to whitelist the specific cases, so
// instead, skip more than needed, then call back into here with the
// CommaVisitor in SemaStmt.cpp.
// The whitelisted locations are the initialization and increment portions
// of a for loop. The additional checks are on the condition of
// if statements, do/while loops, and for loops.
const unsigned ForIncrementFlags =
Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
const unsigned ScopeFlags = getCurScope()->getFlags();
if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
(ScopeFlags & ForInitFlags) == ForInitFlags)
return;
// If there are multiple comma operators used together, get the RHS of the
// of the comma operator as the LHS.
while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
if (BO->getOpcode() != BO_Comma)
break;
LHS = BO->getRHS();
}
// Only allow some expressions on LHS to not warn.
if (IgnoreCommaOperand(LHS))
return;
Diag(Loc, diag::warn_comma_operator);
Diag(LHS->getLocStart(), diag::note_cast_to_void)
<< LHS->getSourceRange()
<< FixItHint::CreateInsertion(LHS->getLocStart(),
LangOpts.CPlusPlus ? "static_cast<void>("
: "(void)(")
<< FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
")");
}
// C99 6.5.17
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc) {
LHS = S.CheckPlaceholderExpr(LHS.get());
RHS = S.CheckPlaceholderExpr(RHS.get());
if (LHS.isInvalid() || RHS.isInvalid())
return QualType();
// C's comma performs lvalue conversion (C99 6.3.2.1) on both its
// operands, but not unary promotions.
// C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
// So we treat the LHS as a ignored value, and in C++ we allow the
// containing site to determine what should be done with the RHS.
LHS = S.IgnoredValueConversions(LHS.get());
if (LHS.isInvalid())
return QualType();
S.DiagnoseUnusedExprResult(LHS.get());
if (!S.getLangOpts().CPlusPlus) {
RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
if (RHS.isInvalid())
return QualType();
if (!RHS.get()->getType()->isVoidType())
S.RequireCompleteType(Loc, RHS.get()->getType(),
diag::err_incomplete_type);
}
if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
S.DiagnoseCommaOperator(LHS.get(), Loc);
return RHS.get()->getType();
}
/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
ExprValueKind &VK,
ExprObjectKind &OK,
SourceLocation OpLoc,
bool IsInc, bool IsPrefix) {
if (Op->isTypeDependent())
return S.Context.DependentTy;
QualType ResType = Op->getType();
// Atomic types can be used for increment / decrement where the non-atomic
// versions can, so ignore the _Atomic() specifier for the purpose of
// checking.
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
ResType = ResAtomicType->getValueType();
assert(!ResType.isNull() && "no type for increment/decrement expression");
if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
// Decrement of bool is not allowed.
if (!IsInc) {
S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
return QualType();
}
// Increment of bool sets it to true, but is deprecated.
S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
: diag::warn_increment_bool)
<< Op->getSourceRange();
} else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
// Error on enum increments and decrements in C++ mode
S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
return QualType();
} else if (ResType->isRealType()) {
// OK!
} else if (ResType->isPointerType()) {
// C99 6.5.2.4p2, 6.5.6p2
if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
return QualType();
} else if (ResType->isObjCObjectPointerType()) {
// On modern runtimes, ObjC pointer arithmetic is forbidden.
// Otherwise, we just need a complete type.
if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
checkArithmeticOnObjCPointer(S, OpLoc, Op))
return QualType();
} else if (ResType->isAnyComplexType()) {
// C99 does not support ++/-- on complex types, we allow as an extension.
S.Diag(OpLoc, diag::ext_integer_increment_complex)
<< ResType << Op->getSourceRange();
} else if (ResType->isPlaceholderType()) {
ExprResult PR = S.CheckPlaceholderExpr(Op);
if (PR.isInvalid()) return QualType();
return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
IsInc, IsPrefix);
} else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
// OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
} else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
(ResType->getAs<VectorType>()->getVectorKind() !=
VectorType::AltiVecBool)) {
// The z vector extensions allow ++ and -- for non-bool vectors.
} else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
// OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
} else {
S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
<< ResType << int(IsInc) << Op->getSourceRange();
return QualType();
}
// At this point, we know we have a real, complex or pointer type.
// Now make sure the operand is a modifiable lvalue.
if (CheckForModifiableLvalue(Op, OpLoc, S))
return QualType();
// In C++, a prefix increment is the same type as the operand. Otherwise
// (in C or with postfix), the increment is the unqualified type of the
// operand.
if (IsPrefix && S.getLangOpts().CPlusPlus) {
VK = VK_LValue;
OK = Op->getObjectKind();
return ResType;
} else {
VK = VK_RValue;
return ResType.getUnqualifiedType();
}
}
/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
/// This routine allows us to typecheck complex/recursive expressions
/// where the declaration is needed for type checking. We only need to
/// handle cases when the expression references a function designator
/// or is an lvalue. Here are some examples:
/// - &(x) => x
/// - &*****f => f for f a function designator.
/// - &s.xx => s
/// - &s.zz[1].yy -> s, if zz is an array
/// - *(x + 1) -> x, if x is an array
/// - &"123"[2] -> 0
/// - & __real__ x -> x
static ValueDecl *getPrimaryDecl(Expr *E) {
switch (E->getStmtClass()) {
case Stmt::DeclRefExprClass:
return cast<DeclRefExpr>(E)->getDecl();
case Stmt::MemberExprClass:
// If this is an arrow operator, the address is an offset from
// the base's value, so the object the base refers to is
// irrelevant.
if (cast<MemberExpr>(E)->isArrow())
return nullptr;
// Otherwise, the expression refers to a part of the base
return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
case Stmt::ArraySubscriptExprClass: {
// FIXME: This code shouldn't be necessary! We should catch the implicit
// promotion of register arrays earlier.
Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
if (ICE->getSubExpr()->getType()->isArrayType())
return getPrimaryDecl(ICE->getSubExpr());
}
return nullptr;
}
case Stmt::UnaryOperatorClass: {
UnaryOperator *UO = cast<UnaryOperator>(E);
switch(UO->getOpcode()) {
case UO_Real:
case UO_Imag:
case UO_Extension:
return getPrimaryDecl(UO->getSubExpr());
default:
return nullptr;
}
}
case Stmt::ParenExprClass:
return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
case Stmt::ImplicitCastExprClass:
// If the result of an implicit cast is an l-value, we care about
// the sub-expression; otherwise, the result here doesn't matter.
return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
default:
return nullptr;
}
}
namespace {
enum {
AO_Bit_Field = 0,
AO_Vector_Element = 1,
AO_Property_Expansion = 2,
AO_Register_Variable = 3,
AO_No_Error = 4
};
}
/// \brief Diagnose invalid operand for address of operations.
///
/// \param Type The type of operand which cannot have its address taken.
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
Expr *E, unsigned Type) {
S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
}
/// CheckAddressOfOperand - The operand of & must be either a function
/// designator or an lvalue designating an object. If it is an lvalue, the
/// object cannot be declared with storage class register or be a bit field.
/// Note: The usual conversions are *not* applied to the operand of the &
/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
/// In C++, the operand might be an overloaded function name, in which case
/// we allow the '&' but retain the overloaded-function type.
QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
if (PTy->getKind() == BuiltinType::Overload) {
Expr *E = OrigOp.get()->IgnoreParens();
if (!isa<OverloadExpr>(E)) {
assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
<< OrigOp.get()->getSourceRange();
return QualType();
}
OverloadExpr *Ovl = cast<OverloadExpr>(E);
if (isa<UnresolvedMemberExpr>(Ovl))
if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
<< OrigOp.get()->getSourceRange();
return QualType();
}
return Context.OverloadTy;
}
if (PTy->getKind() == BuiltinType::UnknownAny)
return Context.UnknownAnyTy;
if (PTy->getKind() == BuiltinType::BoundMember) {
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
<< OrigOp.get()->getSourceRange();
return QualType();
}
OrigOp = CheckPlaceholderExpr(OrigOp.get());
if (OrigOp.isInvalid()) return QualType();
}
if (OrigOp.get()->isTypeDependent())
return Context.DependentTy;
assert(!OrigOp.get()->getType()->isPlaceholderType());
// Make sure to ignore parentheses in subsequent checks
Expr *op = OrigOp.get()->IgnoreParens();
// OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
return QualType();
}
if (getLangOpts().C99) {
// Implement C99-only parts of addressof rules.
if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
if (uOp->getOpcode() == UO_Deref)
// Per C99 6.5.3.2, the address of a deref always returns a valid result
// (assuming the deref expression is valid).
return uOp->getSubExpr()->getType();
}
// Technically, there should be a check for array subscript
// expressions here, but the result of one is always an lvalue anyway.
}
ValueDecl *dcl = getPrimaryDecl(op);
if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
op->getLocStart()))
return QualType();
Expr::LValueClassification lval = op->ClassifyLValue(Context);
unsigned AddressOfError = AO_No_Error;
if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
bool sfinae = (bool)isSFINAEContext();
Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
: diag::ext_typecheck_addrof_temporary)
<< op->getType() << op->getSourceRange();
if (sfinae)
return QualType();
// Materialize the temporary as an lvalue so that we can take its address.
OrigOp = op =
CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
} else if (isa<ObjCSelectorExpr>(op)) {
return Context.getPointerType(op->getType());
} else if (lval == Expr::LV_MemberFunction) {
// If it's an instance method, make a member pointer.
// The expression must have exactly the form &A::foo.
// If the underlying expression isn't a decl ref, give up.
if (!isa<DeclRefExpr>(op)) {
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
<< OrigOp.get()->getSourceRange();
return QualType();
}
DeclRefExpr *DRE = cast<DeclRefExpr>(op);
CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
// The id-expression was parenthesized.
if (OrigOp.get() != DRE) {
Diag(OpLoc, diag::err_parens_pointer_member_function)
<< OrigOp.get()->getSourceRange();
// The method was named without a qualifier.
} else if (!DRE->getQualifier()) {
if (MD->getParent()->getName().empty())
Diag(OpLoc, diag::err_unqualified_pointer_member_function)
<< op->getSourceRange();
else {
SmallString<32> Str;
StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Diag(OpLoc, diag::err_unqualified_pointer_member_function)
<< op->getSourceRange()
<< FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
}
}
// Taking the address of a dtor is illegal per C++ [class.dtor]p2.
if (isa<CXXDestructorDecl>(MD))
Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
QualType MPTy = Context.getMemberPointerType(
op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
// Under the MS ABI, lock down the inheritance model now.
if (Context.getTargetInfo().getCXXABI().isMicrosoft())
(void)isCompleteType(OpLoc, MPTy);
return MPTy;
} else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
// C99 6.5.3.2p1
// The operand must be either an l-value or a function designator
if (!op->getType()->isFunctionType()) {
// Use a special diagnostic for loads from property references.
if (isa<PseudoObjectExpr>(op)) {
AddressOfError = AO_Property_Expansion;
} else {
Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
<< op->getType() << op->getSourceRange();
return QualType();
}
}
} else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
// The operand cannot be a bit-field
AddressOfError = AO_Bit_Field;
} else if (op->getObjectKind() == OK_VectorComponent) {
// The operand cannot be an element of a vector
AddressOfError = AO_Vector_Element;
} else if (dcl) { // C99 6.5.3.2p1
// We have an lvalue with a decl. Make sure the decl is not declared
// with the register storage-class specifier.
if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
// in C++ it is not error to take address of a register
// variable (c++03 7.1.1P3)
if (vd->getStorageClass() == SC_Register &&
!getLangOpts().CPlusPlus) {
AddressOfError = AO_Register_Variable;
}
} else if (isa<MSPropertyDecl>(dcl)) {
AddressOfError = AO_Property_Expansion;
} else if (isa<FunctionTemplateDecl>(dcl)) {
return Context.OverloadTy;
} else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
// Okay: we can take the address of a field.
// Could be a pointer to member, though, if there is an explicit
// scope qualifier for the class.
if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
DeclContext *Ctx = dcl->getDeclContext();
if (Ctx && Ctx->isRecord()) {
if (dcl->getType()->isReferenceType()) {
Diag(OpLoc,
diag::err_cannot_form_pointer_to_member_of_reference_type)
<< dcl->getDeclName() << dcl->getType();
return QualType();
}
while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
Ctx = Ctx->getParent();
QualType MPTy = Context.getMemberPointerType(
op->getType(),
Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
// Under the MS ABI, lock down the inheritance model now.
if (Context.getTargetInfo().getCXXABI().isMicrosoft())
(void)isCompleteType(OpLoc, MPTy);
return MPTy;
}
}
} else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
!isa<BindingDecl>(dcl))
llvm_unreachable("Unknown/unexpected decl type");
}
if (AddressOfError != AO_No_Error) {
diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
return QualType();
}
if (lval == Expr::LV_IncompleteVoidType) {
// Taking the address of a void variable is technically illegal, but we
// allow it in cases which are otherwise valid.
// Example: "extern void x; void* y = &x;".
Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
}
// If the operand has type "type", the result has type "pointer to type".
if (op->getType()->isObjCObjectType())
return Context.getObjCObjectPointerType(op->getType());
CheckAddressOfPackedMember(op);
return Context.getPointerType(op->getType());
}
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
if (!DRE)
return;
const Decl *D = DRE->getDecl();
if (!D)
return;
const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
if (!Param)
return;
if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
return;
if (FunctionScopeInfo *FD = S.getCurFunction())
if (!FD->ModifiedNonNullParams.count(Param))
FD->ModifiedNonNullParams.insert(Param);
}
/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
SourceLocation OpLoc) {
if (Op->isTypeDependent())
return S.Context.DependentTy;
ExprResult ConvResult = S.UsualUnaryConversions(Op);
if (ConvResult.isInvalid())
return QualType();
Op = ConvResult.get();
QualType OpTy = Op->getType();
QualType Result;
if (isa<CXXReinterpretCastExpr>(Op)) {
QualType OpOrigType = Op->IgnoreParenCasts()->getType();
S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
Op->getSourceRange());
}
if (const PointerType *PT = OpTy->getAs<PointerType>())
{
Result = PT->getPointeeType();
}
else if (const ObjCObjectPointerType *OPT =
OpTy->getAs<ObjCObjectPointerType>())
Result = OPT->getPointeeType();
else {
ExprResult PR = S.CheckPlaceholderExpr(Op);
if (PR.isInvalid()) return QualType();
if (PR.get() != Op)
return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
}
if (Result.isNull()) {
S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
<< OpTy << Op->getSourceRange();
return QualType();
}
// Note that per both C89 and C99, indirection is always legal, even if Result
// is an incomplete type or void. It would be possible to warn about
// dereferencing a void pointer, but it's completely well-defined, and such a
// warning is unlikely to catch any mistakes. In C++, indirection is not valid
// for pointers to 'void' but is fine for any other pointer type:
//
// C++ [expr.unary.op]p1:
// [...] the expression to which [the unary * operator] is applied shall
// be a pointer to an object type, or a pointer to a function type
if (S.getLangOpts().CPlusPlus && Result->isVoidType())
S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
<< OpTy << Op->getSourceRange();
// Dereferences are usually l-values...
VK = VK_LValue;
// ...except that certain expressions are never l-values in C.
if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
VK = VK_RValue;
return Result;
}
BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
BinaryOperatorKind Opc;
switch (Kind) {
default: llvm_unreachable("Unknown binop!");
case tok::periodstar: Opc = BO_PtrMemD; break;
case tok::arrowstar: Opc = BO_PtrMemI; break;
case tok::star: Opc = BO_Mul; break;
case tok::slash: Opc = BO_Div; break;
case tok::percent: Opc = BO_Rem; break;
case tok::plus: Opc = BO_Add; break;
case tok::minus: Opc = BO_Sub; break;
case tok::lessless: Opc = BO_Shl; break;
case tok::greatergreater: Opc = BO_Shr; break;
case tok::lessequal: Opc = BO_LE; break;
case tok::less: Opc = BO_LT; break;
case tok::greaterequal: Opc = BO_GE; break;
case tok::greater: Opc = BO_GT; break;
case tok::exclaimequal: Opc = BO_NE; break;
case tok::equalequal: Opc = BO_EQ; break;
case tok::amp: Opc = BO_And; break;
case tok::caret: Opc = BO_Xor; break;
case tok::pipe: Opc = BO_Or; break;
case tok::ampamp: Opc = BO_LAnd; break;
case tok::pipepipe: Opc = BO_LOr; break;
case tok::equal: Opc = BO_Assign; break;
case tok::starequal: Opc = BO_MulAssign; break;
case tok::slashequal: Opc = BO_DivAssign; break;
case tok::percentequal: Opc = BO_RemAssign; break;
case tok::plusequal: Opc = BO_AddAssign; break;
case tok::minusequal: Opc = BO_SubAssign; break;
case tok::lesslessequal: Opc = BO_ShlAssign; break;
case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
case tok::ampequal: Opc = BO_AndAssign; break;
case tok::caretequal: Opc = BO_XorAssign; break;
case tok::pipeequal: Opc = BO_OrAssign; break;
case tok::comma: Opc = BO_Comma; break;
}
return Opc;
}
static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
tok::TokenKind Kind) {
UnaryOperatorKind Opc;
switch (Kind) {
default: llvm_unreachable("Unknown unary op!");
case tok::plusplus: Opc = UO_PreInc; break;
case tok::minusminus: Opc = UO_PreDec; break;
case tok::amp: Opc = UO_AddrOf; break;
case tok::star: Opc = UO_Deref; break;
case tok::plus: Opc = UO_Plus; break;
case tok::minus: Opc = UO_Minus; break;
case tok::tilde: Opc = UO_Not; break;
case tok::exclaim: Opc = UO_LNot; break;
case tok::kw___real: Opc = UO_Real; break;
case tok::kw___imag: Opc = UO_Imag; break;
case tok::kw___extension__: Opc = UO_Extension; break;
}
return Opc;
}
/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
/// This warning is only emitted for builtin assignment operations. It is also
/// suppressed in the event of macro expansions.
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
SourceLocation OpLoc) {
if (S.inTemplateInstantiation())
return;
if (OpLoc.isInvalid() || OpLoc.isMacroID())
return;
LHSExpr = LHSExpr->IgnoreParenImpCasts();
RHSExpr = RHSExpr->IgnoreParenImpCasts();
const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
if (!LHSDeclRef || !RHSDeclRef ||
LHSDeclRef->getLocation().isMacroID() ||
RHSDeclRef->getLocation().isMacroID())
return;
const ValueDecl *LHSDecl =
cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
const ValueDecl *RHSDecl =
cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
if (LHSDecl != RHSDecl)
return;
if (LHSDecl->getType().isVolatileQualified())
return;
if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
if (RefTy->getPointeeType().isVolatileQualified())
return;
S.Diag(OpLoc, diag::warn_self_assignment)
<< LHSDeclRef->getType()
<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
}
/// Check if a bitwise-& is performed on an Objective-C pointer. This
/// is usually indicative of introspection within the Objective-C pointer.
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
SourceLocation OpLoc) {
if (!S.getLangOpts().ObjC1)
return;
const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
const Expr *LHS = L.get();
const Expr *RHS = R.get();
if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
ObjCPointerExpr = LHS;
OtherExpr = RHS;
}
else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
ObjCPointerExpr = RHS;
OtherExpr = LHS;
}
// This warning is deliberately made very specific to reduce false
// positives with logic that uses '&' for hashing. This logic mainly
// looks for code trying to introspect into tagged pointers, which
// code should generally never do.
if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
unsigned Diag = diag::warn_objc_pointer_masking;
// Determine if we are introspecting the result of performSelectorXXX.
const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
// Special case messages to -performSelector and friends, which
// can return non-pointer values boxed in a pointer value.
// Some clients may wish to silence warnings in this subcase.
if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
Selector S = ME->getSelector();
StringRef SelArg0 = S.getNameForSlot(0);
if (SelArg0.startswith("performSelector"))
Diag = diag::warn_objc_pointer_masking_performSelector;
}
S.Diag(OpLoc, Diag)
<< ObjCPointerExpr->getSourceRange();
}
}
static NamedDecl *getDeclFromExpr(Expr *E) {
if (!E)
return nullptr;
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
return DRE->getDecl();
if (auto *ME = dyn_cast<MemberExpr>(E))
return ME->getMemberDecl();
if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
return IRE->getDecl();
return nullptr;
}
/// CreateBuiltinBinOp - Creates a new built-in binary operation with
/// operator @p Opc at location @c TokLoc. This routine only supports
/// built-in operations; ActOnBinOp handles overloaded operators.
ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr) {
if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
// The syntax only allows initializer lists on the RHS of assignment,
// so we don't need to worry about accepting invalid code for
// non-assignment operators.
// C++11 5.17p9:
// The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
// of x = {} is x = T().
InitializationKind Kind =
InitializationKind::CreateDirectList(RHSExpr->getLocStart());
InitializedEntity Entity =
InitializedEntity::InitializeTemporary(LHSExpr->getType());
InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
if (Init.isInvalid())
return Init;
RHSExpr = Init.get();
}
ExprResult LHS = LHSExpr, RHS = RHSExpr;
QualType ResultTy; // Result type of the binary operator.
// The following two variables are used for compound assignment operators
QualType CompLHSTy; // Type of LHS after promotions for computation
QualType CompResultTy; // Type of computation result
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
if (!getLangOpts().CPlusPlus) {
// C cannot handle TypoExpr nodes on either side of a binop because it
// doesn't handle dependent types properly, so make sure any TypoExprs have
// been dealt with before checking the operands.
LHS = CorrectDelayedTyposInExpr(LHSExpr);
RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
if (Opc != BO_Assign)
return ExprResult(E);
// Avoid correcting the RHS to the same Expr as the LHS.
Decl *D = getDeclFromExpr(E);
return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
});
if (!LHS.isUsable() || !RHS.isUsable())
return ExprError();
}
if (getLangOpts().OpenCL) {
QualType LHSTy = LHSExpr->getType();
QualType RHSTy = RHSExpr->getType();
// OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
// the ATOMIC_VAR_INIT macro.
if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
if (BO_Assign == Opc)
Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
else
ResultTy = InvalidOperands(OpLoc, LHS, RHS);
return ExprError();
}
// OpenCL special types - image, sampler, pipe, and blocks are to be used
// only with a builtin functions and therefore should be disallowed here.
if (LHSTy->isImageType() || RHSTy->isImageType() ||
LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
LHSTy->isPipeType() || RHSTy->isPipeType() ||
LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
ResultTy = InvalidOperands(OpLoc, LHS, RHS);
return ExprError();
}
}
switch (Opc) {
case BO_Assign:
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
if (getLangOpts().CPlusPlus &&
LHS.get()->getObjectKind() != OK_ObjCProperty) {
VK = LHS.get()->getValueKind();
OK = LHS.get()->getObjectKind();
}
if (!ResultTy.isNull()) {
DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
}
RecordModifiableNonNullParam(*this, LHS.get());
break;
case BO_PtrMemD:
case BO_PtrMemI:
ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
Opc == BO_PtrMemI);
break;
case BO_Mul:
case BO_Div:
ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
Opc == BO_Div);
break;
case BO_Rem:
ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
break;
case BO_Add:
ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
break;
case BO_Sub:
ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
break;
case BO_Shl:
case BO_Shr:
ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
break;
case BO_LE:
case BO_LT:
case BO_GE:
case BO_GT:
ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
break;
case BO_EQ:
case BO_NE:
ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
break;
case BO_And:
checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
case BO_Xor:
case BO_Or:
ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
break;
case BO_LAnd:
case BO_LOr:
ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
break;
case BO_MulAssign:
case BO_DivAssign:
CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
Opc == BO_DivAssign);
CompLHSTy = CompResultTy;
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_RemAssign:
CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
CompLHSTy = CompResultTy;
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_AddAssign:
CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_SubAssign:
CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_ShlAssign:
case BO_ShrAssign:
CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
CompLHSTy = CompResultTy;
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_AndAssign:
case BO_OrAssign: // fallthrough
DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
case BO_XorAssign:
CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
CompLHSTy = CompResultTy;
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
break;
case BO_Comma:
ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
VK = RHS.get()->getValueKind();
OK = RHS.get()->getObjectKind();
}
break;
}
if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
return ExprError();
// Check for array bounds violations for both sides of the BinaryOperator
CheckArrayAccess(LHS.get());
CheckArrayAccess(RHS.get());
if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
&Context.Idents.get("object_setClass"),
SourceLocation(), LookupOrdinaryName);
if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
FixItHint::CreateInsertion(RHSLocEnd, ")");
}
else
Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
}
else if (const ObjCIvarRefExpr *OIRE =
dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
if (CompResultTy.isNull())
return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
OK, OpLoc, FPFeatures);
if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
OK_ObjCProperty) {
VK = VK_LValue;
OK = LHS.get()->getObjectKind();
}
return new (Context) CompoundAssignOperator(
LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
OpLoc, FPFeatures);
}
/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
/// operators are mixed in a way that suggests that the programmer forgot that
/// comparison operators have higher precedence. The most typical example of
/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
SourceLocation OpLoc, Expr *LHSExpr,
Expr *RHSExpr) {
BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
// Check that one of the sides is a comparison operator and the other isn't.
bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
bool isRightComp = RHSBO && RHSBO->isComparisonOp();
if (isLeftComp == isRightComp)
return;
// Bitwise operations are sometimes used as eager logical ops.
// Don't diagnose this.
bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
if (isLeftBitwise || isRightBitwise)
return;
SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
OpLoc)
: SourceRange(OpLoc, RHSExpr->getLocEnd());
StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
SourceRange ParensRange = isLeftComp ?
SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
: SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
<< DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
SuggestParentheses(Self, OpLoc,
Self.PDiag(diag::note_precedence_silence) << OpStr,
(isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
SuggestParentheses(Self, OpLoc,
Self.PDiag(diag::note_precedence_bitwise_first)
<< BinaryOperator::getOpcodeStr(Opc),
ParensRange);
}
/// \brief It accepts a '&&' expr that is inside a '||' one.
/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
/// in parentheses.
static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
BinaryOperator *Bop) {
assert(Bop->getOpcode() == BO_LAnd);
Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
<< Bop->getSourceRange() << OpLoc;
SuggestParentheses(Self, Bop->getOperatorLoc(),
Self.PDiag(diag::note_precedence_silence)
<< Bop->getOpcodeStr(),
Bop->getSourceRange());
}
/// \brief Returns true if the given expression can be evaluated as a constant
/// 'true'.
static bool EvaluatesAsTrue(Sema &S, Expr *E) {
bool Res;
return !E->isValueDependent() &&
E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
}
/// \brief Returns true if the given expression can be evaluated as a constant
/// 'false'.
static bool EvaluatesAsFalse(Sema &S, Expr *E) {
bool Res;
return !E->isValueDependent() &&
E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
}
/// \brief Look for '&&' in the left hand of a '||' expr.
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Expr *LHSExpr, Expr *RHSExpr) {
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
if (Bop->getOpcode() == BO_LAnd) {
// If it's "a && b || 0" don't warn since the precedence doesn't matter.
if (EvaluatesAsFalse(S, RHSExpr))
return;
// If it's "1 && a || b" don't warn since the precedence doesn't matter.
if (!EvaluatesAsTrue(S, Bop->getLHS()))
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
} else if (Bop->getOpcode() == BO_LOr) {
if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
// If it's "a || b && 1 || c" we didn't warn earlier for
// "a || b && 1", but warn now.
if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
}
}
}
}
/// \brief Look for '&&' in the right hand of a '||' expr.
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Expr *LHSExpr, Expr *RHSExpr) {
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
if (Bop->getOpcode() == BO_LAnd) {
// If it's "0 || a && b" don't warn since the precedence doesn't matter.
if (EvaluatesAsFalse(S, LHSExpr))
return;
// If it's "a || b && 1" don't warn since the precedence doesn't matter.
if (!EvaluatesAsTrue(S, Bop->getRHS()))
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
}
}
}
/// \brief Look for bitwise op in the left or right hand of a bitwise op with
/// lower precedence and emit a diagnostic together with a fixit hint that wraps
/// the '&' expression in parentheses.
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
SourceLocation OpLoc, Expr *SubExpr) {
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
<< Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
<< Bop->getSourceRange() << OpLoc;
SuggestParentheses(S, Bop->getOperatorLoc(),
S.PDiag(diag::note_precedence_silence)
<< Bop->getOpcodeStr(),
Bop->getSourceRange());
}
}
}
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
Expr *SubExpr, StringRef Shift) {
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
StringRef Op = Bop->getOpcodeStr();
S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
<< Bop->getSourceRange() << OpLoc << Shift << Op;
SuggestParentheses(S, Bop->getOperatorLoc(),
S.PDiag(diag::note_precedence_silence) << Op,
Bop->getSourceRange());
}
}
}
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
Expr *LHSExpr, Expr *RHSExpr) {
CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
if (!OCE)
return;
FunctionDecl *FD = OCE->getDirectCallee();
if (!FD || !FD->isOverloadedOperator())
return;
OverloadedOperatorKind Kind = FD->getOverloadedOperator();
if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
return;
S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
<< (Kind == OO_LessLess);
SuggestParentheses(S, OCE->getOperatorLoc(),
S.PDiag(diag::note_precedence_silence)
<< (Kind == OO_LessLess ? "<<" : ">>"),
OCE->getSourceRange());
SuggestParentheses(S, OpLoc,
S.PDiag(diag::note_evaluate_comparison_first),
SourceRange(OCE->getArg(1)->getLocStart(),
RHSExpr->getLocEnd()));
}
/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
/// precedence.
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
SourceLocation OpLoc, Expr *LHSExpr,
Expr *RHSExpr){
// Diagnose "arg1 'bitwise' arg2 'eq' arg3".
if (BinaryOperator::isBitwiseOp(Opc))
DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
// Diagnose "arg1 & arg2 | arg3"
if ((Opc == BO_Or || Opc == BO_Xor) &&
!OpLoc.isMacroID()/* Don't warn in macros. */) {
DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
}
// Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
// We don't warn for 'assert(a || b && "bad")' since this is safe.
if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
}
if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
|| Opc == BO_Shr) {
StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
}
// Warn on overloaded shift operators and comparisons, such as:
// cout << 5 == 4;
if (BinaryOperator::isComparisonOp(Opc))
DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
}
// Binary Operators. 'Tok' is the token for the operator.
ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind,
Expr *LHSExpr, Expr *RHSExpr) {
BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
assert(LHSExpr && "ActOnBinOp(): missing left expression");
assert(RHSExpr && "ActOnBinOp(): missing right expression");
// Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
}
/// Build an overloaded binary operator expression in the given scope.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
BinaryOperatorKind Opc,
Expr *LHS, Expr *RHS) {
// Find all of the overloaded operators visible from this
// point. We perform both an operator-name lookup from the local
// scope and an argument-dependent lookup based on the types of
// the arguments.
UnresolvedSet<16> Functions;
OverloadedOperatorKind OverOp
= BinaryOperator::getOverloadedOperator(Opc);
if (Sc && OverOp != OO_None && OverOp != OO_Equal)
S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
RHS->getType(), Functions);
// Build the (potentially-overloaded, potentially-dependent)
// binary operation.
return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
}
ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr) {
// We want to end up calling one of checkPseudoObjectAssignment
// (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
// both expressions are overloadable or either is type-dependent),
// or CreateBuiltinBinOp (in any other case). We also want to get
// any placeholder types out of the way.
// Handle pseudo-objects in the LHS.
if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
// Assignments with a pseudo-object l-value need special analysis.
if (pty->getKind() == BuiltinType::PseudoObject &&
BinaryOperator::isAssignmentOp(Opc))
return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
// Don't resolve overloads if the other type is overloadable.
if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
// We can't actually test that if we still have a placeholder,
// though. Fortunately, none of the exceptions we see in that
// code below are valid when the LHS is an overload set. Note
// that an overload set can be dependently-typed, but it never
// instantiates to having an overloadable type.
ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
if (resolvedRHS.isInvalid()) return ExprError();
RHSExpr = resolvedRHS.get();
if (RHSExpr->isTypeDependent() ||
RHSExpr->getType()->isOverloadableType())
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
}
ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
if (LHS.isInvalid()) return ExprError();
LHSExpr = LHS.get();
}
// Handle pseudo-objects in the RHS.
if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
// An overload in the RHS can potentially be resolved by the type
// being assigned to.
if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
if (getLangOpts().CPlusPlus &&
(LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
LHSExpr->getType()->isOverloadableType()))
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
}
// Don't resolve overloads if the other type is overloadable.
if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
LHSExpr->getType()->isOverloadableType())
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
if (!resolvedRHS.isUsable()) return ExprError();
RHSExpr = resolvedRHS.get();
}
if (getLangOpts().CPlusPlus) {
// If either expression is type-dependent, always build an
// overloaded op.
if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
// Otherwise, build an overloaded op if either expression has an
// overloadable type.
if (LHSExpr->getType()->isOverloadableType() ||
RHSExpr->getType()->isOverloadableType())
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
}
// Build a built-in binary operation.
return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
}
ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
Expr *InputExpr) {
ExprResult Input = InputExpr;
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
QualType resultType;
if (getLangOpts().OpenCL) {
QualType Ty = InputExpr->getType();
// The only legal unary operation for atomics is '&'.
if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
// OpenCL special types - image, sampler, pipe, and blocks are to be used
// only with a builtin functions and therefore should be disallowed here.
(Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
|| Ty->isBlockPointerType())) {
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< InputExpr->getType()
<< Input.get()->getSourceRange());
}
}
switch (Opc) {
case UO_PreInc:
case UO_PreDec:
case UO_PostInc:
case UO_PostDec:
resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
OpLoc,
Opc == UO_PreInc ||
Opc == UO_PostInc,
Opc == UO_PreInc ||
Opc == UO_PreDec);
break;
case UO_AddrOf:
resultType = CheckAddressOfOperand(Input, OpLoc);
RecordModifiableNonNullParam(*this, InputExpr);
break;
case UO_Deref: {
Input = DefaultFunctionArrayLvalueConversion(Input.get());
if (Input.isInvalid()) return ExprError();
resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
break;
}
case UO_Plus:
case UO_Minus:
Input = UsualUnaryConversions(Input.get());
if (Input.isInvalid()) return ExprError();
resultType = Input.get()->getType();
if (resultType->isDependentType())
break;
if (resultType->isArithmeticType()) // C99 6.5.3.3p1
break;
else if (resultType->isVectorType() &&
// The z vector extensions don't allow + or - with bool vectors.
(!Context.getLangOpts().ZVector ||
resultType->getAs<VectorType>()->getVectorKind() !=
VectorType::AltiVecBool))
break;
else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
Opc == UO_Plus &&
resultType->isPointerType())
break;
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
case UO_Not: // bitwise complement
Input = UsualUnaryConversions(Input.get());
if (Input.isInvalid())
return ExprError();
resultType = Input.get()->getType();
if (resultType->isDependentType())
break;
// C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
if (resultType->isComplexType() || resultType->isComplexIntegerType())
// C99 does not support '~' for complex conjugation.
Diag(OpLoc, diag::ext_integer_complement_complex)
<< resultType << Input.get()->getSourceRange();
else if (resultType->hasIntegerRepresentation())
break;
else if (resultType->isExtVectorType()) {
if (Context.getLangOpts().OpenCL) {
// OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
// on vector float types.
QualType T = resultType->getAs<ExtVectorType>()->getElementType();
if (!T->isIntegerType())
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
}
break;
} else {
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
}
break;
case UO_LNot: // logical negation
// Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Input = DefaultFunctionArrayLvalueConversion(Input.get());
if (Input.isInvalid()) return ExprError();
resultType = Input.get()->getType();
// Though we still have to promote half FP to float...
if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
resultType = Context.FloatTy;
}
if (resultType->isDependentType())
break;
if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
// C99 6.5.3.3p1: ok, fallthrough;
if (Context.getLangOpts().CPlusPlus) {
// C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
// operand contextually converted to bool.
Input = ImpCastExprToType(Input.get(), Context.BoolTy,
ScalarTypeToBooleanCastKind(resultType));
} else if (Context.getLangOpts().OpenCL &&
Context.getLangOpts().OpenCLVersion < 120) {
// OpenCL v1.1 6.3.h: The logical operator not (!) does not
// operate on scalar float types.
if (!resultType->isIntegerType() && !resultType->isPointerType())
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
}
} else if (resultType->isExtVectorType()) {
if (Context.getLangOpts().OpenCL &&
Context.getLangOpts().OpenCLVersion < 120) {
// OpenCL v1.1 6.3.h: The logical operator not (!) does not
// operate on vector float types.
QualType T = resultType->getAs<ExtVectorType>()->getElementType();
if (!T->isIntegerType())
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
}
// Vector logical not returns the signed variant of the operand type.
resultType = GetSignedVectorType(resultType);
break;
} else {
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
<< resultType << Input.get()->getSourceRange());
}
// LNot always has type int. C99 6.5.3.3p5.
// In C++, it's bool. C++ 5.3.1p8
resultType = Context.getLogicalOperationType();
break;
case UO_Real:
case UO_Imag:
resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
// _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
// complex l-values to ordinary l-values and all other values to r-values.
if (Input.isInvalid()) return ExprError();
if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
if (Input.get()->getValueKind() != VK_RValue &&
Input.get()->getObjectKind() == OK_Ordinary)
VK = Input.get()->getValueKind();
} else if (!getLangOpts().CPlusPlus) {
// In C, a volatile scalar is read by __imag. In C++, it is not.
Input = DefaultLvalueConversion(Input.get());
}
break;
case UO_Extension:
case UO_Coawait:
resultType = Input.get()->getType();
VK = Input.get()->getValueKind();
OK = Input.get()->getObjectKind();
break;
}
if (resultType.isNull() || Input.isInvalid())
return ExprError();
// Check for array bounds violations in the operand of the UnaryOperator,
// except for the '*' and '&' operators that have to be handled specially
// by CheckArrayAccess (as there are special cases like &array[arraysize]
// that are explicitly defined as valid by the standard).
if (Opc != UO_AddrOf && Opc != UO_Deref)
CheckArrayAccess(Input.get());
return new (Context)
UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
}
/// \brief Determine whether the given expression is a qualified member
/// access expression, of a form that could be turned into a pointer to member
/// with the address-of operator.
static bool isQualifiedMemberAccess(Expr *E) {
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (!DRE->getQualifier())
return false;
ValueDecl *VD = DRE->getDecl();
if (!VD->isCXXClassMember())
return false;
if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
return true;
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
return Method->isInstance();
return false;
}
if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
if (!ULE->getQualifier())
return false;
for (NamedDecl *D : ULE->decls()) {
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
if (Method->isInstance())
return true;
} else {
// Overload set does not contain methods.
break;
}
}
return false;
}
return false;
}
ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input) {
// First things first: handle placeholders so that the
// overloaded-operator check considers the right type.
if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
// Increment and decrement of pseudo-object references.
if (pty->getKind() == BuiltinType::PseudoObject &&
UnaryOperator::isIncrementDecrementOp(Opc))
return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
// extension is always a builtin operator.
if (Opc == UO_Extension)
return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
// & gets special logic for several kinds of placeholder.
// The builtin code knows what to do.
if (Opc == UO_AddrOf &&
(pty->getKind() == BuiltinType::Overload ||
pty->getKind() == BuiltinType::UnknownAny ||
pty->getKind() == BuiltinType::BoundMember))
return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
// Anything else needs to be handled now.
ExprResult Result = CheckPlaceholderExpr(Input);
if (Result.isInvalid()) return ExprError();
Input = Result.get();
}
if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
!(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
// Find all of the overloaded operators visible from this
// point. We perform both an operator-name lookup from the local
// scope and an argument-dependent lookup based on the types of
// the arguments.
UnresolvedSet<16> Functions;
OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
if (S && OverOp != OO_None)
LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
Functions);
return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
}
return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
}
// Unary Operators. 'Tok' is the token for the operator.
ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input) {
return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
}
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl) {
TheDecl->markUsed(Context);
// Create the AST node. The address of a label always has type 'void*'.
return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Context.getPointerType(Context.VoidTy));
}
/// Given the last statement in a statement-expression, check whether
/// the result is a producing expression (like a call to an
/// ns_returns_retained function) and, if so, rebuild it to hoist the
/// release out of the full-expression. Otherwise, return null.
/// Cannot fail.
static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
// Should always be wrapped with one of these.
ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
if (!cleanups) return nullptr;
ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
return nullptr;
// Splice out the cast. This shouldn't modify any interesting
// features of the statement.
Expr *producer = cast->getSubExpr();
assert(producer->getType() == cast->getType());
assert(producer->getValueKind() == cast->getValueKind());
cleanups->setSubExpr(producer);
return cleanups;
}
void Sema::ActOnStartStmtExpr() {
PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
}
void Sema::ActOnStmtExprError() {
// Note that function is also called by TreeTransform when leaving a
// StmtExpr scope without rebuilding anything.
DiscardCleanupsInEvaluationContext();
PopExpressionEvaluationContext();
}
ExprResult
Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc) { // "({..})"
assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
if (hasAnyUnrecoverableErrorsInThisFunction())
DiscardCleanupsInEvaluationContext();
assert(!Cleanup.exprNeedsCleanups() &&
"cleanups within StmtExpr not correctly bound!");
PopExpressionEvaluationContext();
// FIXME: there are a variety of strange constraints to enforce here, for
// example, it is not possible to goto into a stmt expression apparently.
// More semantic analysis is needed.
// If there are sub-stmts in the compound stmt, take the type of the last one
// as the type of the stmtexpr.
QualType Ty = Context.VoidTy;
bool StmtExprMayBindToTemp = false;
if (!Compound->body_empty()) {
Stmt *LastStmt = Compound->body_back();
LabelStmt *LastLabelStmt = nullptr;
// If LastStmt is a label, skip down through into the body.
while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
LastLabelStmt = Label;
LastStmt = Label->getSubStmt();
}
if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
// Do function/array conversion on the last expression, but not
// lvalue-to-rvalue. However, initialize an unqualified type.
ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
if (LastExpr.isInvalid())
return ExprError();
Ty = LastExpr.get()->getType().getUnqualifiedType();
if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
// In ARC, if the final expression ends in a consume, splice
// the consume out and bind it later. In the alternate case
// (when dealing with a retainable type), the result
// initialization will create a produce. In both cases the
// result will be +1, and we'll need to balance that out with
// a bind.
if (Expr *rebuiltLastStmt
= maybeRebuildARCConsumingStmt(LastExpr.get())) {
LastExpr = rebuiltLastStmt;
} else {
LastExpr = PerformCopyInitialization(
InitializedEntity::InitializeResult(LPLoc,
Ty,
false),
SourceLocation(),
LastExpr);
}
if (LastExpr.isInvalid())
return ExprError();
if (LastExpr.get() != nullptr) {
if (!LastLabelStmt)
Compound->setLastStmt(LastExpr.get());
else
LastLabelStmt->setSubStmt(LastExpr.get());
StmtExprMayBindToTemp = true;
}
}
}
}
// FIXME: Check that expression type is complete/non-abstract; statement
// expressions are not lvalues.
Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
if (StmtExprMayBindToTemp)
return MaybeBindToTemporary(ResStmtExpr);
return ResStmtExpr;
}
ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc) {
QualType ArgTy = TInfo->getType();
bool Dependent = ArgTy->isDependentType();
SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
// We must have at least one component that refers to the type, and the first
// one is known to be a field designator. Verify that the ArgTy represents
// a struct/union/class.
if (!Dependent && !ArgTy->isRecordType())
return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
<< ArgTy << TypeRange);
// Type must be complete per C99 7.17p3 because a declaring a variable
// with an incomplete type would be ill-formed.
if (!Dependent
&& RequireCompleteType(BuiltinLoc, ArgTy,
diag::err_offsetof_incomplete_type, TypeRange))
return ExprError();
// offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
// GCC extension, diagnose them.
// FIXME: This diagnostic isn't actually visible because the location is in
// a system header!
if (Components.size() != 1)
Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
<< SourceRange(Components[1].LocStart, Components.back().LocEnd);
bool DidWarnAboutNonPOD = false;
QualType CurrentType = ArgTy;
SmallVector<OffsetOfNode, 4> Comps;
SmallVector<Expr*, 4> Exprs;
for (const OffsetOfComponent &OC : Components) {
if (OC.isBrackets) {
// Offset of an array sub-field. TODO: Should we allow vector elements?
if (!CurrentType->isDependentType()) {
const ArrayType *AT = Context.getAsArrayType(CurrentType);
if(!AT)
return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
<< CurrentType);
CurrentType = AT->getElementType();
} else
CurrentType = Context.DependentTy;
ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
if (IdxRval.isInvalid())
return ExprError();
Expr *Idx = IdxRval.get();
// The expression must be an integral expression.
// FIXME: An integral constant expression?
if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
!Idx->getType()->isIntegerType())
return ExprError(Diag(Idx->getLocStart(),
diag::err_typecheck_subscript_not_integer)
<< Idx->getSourceRange());
// Record this array index.
Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Exprs.push_back(Idx);
continue;
}
// Offset of a field.
if (CurrentType->isDependentType()) {
// We have the offset of a field, but we can't look into the dependent
// type. Just record the identifier of the field.
Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
CurrentType = Context.DependentTy;
continue;
}
// We need to have a complete type to look into.
if (RequireCompleteType(OC.LocStart, CurrentType,
diag::err_offsetof_incomplete_type))
return ExprError();
// Look for the designated field.
const RecordType *RC = CurrentType->getAs<RecordType>();
if (!RC)
return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
<< CurrentType);
RecordDecl *RD = RC->getDecl();
// C++ [lib.support.types]p5:
// The macro offsetof accepts a restricted set of type arguments in this
// International Standard. type shall be a POD structure or a POD union
// (clause 9).
// C++11 [support.types]p4:
// If type is not a standard-layout class (Clause 9), the results are
// undefined.
if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
unsigned DiagID =
LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
: diag::ext_offsetof_non_pod_type;
if (!IsSafe && !DidWarnAboutNonPOD &&
DiagRuntimeBehavior(BuiltinLoc, nullptr,
PDiag(DiagID)
<< SourceRange(Components[0].LocStart, OC.LocEnd)
<< CurrentType))
DidWarnAboutNonPOD = true;
}
// Look for the field.
LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
LookupQualifiedName(R, RD);
FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
IndirectFieldDecl *IndirectMemberDecl = nullptr;
if (!MemberDecl) {
if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
MemberDecl = IndirectMemberDecl->getAnonField();
}
if (!MemberDecl)
return ExprError(Diag(BuiltinLoc, diag::err_no_member)
<< OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
OC.LocEnd));
// C99 7.17p3:
// (If the specified member is a bit-field, the behavior is undefined.)
//
// We diagnose this as an error.
if (MemberDecl->isBitField()) {
Diag(OC.LocEnd, diag::err_offsetof_bitfield)
<< MemberDecl->getDeclName()
<< SourceRange(BuiltinLoc, RParenLoc);
Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
return ExprError();
}
RecordDecl *Parent = MemberDecl->getParent();
if (IndirectMemberDecl)
Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
// If the member was found in a base class, introduce OffsetOfNodes for
// the base class indirections.
CXXBasePaths Paths;
if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
Paths)) {
if (Paths.getDetectedVirtual()) {
Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
<< MemberDecl->getDeclName()
<< SourceRange(BuiltinLoc, RParenLoc);
return ExprError();
}
CXXBasePath &Path = Paths.front();
for (const CXXBasePathElement &B : Path)
Comps.push_back(OffsetOfNode(B.Base));
}
if (IndirectMemberDecl) {
for (auto *FI : IndirectMemberDecl->chain()) {
assert(isa<FieldDecl>(FI));
Comps.push_back(OffsetOfNode(OC.LocStart,
cast<FieldDecl>(FI), OC.LocEnd));
}
} else
Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
CurrentType = MemberDecl->getType().getNonReferenceType();
}
return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
Comps, Exprs, RParenLoc);
}
ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc) {
TypeSourceInfo *ArgTInfo;
QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
if (ArgTy.isNull())
return ExprError();
if (!ArgTInfo)
ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
}
ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr,
Expr *LHSExpr, Expr *RHSExpr,
SourceLocation RPLoc) {
assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
ExprValueKind VK = VK_RValue;
ExprObjectKind OK = OK_Ordinary;
QualType resType;
bool ValueDependent = false;
bool CondIsTrue = false;
if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
resType = Context.DependentTy;
ValueDependent = true;
} else {
// The conditional expression is required to be a constant expression.
llvm::APSInt condEval(32);
ExprResult CondICE
= VerifyIntegerConstantExpression(CondExpr, &condEval,
diag::err_typecheck_choose_expr_requires_constant, false);
if (CondICE.isInvalid())
return ExprError();
CondExpr = CondICE.get();
CondIsTrue = condEval.getZExtValue();
// If the condition is > zero, then the AST type is the same as the LSHExpr.
Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
resType = ActiveExpr->getType();
ValueDependent = ActiveExpr->isValueDependent();
VK = ActiveExpr->getValueKind();
OK = ActiveExpr->getObjectKind();
}
return new (Context)
ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
CondIsTrue, resType->isDependentType(), ValueDependent);
}
//===----------------------------------------------------------------------===//
// Clang Extensions.
//===----------------------------------------------------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is started.
void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
if (LangOpts.CPlusPlus) {
Decl *ManglingContextDecl;
if (MangleNumberingContext *MCtx =
getCurrentMangleNumberContext(Block->getDeclContext(),
ManglingContextDecl)) {
unsigned ManglingNumber = MCtx->getManglingNumber(Block);
Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
}
}
PushBlockScope(CurScope, Block);
CurContext->addDecl(Block);
if (CurScope)
PushDeclContext(CurScope, Block);
else
CurContext = Block;
getCurBlock()->HasImplicitReturnType = true;
// Enter a new evaluation context to insulate the block from any
// cleanups from the enclosing full-expression.
PushExpressionEvaluationContext(
ExpressionEvaluationContext::PotentiallyEvaluated);
}
void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope) {
assert(ParamInfo.getIdentifier() == nullptr &&
"block-id should have no identifier!");
assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
BlockScopeInfo *CurBlock = getCurBlock();
TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
QualType T = Sig->getType();
// FIXME: We should allow unexpanded parameter packs here, but that would,
// in turn, make the block expression contain unexpanded parameter packs.
if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
// Drop the parameters.
FunctionProtoType::ExtProtoInfo EPI;
EPI.HasTrailingReturn = false;
EPI.TypeQuals |= DeclSpec::TQ_const;
T = Context.getFunctionType(Context.DependentTy, None, EPI);
Sig = Context.getTrivialTypeSourceInfo(T);
}
// GetTypeForDeclarator always produces a function type for a block
// literal signature. Furthermore, it is always a FunctionProtoType
// unless the function was written with a typedef.
assert(T->isFunctionType() &&
"GetTypeForDeclarator made a non-function block signature");
// Look for an explicit signature in that function type.
FunctionProtoTypeLoc ExplicitSignature;
TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
// Check whether that explicit signature was synthesized by
// GetTypeForDeclarator. If so, don't save that as part of the
// written signature.
if (ExplicitSignature.getLocalRangeBegin() ==
ExplicitSignature.getLocalRangeEnd()) {
// This would be much cheaper if we stored TypeLocs instead of
// TypeSourceInfos.
TypeLoc Result = ExplicitSignature.getReturnLoc();
unsigned Size = Result.getFullDataSize();
Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
Sig->getTypeLoc().initializeFullCopy(Result, Size);
ExplicitSignature = FunctionProtoTypeLoc();
}
}
CurBlock->TheDecl->setSignatureAsWritten(Sig);
CurBlock->FunctionType = T;
const FunctionType *Fn = T->getAs<FunctionType>();
QualType RetTy = Fn->getReturnType();
bool isVariadic =
(isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
CurBlock->TheDecl->setIsVariadic(isVariadic);
// Context.DependentTy is used as a placeholder for a missing block
// return type. TODO: what should we do with declarators like:
// ^ * { ... }
// If the answer is "apply template argument deduction"....
if (RetTy != Context.DependentTy) {
CurBlock->ReturnType = RetTy;
CurBlock->TheDecl->setBlockMissingReturnType(false);
CurBlock->HasImplicitReturnType = false;
}
// Push block parameters from the declarator if we had them.
SmallVector<ParmVarDecl*, 8> Params;
if (ExplicitSignature) {
for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
ParmVarDecl *Param = ExplicitSignature.getParam(I);
if (Param->getIdentifier() == nullptr &&
!Param->isImplicit() &&
!Param->isInvalidDecl() &&
!getLangOpts().CPlusPlus)
Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Params.push_back(Param);
}
// Fake up parameter variables if we have a typedef, like
// ^ fntype { ... }
} else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
for (const auto &I : Fn->param_types()) {
ParmVarDecl *Param = BuildParmVarDeclForTypedef(
CurBlock->TheDecl, ParamInfo.getLocStart(), I);
Params.push_back(Param);
}
}
// Set the parameters on the block decl.
if (!Params.empty()) {
CurBlock->TheDecl->setParams(Params);
CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
/*CheckParameterNames=*/false);
}
// Finally we can process decl attributes.
ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
// Put the parameter variables in scope.
for (auto AI : CurBlock->TheDecl->parameters()) {
AI->setOwningFunction(CurBlock->TheDecl);
// If this has an identifier, add it to the scope stack.
if (AI->getIdentifier()) {
CheckShadow(CurBlock->TheScope, AI);
PushOnScopeChains(AI, CurBlock->TheScope);
}
}
}
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
// Leave the expression-evaluation context.
DiscardCleanupsInEvaluationContext();
PopExpressionEvaluationContext();
// Pop off CurBlock, handle nested blocks.
PopDeclContext();
PopFunctionScopeInfo();
}
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Stmt *Body, Scope *CurScope) {
// If blocks are disabled, emit an error.
if (!LangOpts.Blocks)
Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
// Leave the expression-evaluation context.
if (hasAnyUnrecoverableErrorsInThisFunction())
DiscardCleanupsInEvaluationContext();
assert(!Cleanup.exprNeedsCleanups() &&
"cleanups within block not correctly bound!");
PopExpressionEvaluationContext();
BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
if (BSI->HasImplicitReturnType)
deduceClosureReturnType(*BSI);
PopDeclContext();
QualType RetTy = Context.VoidTy;
if (!BSI->ReturnType.isNull())
RetTy = BSI->ReturnType;
bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
QualType BlockTy;
// Set the captured variables on the block.
// FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
SmallVector<BlockDecl::Capture, 4> Captures;
for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
if (Cap.isThisCapture())
continue;
BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Cap.isNested(), Cap.getInitExpr());
Captures.push_back(NewCap);
}
BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
// If the user wrote a function type in some form, try to use that.
if (!BSI->FunctionType.isNull()) {
const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
FunctionType::ExtInfo Ext = FTy->getExtInfo();
if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
// Turn protoless block types into nullary block types.
if (isa<FunctionNoProtoType>(FTy)) {
FunctionProtoType::ExtProtoInfo EPI;
EPI.ExtInfo = Ext;
BlockTy = Context.getFunctionType(RetTy, None, EPI);
// Otherwise, if we don't need to change anything about the function type,
// preserve its sugar structure.
} else if (FTy->getReturnType() == RetTy &&
(!NoReturn || FTy->getNoReturnAttr())) {
BlockTy = BSI->FunctionType;
// Otherwise, make the minimal modifications to the function type.
} else {
const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
EPI.TypeQuals = 0; // FIXME: silently?
EPI.ExtInfo = Ext;
BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
}
// If we don't have a function type, just build one from nothing.
} else {
FunctionProtoType::ExtProtoInfo EPI;
EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
BlockTy = Context.getFunctionType(RetTy, None, EPI);
}
DiagnoseUnusedParameters(BSI->TheDecl->parameters());
BlockTy = Context.getBlockPointerType(BlockTy);
// If needed, diagnose invalid gotos and switches in the block.
if (getCurFunction()->NeedsScopeChecking() &&
!PP.isCodeCompletionEnabled())
DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
// Try to apply the named return value optimization. We have to check again
// if we can do this, though, because blocks keep return statements around
// to deduce an implicit return type.
if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
!BSI->TheDecl->isDependentContext())
computeNRVO(Body, BSI);
BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
// If the block isn't obviously global, i.e. it captures anything at
// all, then we need to do a few things in the surrounding context:
if (Result->getBlockDecl()->hasCaptures()) {
// First, this expression has a new cleanup object.
ExprCleanupObjects.push_back(Result->getBlockDecl());
Cleanup.setExprNeedsCleanups(true);
// It also gets a branch-protected scope if any of the captured
// variables needs destruction.
for (const auto &CI : Result->getBlockDecl()->captures()) {
const VarDecl *var = CI.getVariable();
if (var->getType().isDestructedType() != QualType::DK_none) {
getCurFunction()->setHasBranchProtectedScope();
break;
}
}
}
return Result;
}
ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc) {
TypeSourceInfo *TInfo;
GetTypeFromParser(Ty, &TInfo);
return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
}
ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
Expr *E, TypeSourceInfo *TInfo,
SourceLocation RPLoc) {
Expr *OrigExpr = E;
bool IsMS = false;
// CUDA device code does not support varargs.
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
CUDAFunctionTarget T = IdentifyCUDATarget(F);
if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
}
}
// It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
// as Microsoft ABI on an actual Microsoft platform, where
// __builtin_ms_va_list and __builtin_va_list are the same.)
if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
QualType MSVaListType = Context.getBuiltinMSVaListType();
if (Context.hasSameType(MSVaListType, E->getType())) {
if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
return ExprError();
IsMS = true;
}
}
// Get the va_list type
QualType VaListType = Context.getBuiltinVaListType();
if (!IsMS) {
if (VaListType->isArrayType()) {
// Deal with implicit array decay; for example, on x86-64,
// va_list is an array, but it's supposed to decay to
// a pointer for va_arg.
VaListType = Context.getArrayDecayedType(VaListType);
// Make sure the input expression also decays appropriately.
ExprResult Result = UsualUnaryConversions(E);
if (Result.isInvalid())
return ExprError();
E = Result.get();
} else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
// If va_list is a record type and we are compiling in C++ mode,
// check the argument using reference binding.
InitializedEntity Entity = InitializedEntity::InitializeParameter(
Context, Context.getLValueReferenceType(VaListType), false);
ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
if (Init.isInvalid())
return ExprError();
E = Init.getAs<Expr>();
} else {
// Otherwise, the va_list argument must be an l-value because
// it is modified by va_arg.
if (!E->isTypeDependent() &&
CheckForModifiableLvalue(E, BuiltinLoc, *this))
return ExprError();
}
}
if (!IsMS && !E->isTypeDependent() &&
!Context.hasSameType(VaListType, E->getType()))
return ExprError(Diag(E->getLocStart(),
diag::err_first_argument_to_va_arg_not_of_type_va_list)
<< OrigExpr->getType() << E->getSourceRange());
if (!TInfo->getType()->isDependentType()) {
if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
diag::err_second_parameter_to_va_arg_incomplete,
TInfo->getTypeLoc()))
return ExprError();
if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
TInfo->getType(),
diag::err_second_parameter_to_va_arg_abstract,
TInfo->getTypeLoc()))
return ExprError();
if (!TInfo->getType().isPODType(Context)) {
Diag(TInfo->getTypeLoc().getBeginLoc(),
TInfo->getType()->isObjCLifetimeType()
? diag::warn_second_parameter_to_va_arg_ownership_qualified
: diag::warn_second_parameter_to_va_arg_not_pod)
<< TInfo->getType()
<< TInfo->getTypeLoc().getSourceRange();
}
// Check for va_arg where arguments of the given type will be promoted
// (i.e. this va_arg is guaranteed to have undefined behavior).
QualType PromoteType;
if (TInfo->getType()->isPromotableIntegerType()) {
PromoteType = Context.getPromotedIntegerType(TInfo->getType());
if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
PromoteType = QualType();
}
if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
PromoteType = Context.DoubleTy;
if (!PromoteType.isNull())
DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
<< TInfo->getType()
<< PromoteType
<< TInfo->getTypeLoc().getSourceRange());
}
QualType T = TInfo->getType().getNonLValueExprType(Context);
return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
}
ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
// The type of __null will be int or long, depending on the size of
// pointers on the target.
QualType Ty;
unsigned pw = Context.getTargetInfo().getPointerWidth(0);
if (pw == Context.getTargetInfo().getIntWidth())
Ty = Context.IntTy;
else if (pw == Context.getTargetInfo().getLongWidth())
Ty = Context.LongTy;
else if (pw == Context.getTargetInfo().getLongLongWidth())
Ty = Context.LongLongTy;
else {
llvm_unreachable("I don't know size of pointer!");
}
return new (Context) GNUNullExpr(Ty, TokenLoc);
}
bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
bool Diagnose) {
if (!getLangOpts().ObjC1)
return false;
const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
if (!PT)
return false;
if (!PT->isObjCIdType()) {
// Check if the destination is the 'NSString' interface.
const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
if (!ID || !ID->getIdentifier()->isStr("NSString"))
return false;
}
// Ignore any parens, implicit casts (should only be
// array-to-pointer decays), and not-so-opaque values. The last is
// important for making this trigger for property assignments.
Expr *SrcExpr = Exp->IgnoreParenImpCasts();
if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
if (OV->getSourceExpr())
SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
if (!SL || !SL->isAscii())
return false;
if (Diagnose) {
Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
<< FixItHint::CreateInsertion(SL->getLocStart(), "@");
Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
}
return true;
}
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
const Expr *SrcExpr) {
if (!DstType->isFunctionPointerType() ||
!SrcExpr->getType()->isFunctionType())
return false;
auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
if (!DRE)
return false;
auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
if (!FD)
return false;
return !S.checkAddressOfFunctionIsAvailable(FD,
/*Complain=*/true,
SrcExpr->getLocStart());
}
bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained) {
if (Complained)
*Complained = false;
// Decode the result (notice that AST's are still created for extensions).
bool CheckInferredResultType = false;
bool isInvalid = false;
unsigned DiagKind = 0;
FixItHint Hint;
ConversionFixItGenerator ConvHints;
bool MayHaveConvFixit = false;
bool MayHaveFunctionDiff = false;
const ObjCInterfaceDecl *IFace = nullptr;
const ObjCProtocolDecl *PDecl = nullptr;
switch (ConvTy) {
case Compatible:
DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
return false;
case PointerToInt:
DiagKind = diag::ext_typecheck_convert_pointer_int;
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
MayHaveConvFixit = true;
break;
case IntToPointer:
DiagKind = diag::ext_typecheck_convert_int_pointer;
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
MayHaveConvFixit = true;
break;
case IncompatiblePointer:
if (Action == AA_Passing_CFAudited)
DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
else if (SrcType->isFunctionPointerType() &&
DstType->isFunctionPointerType())
DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
else
DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
CheckInferredResultType = DstType->isObjCObjectPointerType() &&
SrcType->isObjCObjectPointerType();
if (Hint.isNull() && !CheckInferredResultType) {
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
}
else if (CheckInferredResultType) {
SrcType = SrcType.getUnqualifiedType();
DstType = DstType.getUnqualifiedType();
}
MayHaveConvFixit = true;
break;
case IncompatiblePointerSign:
DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
break;
case FunctionVoidPointer:
DiagKind = diag::ext_typecheck_convert_pointer_void_func;
break;
case IncompatiblePointerDiscardsQualifiers: {
// Perform array-to-pointer decay if necessary.
if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
Qualifiers rhq = DstType->getPointeeType().getQualifiers();
if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
DiagKind = diag::err_typecheck_incompatible_address_space;
break;
} else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
DiagKind = diag::err_typecheck_incompatible_ownership;
break;
}
llvm_unreachable("unknown error case for discarding qualifiers!");
// fallthrough
}
case CompatiblePointerDiscardsQualifiers:
// If the qualifiers lost were because we were applying the
// (deprecated) C++ conversion from a string literal to a char*
// (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
// Ideally, this check would be performed in
// checkPointerTypesForAssignment. However, that would require a
// bit of refactoring (so that the second argument is an
// expression, rather than a type), which should be done as part
// of a larger effort to fix checkPointerTypesForAssignment for
// C++ semantics.
if (getLangOpts().CPlusPlus &&
IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
return false;
DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
break;
case IncompatibleNestedPointerQualifiers:
DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
break;
case IntToBlockPointer:
DiagKind = diag::err_int_to_block_pointer;
break;
case IncompatibleBlockPointer:
DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
break;
case IncompatibleObjCQualifiedId: {
if (SrcType->isObjCQualifiedIdType()) {
const ObjCObjectPointerType *srcOPT =
SrcType->getAs<ObjCObjectPointerType>();
for (auto *srcProto : srcOPT->quals()) {
PDecl = srcProto;
break;
}
if (const ObjCInterfaceType *IFaceT =
DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
IFace = IFaceT->getDecl();
}
else if (DstType->isObjCQualifiedIdType()) {
const ObjCObjectPointerType *dstOPT =
DstType->getAs<ObjCObjectPointerType>();
for (auto *dstProto : dstOPT->quals()) {
PDecl = dstProto;
break;
}
if (const ObjCInterfaceType *IFaceT =
SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
IFace = IFaceT->getDecl();
}
DiagKind = diag::warn_incompatible_qualified_id;
break;
}
case IncompatibleVectors:
DiagKind = diag::warn_incompatible_vectors;
break;
case IncompatibleObjCWeakRef:
DiagKind = diag::err_arc_weak_unavailable_assign;
break;
case Incompatible:
if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
if (Complained)
*Complained = true;
return true;
}
DiagKind = diag::err_typecheck_convert_incompatible;
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
MayHaveConvFixit = true;
isInvalid = true;
MayHaveFunctionDiff = true;
break;
}
QualType FirstType, SecondType;
switch (Action) {
case AA_Assigning:
case AA_Initializing:
// The destination type comes first.
FirstType = DstType;
SecondType = SrcType;
break;
case AA_Returning:
case AA_Passing:
case AA_Passing_CFAudited:
case AA_Converting:
case AA_Sending:
case AA_Casting:
// The source type comes first.
FirstType = SrcType;
SecondType = DstType;
break;
}
PartialDiagnostic FDiag = PDiag(DiagKind);
if (Action == AA_Passing_CFAudited)
FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
else
FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
// If we can fix the conversion, suggest the FixIts.
assert(ConvHints.isNull() || Hint.isNull());
if (!ConvHints.isNull()) {
for (FixItHint &H : ConvHints.Hints)
FDiag << H;
} else {
FDiag << Hint;
}
if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
if (MayHaveFunctionDiff)
HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
Diag(Loc, FDiag);
if (DiagKind == diag::warn_incompatible_qualified_id &&
PDecl && IFace && !IFace->hasDefinition())
Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
<< IFace->getName() << PDecl->getName();
if (SecondType == Context.OverloadTy)
NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
FirstType, /*TakingAddress=*/true);
if (CheckInferredResultType)
EmitRelatedResultTypeNote(SrcExpr);
if (Action == AA_Returning && ConvTy == IncompatiblePointer)
EmitRelatedResultTypeNoteForReturn(DstType);
if (Complained)
*Complained = true;
return isInvalid;
}
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result) {
class SimpleICEDiagnoser : public VerifyICEDiagnoser {
public:
void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
}
} Diagnoser;
return VerifyIntegerConstantExpression(E, Result, Diagnoser);
}
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold) {
class IDDiagnoser : public VerifyICEDiagnoser {
unsigned DiagID;
public:
IDDiagnoser(unsigned DiagID)
: VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
S.Diag(Loc, DiagID) << SR;
}
} Diagnoser(DiagID);
return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
}
void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
SourceRange SR) {
S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
}
ExprResult
Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold) {
SourceLocation DiagLoc = E->getLocStart();
if (getLangOpts().CPlusPlus11) {
// C++11 [expr.const]p5:
// If an expression of literal class type is used in a context where an
// integral constant expression is required, then that class type shall
// have a single non-explicit conversion function to an integral or
// unscoped enumeration type
ExprResult Converted;
class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
public:
CXX11ConvertDiagnoser(bool Silent)
: ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
Silent, true) {}
SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
QualType T) override {
return S.Diag(Loc, diag::err_ice_not_integral) << T;
}
SemaDiagnosticBuilder diagnoseIncomplete(
Sema &S, SourceLocation Loc, QualType T) override {
return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
}
SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
}
SemaDiagnosticBuilder noteExplicitConv(
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
<< ConvTy->isEnumeralType() << ConvTy;
}
SemaDiagnosticBuilder diagnoseAmbiguous(
Sema &S, SourceLocation Loc, QualType T) override {
return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
}
SemaDiagnosticBuilder noteAmbiguous(
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
<< ConvTy->isEnumeralType() << ConvTy;
}
SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
llvm_unreachable("conversion functions are permitted");
}
} ConvertDiagnoser(Diagnoser.Suppress);
Converted = PerformContextualImplicitConversion(DiagLoc, E,
ConvertDiagnoser);
if (Converted.isInvalid())
return Converted;
E = Converted.get();
if (!E->getType()->isIntegralOrUnscopedEnumerationType())
return ExprError();
} else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
// An ICE must be of integral or unscoped enumeration type.
if (!Diagnoser.Suppress)
Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
return ExprError();
}
// Circumvent ICE checking in C++11 to avoid evaluating the expression twice
// in the non-ICE case.
if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
if (Result)
*Result = E->EvaluateKnownConstInt(Context);
return E;
}
Expr::EvalResult EvalResult;
SmallVector<PartialDiagnosticAt, 8> Notes;
EvalResult.Diag = &Notes;
// Try to evaluate the expression, and produce diagnostics explaining why it's
// not a constant expression as a side-effect.
bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
// In C++11, we can rely on diagnostics being produced for any expression
// which is not a constant expression. If no diagnostics were produced, then
// this is a constant expression.
if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
if (Result)
*Result = EvalResult.Val.getInt();
return E;
}
// If our only note is the usual "invalid subexpression" note, just point
// the caret at its location rather than producing an essentially
// redundant note.
if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
diag::note_invalid_subexpr_in_const_expr) {
DiagLoc = Notes[0].first;
Notes.clear();
}
if (!Folded || !AllowFold) {
if (!Diagnoser.Suppress) {
Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
for (const PartialDiagnosticAt &Note : Notes)
Diag(Note.first, Note.second);
}
return ExprError();
}
Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
for (const PartialDiagnosticAt &Note : Notes)
Diag(Note.first, Note.second);
if (Result)
*Result = EvalResult.Val.getInt();
return E;
}
namespace {
// Handle the case where we conclude a expression which we speculatively
// considered to be unevaluated is actually evaluated.
class TransformToPE : public TreeTransform<TransformToPE> {
typedef TreeTransform<TransformToPE> BaseTransform;
public:
TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
// Make sure we redo semantic analysis
bool AlwaysRebuild() { return true; }
// Make sure we handle LabelStmts correctly.
// FIXME: This does the right thing, but maybe we need a more general
// fix to TreeTransform?
StmtResult TransformLabelStmt(LabelStmt *S) {
S->getDecl()->setStmt(nullptr);
return BaseTransform::TransformLabelStmt(S);
}
// We need to special-case DeclRefExprs referring to FieldDecls which
// are not part of a member pointer formation; normal TreeTransforming
// doesn't catch this case because of the way we represent them in the AST.
// FIXME: This is a bit ugly; is it really the best way to handle this
// case?
//
// Error on DeclRefExprs referring to FieldDecls.
ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
if (isa<FieldDecl>(E->getDecl()) &&
!SemaRef.isUnevaluatedContext())
return SemaRef.Diag(E->getLocation(),
diag::err_invalid_non_static_member_use)
<< E->getDecl() << E->getSourceRange();
return BaseTransform::TransformDeclRefExpr(E);
}
// Exception: filter out member pointer formation
ExprResult TransformUnaryOperator(UnaryOperator *E) {
if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
return E;
return BaseTransform::TransformUnaryOperator(E);
}
ExprResult TransformLambdaExpr(LambdaExpr *E) {
// Lambdas never need to be transformed.
return E;
}
};
}
ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
assert(isUnevaluatedContext() &&
"Should only transform unevaluated expressions");
ExprEvalContexts.back().Context =
ExprEvalContexts[ExprEvalContexts.size()-2].Context;
if (isUnevaluatedContext())
return E;
return TransformToPE(*this).TransformExpr(E);
}
void
Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl,
bool IsDecltype) {
ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
LambdaContextDecl, IsDecltype);
Cleanup.reset();
if (!MaybeODRUseExprs.empty())
std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
}
void
Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
ReuseLambdaContextDecl_t,
bool IsDecltype) {
Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
}
void Sema::PopExpressionEvaluationContext() {
ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
unsigned NumTypos = Rec.NumTypos;
if (!Rec.Lambdas.empty()) {
if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
unsigned D;
if (Rec.isUnevaluated()) {
// C++11 [expr.prim.lambda]p2:
// A lambda-expression shall not appear in an unevaluated operand
// (Clause 5).
D = diag::err_lambda_unevaluated_operand;
} else {
// C++1y [expr.const]p2:
// A conditional-expression e is a core constant expression unless the
// evaluation of e, following the rules of the abstract machine, would
// evaluate [...] a lambda-expression.
D = diag::err_lambda_in_constant_expression;
}
// C++1z allows lambda expressions as core constant expressions.
// FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
// 1607) from appearing within template-arguments and array-bounds that
// are part of function-signatures. Be mindful that P0315 (Lambdas in
// unevaluated contexts) might lift some of these restrictions in a
// future version.
if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
for (const auto *L : Rec.Lambdas)
Diag(L->getLocStart(), D);
} else {
// Mark the capture expressions odr-used. This was deferred
// during lambda expression creation.
for (auto *Lambda : Rec.Lambdas) {
for (auto *C : Lambda->capture_inits())
MarkDeclarationsReferencedInExpr(C);
}
}
}
// When are coming out of an unevaluated context, clear out any
// temporaries that we may have created as part of the evaluation of
// the expression in that context: they aren't relevant because they
// will never be constructed.
if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
ExprCleanupObjects.end());
Cleanup = Rec.ParentCleanup;
CleanupVarDeclMarking();
std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
// Otherwise, merge the contexts together.
} else {
Cleanup.mergeFrom(Rec.ParentCleanup);
MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
Rec.SavedMaybeODRUseExprs.end());
}
// Pop the current expression evaluation context off the stack.
ExprEvalContexts.pop_back();
if (!ExprEvalContexts.empty())
ExprEvalContexts.back().NumTypos += NumTypos;
else
assert(NumTypos == 0 && "There are outstanding typos after popping the "
"last ExpressionEvaluationContextRecord");
}
void Sema::DiscardCleanupsInEvaluationContext() {
ExprCleanupObjects.erase(
ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
ExprCleanupObjects.end());
Cleanup.reset();
MaybeODRUseExprs.clear();
}
ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
if (!E->getType()->isVariablyModifiedType())
return E;
return TransformToPotentiallyEvaluated(E);
}
/// Are we within a context in which some evaluation could be performed (be it
/// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
/// captured by C++'s idea of an "unevaluated context".
static bool isEvaluatableContext(Sema &SemaRef) {
switch (SemaRef.ExprEvalContexts.back().Context) {
case Sema::ExpressionEvaluationContext::Unevaluated:
case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
case Sema::ExpressionEvaluationContext::DiscardedStatement:
// Expressions in this context are never evaluated.
return false;
case Sema::ExpressionEvaluationContext::UnevaluatedList:
case Sema::ExpressionEvaluationContext::ConstantEvaluated:
case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
// Expressions in this context could be evaluated.
return true;
case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
// Referenced declarations will only be used if the construct in the
// containing expression is used, at which point we'll be given another
// turn to mark them.
return false;
}
llvm_unreachable("Invalid context");
}
/// Are we within a context in which references to resolved functions or to
/// variables result in odr-use?
static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
// An expression in a template is not really an expression until it's been
// instantiated, so it doesn't trigger odr-use.
if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
return false;
switch (SemaRef.ExprEvalContexts.back().Context) {
case Sema::ExpressionEvaluationContext::Unevaluated:
case Sema::ExpressionEvaluationContext::UnevaluatedList:
case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
case Sema::ExpressionEvaluationContext::DiscardedStatement:
return false;
case Sema::ExpressionEvaluationContext::ConstantEvaluated:
case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
return true;
case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
return false;
}
llvm_unreachable("Invalid context");
}
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
return Func->isConstexpr() &&
(Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
}
/// \brief Mark a function referenced, and check whether it is odr-used
/// (C++ [basic.def.odr]p2, C99 6.9p3)
void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse) {
assert(Func && "No function?");
Func->setReferenced();
// C++11 [basic.def.odr]p3:
// A function whose name appears as a potentially-evaluated expression is
// odr-used if it is the unique lookup result or the selected member of a
// set of overloaded functions [...].
//
// We (incorrectly) mark overload resolution as an unevaluated context, so we
// can just check that here.
bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
// Determine whether we require a function definition to exist, per
// C++11 [temp.inst]p3:
// Unless a function template specialization has been explicitly
// instantiated or explicitly specialized, the function template
// specialization is implicitly instantiated when the specialization is
// referenced in a context that requires a function definition to exist.
//
// That is either when this is an odr-use, or when a usage of a constexpr
// function occurs within an evaluatable context.
bool NeedDefinition =
OdrUse || (isEvaluatableContext(*this) &&
isImplicitlyDefinableConstexprFunction(Func));
// C++14 [temp.expl.spec]p6:
// If a template [...] is explicitly specialized then that specialization
// shall be declared before the first use of that specialization that would
// cause an implicit instantiation to take place, in every translation unit
// in which such a use occurs
if (NeedDefinition &&
(Func->getTemplateSpecializationKind() != TSK_Undeclared ||
Func->getMemberSpecializationInfo()))
checkSpecializationVisibility(Loc, Func);
// C++14 [except.spec]p17:
// An exception-specification is considered to be needed when:
// - the function is odr-used or, if it appears in an unevaluated operand,
// would be odr-used if the expression were potentially-evaluated;
//
// Note, we do this even if MightBeOdrUse is false. That indicates that the
// function is a pure virtual function we're calling, and in that case the
// function was selected by overload resolution and we need to resolve its
// exception specification for a different reason.
const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
ResolveExceptionSpec(Loc, FPT);
// If we don't need to mark the function as used, and we don't need to
// try to provide a definition, there's nothing more to do.
if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
(!NeedDefinition || Func->getBody()))
return;
// Note that this declaration has been used.
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
if (Constructor->isDefaultConstructor()) {
if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
return;
DefineImplicitDefaultConstructor(Loc, Constructor);
} else if (Constructor->isCopyConstructor()) {
DefineImplicitCopyConstructor(Loc, Constructor);
} else if (Constructor->isMoveConstructor()) {
DefineImplicitMoveConstructor(Loc, Constructor);
}
} else if (Constructor->getInheritedConstructor()) {
DefineInheritingConstructor(Loc, Constructor);
}
} else if (CXXDestructorDecl *Destructor =
dyn_cast<CXXDestructorDecl>(Func)) {
Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
return;
DefineImplicitDestructor(Loc, Destructor);
}
if (Destructor->isVirtual() && getLangOpts().AppleKext)
MarkVTableUsed(Loc, Destructor->getParent());
} else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
if (MethodDecl->isOverloadedOperator() &&
MethodDecl->getOverloadedOperator() == OO_Equal) {
MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
if (MethodDecl->isCopyAssignmentOperator())
DefineImplicitCopyAssignment(Loc, MethodDecl);
else if (MethodDecl->isMoveAssignmentOperator())
DefineImplicitMoveAssignment(Loc, MethodDecl);
}
} else if (isa<CXXConversionDecl>(MethodDecl) &&
MethodDecl->getParent()->isLambda()) {
CXXConversionDecl *Conversion =
cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
if (Conversion->isLambdaToBlockPointerConversion())
DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
else
DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
} else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
MarkVTableUsed(Loc, MethodDecl->getParent());
}
// Recursive functions should be marked when used from another function.
// FIXME: Is this really right?
if (CurContext == Func) return;
// Implicit instantiation of function templates and member functions of
// class templates.
if (Func->isImplicitlyInstantiable()) {
bool AlreadyInstantiated = false;
SourceLocation PointOfInstantiation = Loc;
if (FunctionTemplateSpecializationInfo *SpecInfo
= Func->getTemplateSpecializationInfo()) {
if (SpecInfo->getPointOfInstantiation().isInvalid())
SpecInfo->setPointOfInstantiation(Loc);
else if (SpecInfo->getTemplateSpecializationKind()
== TSK_ImplicitInstantiation) {
AlreadyInstantiated = true;
PointOfInstantiation = SpecInfo->getPointOfInstantiation();
}
} else if (MemberSpecializationInfo *MSInfo
= Func->getMemberSpecializationInfo()) {
if (MSInfo->getPointOfInstantiation().isInvalid())
MSInfo->setPointOfInstantiation(Loc);
else if (MSInfo->getTemplateSpecializationKind()
== TSK_ImplicitInstantiation) {
AlreadyInstantiated = true;
PointOfInstantiation = MSInfo->getPointOfInstantiation();
}
}
if (!AlreadyInstantiated || Func->isConstexpr()) {
if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
CodeSynthesisContexts.size())
PendingLocalImplicitInstantiations.push_back(
std::make_pair(Func, PointOfInstantiation));
else if (Func->isConstexpr())
// Do not defer instantiations of constexpr functions, to avoid the
// expression evaluator needing to call back into Sema if it sees a
// call to such a function.
InstantiateFunctionDefinition(PointOfInstantiation, Func);
else {
PendingInstantiations.push_back(std::make_pair(Func,
PointOfInstantiation));
// Notify the consumer that a function was implicitly instantiated.
Consumer.HandleCXXImplicitFunctionInstantiation(Func);
}
}
} else {
// Walk redefinitions, as some of them may be instantiable.
for (auto i : Func->redecls()) {
if (!i->isUsed(false) && i->isImplicitlyInstantiable())
MarkFunctionReferenced(Loc, i, OdrUse);
}
}
if (!OdrUse) return;
// Keep track of used but undefined functions.
if (!Func->isDefined()) {
if (mightHaveNonExternalLinkage(Func))
UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
else if (Func->getMostRecentDecl()->isInlined() &&
!LangOpts.GNUInline &&
!Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
}
Func->markUsed(Context);
}
static void
diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
ValueDecl *var, DeclContext *DC) {
DeclContext *VarDC = var->getDeclContext();
// If the parameter still belongs to the translation unit, then
// we're actually just using one parameter in the declaration of
// the next.
if (isa<ParmVarDecl>(var) &&
isa<TranslationUnitDecl>(VarDC))
return;
// For C code, don't diagnose about capture if we're not actually in code
// right now; it's impossible to write a non-constant expression outside of
// function context, so we'll get other (more useful) diagnostics later.
//
// For C++, things get a bit more nasty... it would be nice to suppress this
// diagnostic for certain cases like using a local variable in an array bound
// for a member of a local class, but the correct predicate is not obvious.
if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
return;
unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
unsigned ContextKind = 3; // unknown
if (isa<CXXMethodDecl>(VarDC) &&
cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
ContextKind = 2;
} else if (isa<FunctionDecl>(VarDC)) {
ContextKind = 0;
} else if (isa<BlockDecl>(VarDC)) {
ContextKind = 1;
}
S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
<< var << ValueKind << ContextKind << VarDC;
S.Diag(var->getLocation(), diag::note_entity_declared_at)
<< var;
// FIXME: Add additional diagnostic info about class etc. which prevents
// capture.
}
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
bool &SubCapturesAreNested,
QualType &CaptureType,
QualType &DeclRefType) {
// Check whether we've already captured it.
if (CSI->CaptureMap.count(Var)) {
// If we found a capture, any subcaptures are nested.
SubCapturesAreNested = true;
// Retrieve the capture type for this variable.
CaptureType = CSI->getCapture(Var).getCaptureType();
// Compute the type of an expression that refers to this variable.
DeclRefType = CaptureType.getNonReferenceType();
// Similarly to mutable captures in lambda, all the OpenMP captures by copy
// are mutable in the sense that user can change their value - they are
// private instances of the captured declarations.
const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
if (Cap.isCopyCapture() &&
!(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
!(isa<CapturedRegionScopeInfo>(CSI) &&
cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
DeclRefType.addConst();
return true;
}
return false;
}
// Only block literals, captured statements, and lambda expressions can
// capture; other scopes don't work.
static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
SourceLocation Loc,
const bool Diagnose, Sema &S) {
if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
return getLambdaAwareParentOfDeclContext(DC);
else if (Var->hasLocalStorage()) {
if (Diagnose)
diagnoseUncapturableValueReference(S, Loc, Var, DC);
}
return nullptr;
}
// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
// certain types of variables (unnamed, variably modified types etc.)
// so check for eligibility.
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
SourceLocation Loc,
const bool Diagnose, Sema &S) {
bool IsBlock = isa<BlockScopeInfo>(CSI);
bool IsLambda = isa<LambdaScopeInfo>(CSI);
// Lambdas are not allowed to capture unnamed variables
// (e.g. anonymous unions).
// FIXME: The C++11 rule don't actually state this explicitly, but I'm
// assuming that's the intent.
if (IsLambda && !Var->getDeclName()) {
if (Diagnose) {
S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
S.Diag(Var->getLocation(), diag::note_declared_at);
}
return false;
}
// Prohibit variably-modified types in blocks; they're difficult to deal with.
if (Var->getType()->isVariablyModifiedType() && IsBlock) {
if (Diagnose) {
S.Diag(Loc, diag::err_ref_vm_type);
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
// Prohibit structs with flexible array members too.
// We cannot capture what is in the tail end of the struct.
if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
if (VTTy->getDecl()->hasFlexibleArrayMember()) {
if (Diagnose) {
if (IsBlock)
S.Diag(Loc, diag::err_ref_flexarray_type);
else
S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
<< Var->getDeclName();
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
}
const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
// Lambdas and captured statements are not allowed to capture __block
// variables; they don't support the expected semantics.
if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
if (Diagnose) {
S.Diag(Loc, diag::err_capture_block_variable)
<< Var->getDeclName() << !IsLambda;
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
// OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
if (S.getLangOpts().OpenCL && IsBlock &&
Var->getType()->isBlockPointerType()) {
if (Diagnose)
S.Diag(Loc, diag::err_opencl_block_ref_block);
return false;
}
return true;
}
// Returns true if the capture by block was successful.
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
SourceLocation Loc,
const bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const bool Nested,
Sema &S) {
Expr *CopyExpr = nullptr;
bool ByRef = false;
// Blocks are not allowed to capture arrays.
if (CaptureType->isArrayType()) {
if (BuildAndDiagnose) {
S.Diag(Loc, diag::err_ref_array_type);
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
// Forbid the block-capture of autoreleasing variables.
if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
if (BuildAndDiagnose) {
S.Diag(Loc, diag::err_arc_autoreleasing_capture)
<< /*block*/ 0;
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
// Warn about implicitly autoreleasing indirect parameters captured by blocks.
if (const auto *PT = CaptureType->getAs<PointerType>()) {
// This function finds out whether there is an AttributedType of kind
// attr_objc_ownership in Ty. The existence of AttributedType of kind
// attr_objc_ownership implies __autoreleasing was explicitly specified
// rather than being added implicitly by the compiler.
auto IsObjCOwnershipAttributedType = [](QualType Ty) {
while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
return true;
// Peel off AttributedTypes that are not of kind objc_ownership.
Ty = AttrTy->getModifiedType();
}
return false;
};
QualType PointeeTy = PT->getPointeeType();
if (PointeeTy->getAs<ObjCObjectPointerType>() &&
PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
!IsObjCOwnershipAttributedType(PointeeTy)) {
if (BuildAndDiagnose) {
SourceLocation VarLoc = Var->getLocation();
S.Diag(Loc, diag::warn_block_capture_autoreleasing);
{
auto AddAutoreleaseNote =
S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
// Provide a fix-it for the '__autoreleasing' keyword at the
// appropriate location in the variable's type.
if (const auto *TSI = Var->getTypeSourceInfo()) {
PointerTypeLoc PTL =
TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
if (PTL) {
SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
S.getLangOpts());
if (Loc.isValid()) {
StringRef CharAtLoc = Lexer::getSourceText(
CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
S.getSourceManager(), S.getLangOpts());
AddAutoreleaseNote << FixItHint::CreateInsertion(
Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
? " __autoreleasing "
: " __autoreleasing");
}
}
}
}
S.Diag(VarLoc, diag::note_declare_parameter_strong);
}
}
}
const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
if (HasBlocksAttr || CaptureType->isReferenceType() ||
(S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
// Block capture by reference does not change the capture or
// declaration reference types.
ByRef = true;
} else {
// Block capture by copy introduces 'const'.
CaptureType = CaptureType.getNonReferenceType().withConst();
DeclRefType = CaptureType;
if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
// The capture logic needs the destructor, so make sure we mark it.
// Usually this is unnecessary because most local variables have
// their destructors marked at declaration time, but parameters are
// an exception because it's technically only the call site that
// actually requires the destructor.
if (isa<ParmVarDecl>(Var))
S.FinalizeVarWithDestructor(Var, Record);
// Enter a new evaluation context to insulate the copy
// full-expression.
EnterExpressionEvaluationContext scope(
S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
// According to the blocks spec, the capture of a variable from
// the stack requires a const copy constructor. This is not true
// of the copy/move done to move a __block variable to the heap.
Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
DeclRefType.withConst(),
VK_LValue, Loc);
ExprResult Result
= S.PerformCopyInitialization(
InitializedEntity::InitializeBlock(Var->getLocation(),
CaptureType, false),
Loc, DeclRef);
// Build a full-expression copy expression if initialization
// succeeded and used a non-trivial constructor. Recover from
// errors by pretending that the copy isn't necessary.
if (!Result.isInvalid() &&
!cast<CXXConstructExpr>(Result.get())->getConstructor()
->isTrivial()) {
Result = S.MaybeCreateExprWithCleanups(Result);
CopyExpr = Result.get();
}
}
}
}
// Actually capture the variable.
if (BuildAndDiagnose)
BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
SourceLocation(), CaptureType, CopyExpr);
return true;
}
/// \brief Capture the given variable in the captured region.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
VarDecl *Var,
SourceLocation Loc,
const bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const bool RefersToCapturedVariable,
Sema &S) {
// By default, capture variables by reference.
bool ByRef = true;
// Using an LValue reference type is consistent with Lambdas (see below).
if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
if (S.IsOpenMPCapturedDecl(Var))
DeclRefType = DeclRefType.getUnqualifiedType();
ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
}
if (ByRef)
CaptureType = S.Context.getLValueReferenceType(DeclRefType);
else
CaptureType = DeclRefType;
Expr *CopyExpr = nullptr;
if (BuildAndDiagnose) {
// The current implementation assumes that all variables are captured
// by references. Since there is no capture by copy, no expression
// evaluation will be needed.
RecordDecl *RD = RSI->TheRecordDecl;
FieldDecl *Field
= FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
nullptr, false, ICIS_NoInit);
Field->setImplicit(true);
Field->setAccess(AS_private);
RD->addDecl(Field);
CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
DeclRefType, VK_LValue, Loc);
Var->setReferenced(true);
Var->markUsed(S.Context);
}
// Actually capture the variable.
if (BuildAndDiagnose)
RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
SourceLocation(), CaptureType, CopyExpr);
return true;
}
/// \brief Create a field within the lambda class for the variable
/// being captured.
static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
QualType FieldType, QualType DeclRefType,
SourceLocation Loc,
bool RefersToCapturedVariable) {
CXXRecordDecl *Lambda = LSI->Lambda;
// Build the non-static data member.
FieldDecl *Field
= FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
nullptr, false, ICIS_NoInit);
Field->setImplicit(true);
Field->setAccess(AS_private);
Lambda->addDecl(Field);
}
/// \brief Capture the given variable in the lambda.
static bool captureInLambda(LambdaScopeInfo *LSI,
VarDecl *Var,
SourceLocation Loc,
const bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const bool RefersToCapturedVariable,
const Sema::TryCaptureKind Kind,
SourceLocation EllipsisLoc,
const bool IsTopScope,
Sema &S) {
// Determine whether we are capturing by reference or by value.
bool ByRef = false;
if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
} else {
ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
}
// Compute the type of the field that will capture this variable.
if (ByRef) {
// C++11 [expr.prim.lambda]p15:
// An entity is captured by reference if it is implicitly or
// explicitly captured but not captured by copy. It is
// unspecified whether additional unnamed non-static data
// members are declared in the closure type for entities
// captured by reference.
//
// FIXME: It is not clear whether we want to build an lvalue reference
// to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
// to do the former, while EDG does the latter. Core issue 1249 will
// clarify, but for now we follow GCC because it's a more permissive and
// easily defensible position.
CaptureType = S.Context.getLValueReferenceType(DeclRefType);
} else {
// C++11 [expr.prim.lambda]p14:
// For each entity captured by copy, an unnamed non-static
// data member is declared in the closure type. The
// declaration order of these members is unspecified. The type
// of such a data member is the type of the corresponding
// captured entity if the entity is not a reference to an
// object, or the referenced type otherwise. [Note: If the
// captured entity is a reference to a function, the
// corresponding data member is also a reference to a
// function. - end note ]
if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
if (!RefType->getPointeeType()->isFunctionType())
CaptureType = RefType->getPointeeType();
}
// Forbid the lambda copy-capture of autoreleasing variables.
if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
if (BuildAndDiagnose) {
S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
S.Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
}
return false;
}
// Make sure that by-copy captures are of a complete and non-abstract type.
if (BuildAndDiagnose) {
if (!CaptureType->isDependentType() &&
S.RequireCompleteType(Loc, CaptureType,
diag::err_capture_of_incomplete_type,
Var->getDeclName()))
return false;
if (S.RequireNonAbstractType(Loc, CaptureType,
diag::err_capture_of_abstract_type))
return false;
}
}
// Capture this variable in the lambda.
if (BuildAndDiagnose)
addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
RefersToCapturedVariable);
// Compute the type of a reference to this captured variable.
if (ByRef)
DeclRefType = CaptureType.getNonReferenceType();
else {
// C++ [expr.prim.lambda]p5:
// The closure type for a lambda-expression has a public inline
// function call operator [...]. This function call operator is
// declared const (9.3.1) if and only if the lambda-expression's
// parameter-declaration-clause is not followed by mutable.
DeclRefType = CaptureType.getNonReferenceType();
if (!LSI->Mutable && !CaptureType->isReferenceType())
DeclRefType.addConst();
}
// Add the capture.
if (BuildAndDiagnose)
LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
return true;
}
bool Sema::tryCaptureVariable(
VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
// An init-capture is notionally from the context surrounding its
// declaration, but its parent DC is the lambda class.
DeclContext *VarDC = Var->getDeclContext();
if (Var->isInitCapture())
VarDC = VarDC->getParent();
DeclContext *DC = CurContext;
const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
// We need to sync up the Declaration Context with the
// FunctionScopeIndexToStopAt
if (FunctionScopeIndexToStopAt) {
unsigned FSIndex = FunctionScopes.size() - 1;
while (FSIndex != MaxFunctionScopesIndex) {
DC = getLambdaAwareParentOfDeclContext(DC);
--FSIndex;
}
}
// If the variable is declared in the current context, there is no need to
// capture it.
if (VarDC == DC) return true;
// Capture global variables if it is required to use private copy of this
// variable.
bool IsGlobal = !Var->hasLocalStorage();
if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
return true;
// Walk up the stack to determine whether we can capture the variable,
// performing the "simple" checks that don't depend on type. We stop when
// we've either hit the declared scope of the variable or find an existing
// capture of that variable. We start from the innermost capturing-entity
// (the DC) and ensure that all intervening capturing-entities
// (blocks/lambdas etc.) between the innermost capturer and the variable`s
// declcontext can either capture the variable or have already captured
// the variable.
CaptureType = Var->getType();
DeclRefType = CaptureType.getNonReferenceType();
bool Nested = false;
bool Explicit = (Kind != TryCapture_Implicit);
unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
do {
// Only block literals, captured statements, and lambda expressions can
// capture; other scopes don't work.
DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
ExprLoc,
BuildAndDiagnose,
*this);
// We need to check for the parent *first* because, if we *have*
// private-captured a global variable, we need to recursively capture it in
// intermediate blocks, lambdas, etc.
if (!ParentDC) {
if (IsGlobal) {
FunctionScopesIndex = MaxFunctionScopesIndex - 1;
break;
}
return true;
}
FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
// Check whether we've already captured it.
if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
DeclRefType)) {
CSI->getCapture(Var).markUsed(BuildAndDiagnose);
break;
}
// If we are instantiating a generic lambda call operator body,
// we do not want to capture new variables. What was captured
// during either a lambdas transformation or initial parsing
// should be used.
if (isGenericLambdaCallOperatorSpecialization(DC)) {
if (BuildAndDiagnose) {
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
} else
diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
}
return true;
}
// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
// certain types of variables (unnamed, variably modified types etc.)
// so check for eligibility.
if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
return true;
// Try to capture variable-length arrays types.
if (Var->getType()->isVariablyModifiedType()) {
// We're going to walk down into the type and look for VLA
// expressions.
QualType QTy = Var->getType();
if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
QTy = PVD->getOriginalType();
captureVariablyModifiedType(Context, QTy, CSI);
}
if (getLangOpts().OpenMP) {
if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
// OpenMP private variables should not be captured in outer scope, so
// just break here. Similarly, global variables that are captured in a
// target region should not be captured outside the scope of the region.
if (RSI->CapRegionKind == CR_OpenMP) {
auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
// When we detect target captures we are looking from inside the
// target region, therefore we need to propagate the capture from the
// enclosing region. Therefore, the capture is not initially nested.
if (IsTargetCap)
FunctionScopesIndex--;
if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
Nested = !IsTargetCap;
DeclRefType = DeclRefType.getUnqualifiedType();
CaptureType = Context.getLValueReferenceType(DeclRefType);
break;
}
}
}
}
if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
// No capture-default, and this is not an explicit capture
// so cannot capture this variable.
if (BuildAndDiagnose) {
Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Diag(Var->getLocation(), diag::note_previous_decl)
<< Var->getDeclName();
if (cast<LambdaScopeInfo>(CSI)->Lambda)
Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
diag::note_lambda_decl);
// FIXME: If we error out because an outer lambda can not implicitly
// capture a variable that an inner lambda explicitly captures, we
// should have the inner lambda do the explicit capture - because
// it makes for cleaner diagnostics later. This would purely be done
// so that the diagnostic does not misleadingly claim that a variable
// can not be captured by a lambda implicitly even though it is captured
// explicitly. Suggestion:
// - create const bool VariableCaptureWasInitiallyExplicit = Explicit
// at the function head
// - cache the StartingDeclContext - this must be a lambda
// - captureInLambda in the innermost lambda the variable.
}
return true;
}
FunctionScopesIndex--;
DC = ParentDC;
Explicit = false;
} while (!VarDC->Equals(DC));
// Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
// computing the type of the capture at each step, checking type-specific
// requirements, and adding captures if requested.
// If the variable had already been captured previously, we start capturing
// at the lambda nested within that one.
for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
++I) {
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
if (!captureInBlock(BSI, Var, ExprLoc,
BuildAndDiagnose, CaptureType,
DeclRefType, Nested, *this))
return true;
Nested = true;
} else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
if (!captureInCapturedRegion(RSI, Var, ExprLoc,
BuildAndDiagnose, CaptureType,
DeclRefType, Nested, *this))
return true;
Nested = true;
} else {
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
if (!captureInLambda(LSI, Var, ExprLoc,
BuildAndDiagnose, CaptureType,
DeclRefType, Nested, Kind, EllipsisLoc,
/*IsTopScope*/I == N - 1, *this))
return true;
Nested = true;
}
}
return false;
}
bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind, SourceLocation EllipsisLoc) {
QualType CaptureType;
QualType DeclRefType;
return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
/*BuildAndDiagnose=*/true, CaptureType,
DeclRefType, nullptr);
}
bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
QualType CaptureType;
QualType DeclRefType;
return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
/*BuildAndDiagnose=*/false, CaptureType,
DeclRefType, nullptr);
}
QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
QualType CaptureType;
QualType DeclRefType;
// Determine whether we can capture this variable.
if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
/*BuildAndDiagnose=*/false, CaptureType,
DeclRefType, nullptr))
return QualType();
return DeclRefType;
}
// If either the type of the variable or the initializer is dependent,
// return false. Otherwise, determine whether the variable is a constant
// expression. Use this if you need to know if a variable that might or
// might not be dependent is truly a constant expression.
static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
ASTContext &Context) {
if (Var->getType()->isDependentType())
return false;
const VarDecl *DefVD = nullptr;
Var->getAnyInitializer(DefVD);
if (!DefVD)
return false;
EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Expr *Init = cast<Expr>(Eval->Value);
if (Init->isValueDependent())
return false;
return IsVariableAConstantExpression(Var, Context);
}
void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
// Per C++11 [basic.def.odr], a variable is odr-used "unless it is
// an object that satisfies the requirements for appearing in a
// constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
// is immediately applied." This function handles the lvalue-to-rvalue
// conversion part.
MaybeODRUseExprs.erase(E->IgnoreParens());
// If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
// to a variable that is a constant expression, and if so, identify it as
// a reference to a variable that does not involve an odr-use of that
// variable.
if (LambdaScopeInfo *LSI = getCurLambda()) {
Expr *SansParensExpr = E->IgnoreParens();
VarDecl *Var = nullptr;
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
Var = dyn_cast<VarDecl>(ME->getMemberDecl());
if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
LSI->markVariableExprAsNonODRUsed(SansParensExpr);
}
}
ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
Res = CorrectDelayedTyposInExpr(Res);
if (!Res.isUsable())
return Res;
// If a constant-expression is a reference to a variable where we delay
// deciding whether it is an odr-use, just assume we will apply the
// lvalue-to-rvalue conversion. In the one case where this doesn't happen
// (a non-type template argument), we have special handling anyway.
UpdateMarkingForLValueToRValue(Res.get());
return Res;
}
void Sema::CleanupVarDeclMarking() {
for (Expr *E : MaybeODRUseExprs) {
VarDecl *Var;
SourceLocation Loc;
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
Var = cast<VarDecl>(DRE->getDecl());
Loc = DRE->getLocation();
} else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Var = cast<VarDecl>(ME->getMemberDecl());
Loc = ME->getMemberLoc();
} else {
llvm_unreachable("Unexpected expression");
}
MarkVarDeclODRUsed(Var, Loc, *this,
/*MaxFunctionScopeIndex Pointer*/ nullptr);
}
MaybeODRUseExprs.clear();
}
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
VarDecl *Var, Expr *E) {
assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
"Invalid Expr argument to DoMarkVarDeclReferenced");
Var->setReferenced();
TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
bool OdrUseContext = isOdrUseContext(SemaRef);
bool NeedDefinition =
OdrUseContext || (isEvaluatableContext(SemaRef) &&
Var->isUsableInConstantExpressions(SemaRef.Context));
VarTemplateSpecializationDecl *VarSpec =
dyn_cast<VarTemplateSpecializationDecl>(Var);
assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.");
// If this might be a member specialization of a static data member, check
// the specialization is visible. We already did the checks for variable
// template specializations when we created them.
if (NeedDefinition && TSK != TSK_Undeclared &&
!isa<VarTemplateSpecializationDecl>(Var))
SemaRef.checkSpecializationVisibility(Loc, Var);
// Perform implicit instantiation of static data members, static data member
// templates of class templates, and variable template specializations. Delay
// instantiations of variable templates, except for those that could be used
// in a constant expression.
if (NeedDefinition && isTemplateInstantiation(TSK)) {
bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
if (Var->getPointOfInstantiation().isInvalid()) {
// This is a modification of an existing AST node. Notify listeners.
if (ASTMutationListener *L = SemaRef.getASTMutationListener())
L->StaticDataMemberInstantiated(Var);
} else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
// Don't bother trying to instantiate it again, unless we might need
// its initializer before we get to the end of the TU.
TryInstantiating = false;
}
if (Var->getPointOfInstantiation().isInvalid())
Var->setTemplateSpecializationKind(TSK, Loc);
if (TryInstantiating) {
SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
bool InstantiationDependent = false;
bool IsNonDependent =
VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
VarSpec->getTemplateArgsInfo(), InstantiationDependent)
: true;
// Do not instantiate specializations that are still type-dependent.
if (IsNonDependent) {
if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
// Do not defer instantiations of variables which could be used in a
// constant expression.
SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
} else {
SemaRef.PendingInstantiations
.push_back(std::make_pair(Var, PointOfInstantiation));
}
}
}
}
// Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
// the requirements for appearing in a constant expression (5.19) and, if
// it is an object, the lvalue-to-rvalue conversion (4.1)
// is immediately applied." We check the first part here, and
// Sema::UpdateMarkingForLValueToRValue deals with the second part.
// Note that we use the C++11 definition everywhere because nothing in
// C++03 depends on whether we get the C++03 version correct. The second
// part does not apply to references, since they are not objects.
if (OdrUseContext && E &&
IsVariableAConstantExpression(Var, SemaRef.Context)) {
// A reference initialized by a constant expression can never be
// odr-used, so simply ignore it.
if (!Var->getType()->isReferenceType())
SemaRef.MaybeODRUseExprs.insert(E);
} else if (OdrUseContext) {
MarkVarDeclODRUsed(Var, Loc, SemaRef,
/*MaxFunctionScopeIndex ptr*/ nullptr);
} else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
// If this is a dependent context, we don't need to mark variables as
// odr-used, but we may still need to track them for lambda capture.
// FIXME: Do we also need to do this inside dependent typeid expressions
// (which are modeled as unevaluated at this point)?
const bool RefersToEnclosingScope =
(SemaRef.CurContext != Var->getDeclContext() &&
Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
if (RefersToEnclosingScope) {
LambdaScopeInfo *const LSI =
SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
// If a variable could potentially be odr-used, defer marking it so
// until we finish analyzing the full expression for any
// lvalue-to-rvalue
// or discarded value conversions that would obviate odr-use.
// Add it to the list of potential captures that will be analyzed
// later (ActOnFinishFullExpr) for eventual capture and odr-use marking
// unless the variable is a reference that was initialized by a constant
// expression (this will never need to be captured or odr-used).
assert(E && "Capture variable should be used in an expression.");
if (!Var->getType()->isReferenceType() ||
!IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
LSI->addPotentialCapture(E->IgnoreParens());
}
}
}
}
/// \brief Mark a variable referenced, and check whether it is odr-used
/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
/// used directly for normal expressions referring to VarDecl.
void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
}
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Decl *D, Expr *E, bool MightBeOdrUse) {
if (SemaRef.isInOpenMPDeclareTargetContext())
SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
return;
}
SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
// If this is a call to a method via a cast, also mark the method in the
// derived class used in case codegen can devirtualize the call.
const MemberExpr *ME = dyn_cast<MemberExpr>(E);
if (!ME)
return;
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
if (!MD)
return;
// Only attempt to devirtualize if this is truly a virtual call.
bool IsVirtualCall = MD->isVirtual() &&
ME->performsVirtualDispatch(SemaRef.getLangOpts());
if (!IsVirtualCall)
return;
const Expr *Base = ME->getBase();
const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
if (!MostDerivedClassDecl)
return;
CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
if (!DM || DM->isPure())
return;
SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
}
/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
// TODO: update this with DR# once a defect report is filed.
// C++11 defect. The address of a pure member should not be an ODR use, even
// if it's a qualified reference.
bool OdrUse = true;
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
if (Method->isVirtual())
OdrUse = false;
MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
}
/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
void Sema::MarkMemberReferenced(MemberExpr *E) {
// C++11 [basic.def.odr]p2:
// A non-overloaded function whose name appears as a potentially-evaluated
// expression or a member of a set of candidate functions, if selected by
// overload resolution when referred to from a potentially-evaluated
// expression, is odr-used, unless it is a pure virtual function and its
// name is not explicitly qualified.
bool MightBeOdrUse = true;
if (E->performsVirtualDispatch(getLangOpts())) {
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
if (Method->isPure())
MightBeOdrUse = false;
}
SourceLocation Loc = E->getMemberLoc().isValid() ?
E->getMemberLoc() : E->getLocStart();
MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
}
/// \brief Perform marking for a reference to an arbitrary declaration. It
/// marks the declaration referenced, and performs odr-use checking for
/// functions and variables. This method should not be used when building a
/// normal expression which refers to a variable.
void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
bool MightBeOdrUse) {
if (MightBeOdrUse) {
if (auto *VD = dyn_cast<VarDecl>(D)) {
MarkVariableReferenced(Loc, VD);
return;
}
}
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
return;
}
D->setReferenced();
}
namespace {
// Mark all of the declarations used by a type as referenced.
// FIXME: Not fully implemented yet! We need to have a better understanding
// of when we're entering a context we should not recurse into.
// FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
// TreeTransforms rebuilding the type in a new context. Rather than
// duplicating the TreeTransform logic, we should consider reusing it here.
// Currently that causes problems when rebuilding LambdaExprs.
class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
Sema &S;
SourceLocation Loc;
public:
typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
bool TraverseTemplateArgument(const TemplateArgument &Arg);
};
}
bool MarkReferencedDecls::TraverseTemplateArgument(
const TemplateArgument &Arg) {
{
// A non-type template argument is a constant-evaluated context.
EnterExpressionEvaluationContext Evaluated(
S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
if (Arg.getKind() == TemplateArgument::Declaration) {
if (Decl *D = Arg.getAsDecl())
S.MarkAnyDeclReferenced(Loc, D, true);
} else if (Arg.getKind() == TemplateArgument::Expression) {
S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
}
}
return Inherited::TraverseTemplateArgument(Arg);
}
void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
MarkReferencedDecls Marker(*this, Loc);
Marker.TraverseType(T);
}
namespace {
/// \brief Helper class that marks all of the declarations referenced by
/// potentially-evaluated subexpressions as "referenced".
class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
Sema &S;
bool SkipLocalVariables;
public:
typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
: Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
void VisitDeclRefExpr(DeclRefExpr *E) {
// If we were asked not to visit local variables, don't.
if (SkipLocalVariables) {
if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
if (VD->hasLocalStorage())
return;
}
S.MarkDeclRefReferenced(E);
}
void VisitMemberExpr(MemberExpr *E) {
S.MarkMemberReferenced(E);
Inherited::VisitMemberExpr(E);
}
void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
S.MarkFunctionReferenced(E->getLocStart(),
const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
Visit(E->getSubExpr());
}
void VisitCXXNewExpr(CXXNewExpr *E) {
if (E->getOperatorNew())
S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
if (E->getOperatorDelete())
S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Inherited::VisitCXXNewExpr(E);
}
void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
if (E->getOperatorDelete())
S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
S.MarkFunctionReferenced(E->getLocStart(),
S.LookupDestructor(Record));
}
Inherited::VisitCXXDeleteExpr(E);
}
void VisitCXXConstructExpr(CXXConstructExpr *E) {
S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Inherited::VisitCXXConstructExpr(E);
}
void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
Visit(E->getExpr());
}
void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Inherited::VisitImplicitCastExpr(E);
if (E->getCastKind() == CK_LValueToRValue)
S.UpdateMarkingForLValueToRValue(E->getSubExpr());
}
};
}
/// \brief Mark any declarations that appear within this expression or any
/// potentially-evaluated subexpressions as "referenced".
///
/// \param SkipLocalVariables If true, don't mark local variables as
/// 'referenced'.
void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables) {
EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
}
/// \brief Emit a diagnostic that describes an effect on the run-time behavior
/// of the program being compiled.
///
/// This routine emits the given diagnostic when the code currently being
/// type-checked is "potentially evaluated", meaning that there is a
/// possibility that the code will actually be executable. Code in sizeof()
/// expressions, code used only during overload resolution, etc., are not
/// potentially evaluated. This routine will suppress such diagnostics or,
/// in the absolutely nutty case of potentially potentially evaluated
/// expressions (C++ typeid), queue the diagnostic to potentially emit it
/// later.
///
/// This routine should be used for all diagnostics that describe the run-time
/// behavior of a program, such as passing a non-POD value through an ellipsis.
/// Failure to do so will likely result in spurious diagnostics or failures
/// during overload resolution or within sizeof/alignof/typeof/typeid.
bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD) {
switch (ExprEvalContexts.back().Context) {
case ExpressionEvaluationContext::Unevaluated:
case ExpressionEvaluationContext::UnevaluatedList:
case ExpressionEvaluationContext::UnevaluatedAbstract:
case ExpressionEvaluationContext::DiscardedStatement:
// The argument will never be evaluated, so don't complain.
break;
case ExpressionEvaluationContext::ConstantEvaluated:
// Relevant diagnostics should be produced by constant evaluation.
break;
case ExpressionEvaluationContext::PotentiallyEvaluated:
case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
if (Statement && getCurFunctionOrMethodDecl()) {
FunctionScopes.back()->PossiblyUnreachableDiags.
push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
}
else
Diag(Loc, PD);
return true;
}
return false;
}
bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD) {
if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
return false;
// If we're inside a decltype's expression, don't check for a valid return
// type or construct temporaries until we know whether this is the last call.
if (ExprEvalContexts.back().IsDecltype) {
ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
return false;
}
class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
FunctionDecl *FD;
CallExpr *CE;
public:
CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
: FD(FD), CE(CE) { }
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
if (!FD) {
S.Diag(Loc, diag::err_call_incomplete_return)
<< T << CE->getSourceRange();
return;
}
S.Diag(Loc, diag::err_call_function_incomplete_return)
<< CE->getSourceRange() << FD->getDeclName() << T;
S.Diag(FD->getLocation(), diag::note_entity_declared_at)
<< FD->getDeclName();
}
} Diagnoser(FD, CE);
if (RequireCompleteType(Loc, ReturnType, Diagnoser))
return true;
return false;
}
// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
// will prevent this condition from triggering, which is what we want.
void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
SourceLocation Loc;
unsigned diagnostic = diag::warn_condition_is_assignment;
bool IsOrAssign = false;
if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
return;
IsOrAssign = Op->getOpcode() == BO_OrAssign;
// Greylist some idioms by putting them into a warning subcategory.
if (ObjCMessageExpr *ME
= dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
Selector Sel = ME->getSelector();
// self = [<foo> init...]
if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
diagnostic = diag::warn_condition_is_idiomatic_assignment;
// <foo> = [<bar> nextObject]
else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
diagnostic = diag::warn_condition_is_idiomatic_assignment;
}
Loc = Op->getOperatorLoc();
} else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
return;
IsOrAssign = Op->getOperator() == OO_PipeEqual;
Loc = Op->getOperatorLoc();
} else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
else {
// Not an assignment.
return;
}
Diag(Loc, diagnostic) << E->getSourceRange();
SourceLocation Open = E->getLocStart();
SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
Diag(Loc, diag::note_condition_assign_silence)
<< FixItHint::CreateInsertion(Open, "(")
<< FixItHint::CreateInsertion(Close, ")");
if (IsOrAssign)
Diag(Loc, diag::note_condition_or_assign_to_comparison)
<< FixItHint::CreateReplacement(Loc, "!=");
else
Diag(Loc, diag::note_condition_assign_to_comparison)
<< FixItHint::CreateReplacement(Loc, "==");
}
/// \brief Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
// Don't warn if the parens came from a macro.
SourceLocation parenLoc = ParenE->getLocStart();
if (parenLoc.isInvalid() || parenLoc.isMacroID())
return;
// Don't warn for dependent expressions.
if (ParenE->isTypeDependent())
return;
Expr *E = ParenE->IgnoreParens();
if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
if (opE->getOpcode() == BO_EQ &&
opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
== Expr::MLV_Valid) {
SourceLocation Loc = opE->getOperatorLoc();
Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
SourceRange ParenERange = ParenE->getSourceRange();
Diag(Loc, diag::note_equality_comparison_silence)
<< FixItHint::CreateRemoval(ParenERange.getBegin())
<< FixItHint::CreateRemoval(ParenERange.getEnd());
Diag(Loc, diag::note_equality_comparison_to_assign)
<< FixItHint::CreateReplacement(Loc, "=");
}
}
ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr) {
DiagnoseAssignmentAsCondition(E);
if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
DiagnoseEqualityWithExtraParens(parenE);
ExprResult result = CheckPlaceholderExpr(E);
if (result.isInvalid()) return ExprError();
E = result.get();
if (!E->isTypeDependent()) {
if (getLangOpts().CPlusPlus)
return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
if (ERes.isInvalid())
return ExprError();
E = ERes.get();
QualType T = E->getType();
if (!T->isScalarType()) { // C99 6.8.4.1p1
Diag(Loc, diag::err_typecheck_statement_requires_scalar)
<< T << E->getSourceRange();
return ExprError();
}
CheckBoolLikeConversion(E, Loc);
}
return E;
}
Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK) {
// Empty conditions are valid in for-statements.
if (!SubExpr)
return ConditionResult();
ExprResult Cond;
switch (CK) {
case ConditionKind::Boolean:
Cond = CheckBooleanCondition(Loc, SubExpr);
break;
case ConditionKind::ConstexprIf:
Cond = CheckBooleanCondition(Loc, SubExpr, true);
break;
case ConditionKind::Switch:
Cond = CheckSwitchCondition(Loc, SubExpr);
break;
}
if (Cond.isInvalid())
return ConditionError();
// FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
if (!FullExpr.get())
return ConditionError();
return ConditionResult(*this, nullptr, FullExpr,
CK == ConditionKind::ConstexprIf);
}
namespace {
/// A visitor for rebuilding a call to an __unknown_any expression
/// to have an appropriate type.
struct RebuildUnknownAnyFunction
: StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
Sema &S;
RebuildUnknownAnyFunction(Sema &S) : S(S) {}
ExprResult VisitStmt(Stmt *S) {
llvm_unreachable("unexpected statement!");
}
ExprResult VisitExpr(Expr *E) {
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
<< E->getSourceRange();
return ExprError();
}
/// Rebuild an expression which simply semantically wraps another
/// expression which it shares the type and value kind of.
template <class T> ExprResult rebuildSugarExpr(T *E) {
ExprResult SubResult = Visit(E->getSubExpr());
if (SubResult.isInvalid()) return ExprError();
Expr *SubExpr = SubResult.get();
E->setSubExpr(SubExpr);
E->setType(SubExpr->getType());
E->setValueKind(SubExpr->getValueKind());
assert(E->getObjectKind() == OK_Ordinary);
return E;
}
ExprResult VisitParenExpr(ParenExpr *E) {
return rebuildSugarExpr(E);
}
ExprResult VisitUnaryExtension(UnaryOperator *E) {
return rebuildSugarExpr(E);
}
ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
ExprResult SubResult = Visit(E->getSubExpr());
if (SubResult.isInvalid()) return ExprError();
Expr *SubExpr = SubResult.get();
E->setSubExpr(SubExpr);
E->setType(S.Context.getPointerType(SubExpr->getType()));
assert(E->getValueKind() == VK_RValue);
assert(E->getObjectKind() == OK_Ordinary);
return E;
}
ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
E->setType(VD->getType());
assert(E->getValueKind() == VK_RValue);
if (S.getLangOpts().CPlusPlus &&
!(isa<CXXMethodDecl>(VD) &&
cast<CXXMethodDecl>(VD)->isInstance()))
E->setValueKind(VK_LValue);
return E;
}
ExprResult VisitMemberExpr(MemberExpr *E) {
return resolveDecl(E, E->getMemberDecl());
}
ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
return resolveDecl(E, E->getDecl());
}
};
}
/// Given a function expression of unknown-any type, try to rebuild it
/// to have a function type.
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
if (Result.isInvalid()) return ExprError();
return S.DefaultFunctionArrayConversion(Result.get());
}
namespace {
/// A visitor for rebuilding an expression of type __unknown_anytype
/// into one which resolves the type directly on the referring
/// expression. Strict preservation of the original source
/// structure is not a goal.
struct RebuildUnknownAnyExpr
: StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
Sema &S;
/// The current destination type.
QualType DestType;
RebuildUnknownAnyExpr(Sema &S, QualType CastType)
: S(S), DestType(CastType) {}
ExprResult VisitStmt(Stmt *S) {
llvm_unreachable("unexpected statement!");
}
ExprResult VisitExpr(Expr *E) {
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
<< E->getSourceRange();
return ExprError();
}
ExprResult VisitCallExpr(CallExpr *E);
ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
/// Rebuild an expression which simply semantically wraps another
/// expression which it shares the type and value kind of.
template <class T> ExprResult rebuildSugarExpr(T *E) {
ExprResult SubResult = Visit(E->getSubExpr());
if (SubResult.isInvalid()) return ExprError();
Expr *SubExpr = SubResult.get();
E->setSubExpr(SubExpr);
E->setType(SubExpr->getType());
E->setValueKind(SubExpr->getValueKind());
assert(E->getObjectKind() == OK_Ordinary);
return E;
}
ExprResult VisitParenExpr(ParenExpr *E) {
return rebuildSugarExpr(E);
}
ExprResult VisitUnaryExtension(UnaryOperator *E) {
return rebuildSugarExpr(E);
}
ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
const PointerType *Ptr = DestType->getAs<PointerType>();
if (!Ptr) {
S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
<< E->getSourceRange();
return ExprError();
}
if (isa<CallExpr>(E->getSubExpr())) {
S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
<< E->getSourceRange();
return ExprError();
}
assert(E->getValueKind() == VK_RValue);
assert(E->getObjectKind() == OK_Ordinary);
E->setType(DestType);
// Build the sub-expression as if it were an object of the pointee type.
DestType = Ptr->getPointeeType();
ExprResult SubResult = Visit(E->getSubExpr());
if (SubResult.isInvalid()) return ExprError();
E->setSubExpr(SubResult.get());
return E;
}
ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
ExprResult resolveDecl(Expr *E, ValueDecl *VD);
ExprResult VisitMemberExpr(MemberExpr *E) {
return resolveDecl(E, E->getMemberDecl());
}
ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
return resolveDecl(E, E->getDecl());
}
};
}
/// Rebuilds a call expression which yielded __unknown_anytype.
ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
Expr *CalleeExpr = E->getCallee();
enum FnKind {
FK_MemberFunction,
FK_FunctionPointer,
FK_BlockPointer
};
FnKind Kind;
QualType CalleeType = CalleeExpr->getType();
if (CalleeType == S.Context.BoundMemberTy) {
assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
Kind = FK_MemberFunction;
CalleeType = Expr::findBoundMemberType(CalleeExpr);
} else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
CalleeType = Ptr->getPointeeType();
Kind = FK_FunctionPointer;
} else {
CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
Kind = FK_BlockPointer;
}
const FunctionType *FnType = CalleeType->castAs<FunctionType>();
// Verify that this is a legal result type of a function.
if (DestType->isArrayType() || DestType->isFunctionType()) {
unsigned diagID = diag::err_func_returning_array_function;
if (Kind == FK_BlockPointer)
diagID = diag::err_block_returning_array_function;
S.Diag(E->getExprLoc(), diagID)
<< DestType->isFunctionType() << DestType;
return ExprError();
}
// Otherwise, go ahead and set DestType as the call's result.
E->setType(DestType.getNonLValueExprType(S.Context));
E->setValueKind(Expr::getValueKindForType(DestType));
assert(E->getObjectKind() == OK_Ordinary);
// Rebuild the function type, replacing the result type with DestType.
const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
if (Proto) {
// __unknown_anytype(...) is a special case used by the debugger when
// it has no idea what a function's signature is.
//
// We want to build this call essentially under the K&R
// unprototyped rules, but making a FunctionNoProtoType in C++
// would foul up all sorts of assumptions. However, we cannot
// simply pass all arguments as variadic arguments, nor can we
// portably just call the function under a non-variadic type; see
// the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
// However, it turns out that in practice it is generally safe to
// call a function declared as "A foo(B,C,D);" under the prototype
// "A foo(B,C,D,...);". The only known exception is with the
// Windows ABI, where any variadic function is implicitly cdecl
// regardless of its normal CC. Therefore we change the parameter
// types to match the types of the arguments.
//
// This is a hack, but it is far superior to moving the
// corresponding target-specific code from IR-gen to Sema/AST.
ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
SmallVector<QualType, 8> ArgTypes;
if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
ArgTypes.reserve(E->getNumArgs());
for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Expr *Arg = E->getArg(i);
QualType ArgType = Arg->getType();
if (E->isLValue()) {
ArgType = S.Context.getLValueReferenceType(ArgType);
} else if (E->isXValue()) {
ArgType = S.Context.getRValueReferenceType(ArgType);
}
ArgTypes.push_back(ArgType);
}
ParamTypes = ArgTypes;
}
DestType = S.Context.getFunctionType(DestType, ParamTypes,
Proto->getExtProtoInfo());
} else {
DestType = S.Context.getFunctionNoProtoType(DestType,
FnType->getExtInfo());
}
// Rebuild the appropriate pointer-to-function type.
switch (Kind) {
case FK_MemberFunction:
// Nothing to do.
break;
case FK_FunctionPointer:
DestType = S.Context.getPointerType(DestType);
break;
case FK_BlockPointer:
DestType = S.Context.getBlockPointerType(DestType);
break;
}
// Finally, we can recurse.
ExprResult CalleeResult = Visit(CalleeExpr);
if (!CalleeResult.isUsable()) return ExprError();
E->setCallee(CalleeResult.get());
// Bind a temporary if necessary.
return S.MaybeBindToTemporary(E);
}
ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
// Verify that this is a legal result type of a call.
if (DestType->isArrayType() || DestType->isFunctionType()) {
S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
<< DestType->isFunctionType() << DestType;
return ExprError();
}
// Rewrite the method result type if available.
if (ObjCMethodDecl *Method = E->getMethodDecl()) {
assert(Method->getReturnType() == S.Context.UnknownAnyTy);
Method->setReturnType(DestType);
}
// Change the type of the message.
E->setType(DestType.getNonReferenceType());
E->setValueKind(Expr::getValueKindForType(DestType));
return S.MaybeBindToTemporary(E);
}
ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
// The only case we should ever see here is a function-to-pointer decay.
if (E->getCastKind() == CK_FunctionToPointerDecay) {
assert(E->getValueKind() == VK_RValue);
assert(E->getObjectKind() == OK_Ordinary);
E->setType(DestType);
// Rebuild the sub-expression as the pointee (function) type.
DestType = DestType->castAs<PointerType>()->getPointeeType();
ExprResult Result = Visit(E->getSubExpr());
if (!Result.isUsable()) return ExprError();
E->setSubExpr(Result.get());
return E;
} else if (E->getCastKind() == CK_LValueToRValue) {
assert(E->getValueKind() == VK_RValue);
assert(E->getObjectKind() == OK_Ordinary);
assert(isa<BlockPointerType>(E->getType()));
E->setType(DestType);
// The sub-expression has to be a lvalue reference, so rebuild it as such.
DestType = S.Context.getLValueReferenceType(DestType);
ExprResult Result = Visit(E->getSubExpr());
if (!Result.isUsable()) return ExprError();
E->setSubExpr(Result.get());
return E;
} else {
llvm_unreachable("Unhandled cast type!");
}
}
ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
ExprValueKind ValueKind = VK_LValue;
QualType Type = DestType;
// We know how to make this work for certain kinds of decls:
// - functions
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
if (const PointerType *Ptr = Type->getAs<PointerType>()) {
DestType = Ptr->getPointeeType();
ExprResult Result = resolveDecl(E, VD);
if (Result.isInvalid()) return ExprError();
return S.ImpCastExprToType(Result.get(), Type,
CK_FunctionToPointerDecay, VK_RValue);
}
if (!Type->isFunctionType()) {
S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
<< VD << E->getSourceRange();
return ExprError();
}
if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
// We must match the FunctionDecl's type to the hack introduced in
// RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
// type. See the lengthy commentary in that routine.
QualType FDT = FD->getType();
const FunctionType *FnType = FDT->castAs<FunctionType>();
const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
SourceLocation Loc = FD->getLocation();
FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
FD->getDeclContext(),
Loc, Loc, FD->getNameInfo().getName(),
DestType, FD->getTypeSourceInfo(),
SC_None, false/*isInlineSpecified*/,
FD->hasPrototype(),
false/*isConstexprSpecified*/);
if (FD->getQualifier())
NewFD->setQualifierInfo(FD->getQualifierLoc());
SmallVector<ParmVarDecl*, 16> Params;
for (const auto &AI : FT->param_types()) {
ParmVarDecl *Param =
S.BuildParmVarDeclForTypedef(FD, Loc, AI);
Param->setScopeInfo(0, Params.size());
Params.push_back(Param);
}
NewFD->setParams(Params);
DRE->setDecl(NewFD);
VD = DRE->getDecl();
}
}
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
if (MD->isInstance()) {
ValueKind = VK_RValue;
Type = S.Context.BoundMemberTy;
}
// Function references aren't l-values in C.
if (!S.getLangOpts().CPlusPlus)
ValueKind = VK_RValue;
// - variables
} else if (isa<VarDecl>(VD)) {
if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
Type = RefTy->getPointeeType();
} else if (Type->isFunctionType()) {
S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
<< VD << E->getSourceRange();
return ExprError();
}
// - nothing else
} else {
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
<< VD << E->getSourceRange();
return ExprError();
}
// Modifying the declaration like this is friendly to IR-gen but
// also really dangerous.
VD->setType(DestType);
E->setType(Type);
E->setValueKind(ValueKind);
return E;
}
/// Check a cast of an unknown-any type. We intentionally only
/// trigger this for C-style casts.
ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path) {
// The type we're casting to must be either void or complete.
if (!CastType->isVoidType() &&
RequireCompleteType(TypeRange.getBegin(), CastType,
diag::err_typecheck_cast_to_incomplete))
return ExprError();
// Rewrite the casted expression from scratch.
ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
if (!result.isUsable()) return ExprError();
CastExpr = result.get();
VK = CastExpr->getValueKind();
CastKind = CK_NoOp;
return CastExpr;
}
ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
}
ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
Expr *arg, QualType ¶mType) {
// If the syntactic form of the argument is not an explicit cast of
// any sort, just do default argument promotion.
ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
if (!castArg) {
ExprResult result = DefaultArgumentPromotion(arg);
if (result.isInvalid()) return ExprError();
paramType = result.get()->getType();
return result;
}
// Otherwise, use the type that was written in the explicit cast.
assert(!arg->hasPlaceholderType());
paramType = castArg->getTypeAsWritten();
// Copy-initialize a parameter of that type.
InitializedEntity entity =
InitializedEntity::InitializeParameter(Context, paramType,
/*consumed*/ false);
return PerformCopyInitialization(entity, callLoc, arg);
}
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
Expr *orig = E;
unsigned diagID = diag::err_uncasted_use_of_unknown_any;
while (true) {
E = E->IgnoreParenImpCasts();
if (CallExpr *call = dyn_cast<CallExpr>(E)) {
E = call->getCallee();
diagID = diag::err_uncasted_call_of_unknown_any;
} else {
break;
}
}
SourceLocation loc;
NamedDecl *d;
if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
loc = ref->getLocation();
d = ref->getDecl();
} else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
loc = mem->getMemberLoc();
d = mem->getMemberDecl();
} else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
diagID = diag::err_uncasted_call_of_unknown_any;
loc = msg->getSelectorStartLoc();
d = msg->getMethodDecl();
if (!d) {
S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
<< static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
<< orig->getSourceRange();
return ExprError();
}
} else {
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
<< E->getSourceRange();
return ExprError();
}
S.Diag(loc, diagID) << d << orig->getSourceRange();
// Never recoverable.
return ExprError();
}
/// Check for operands with placeholder types and complain if found.
/// Returns true if there was an error and no recovery was possible.
ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
if (!getLangOpts().CPlusPlus) {
// C cannot handle TypoExpr nodes on either side of a binop because it
// doesn't handle dependent types properly, so make sure any TypoExprs have
// been dealt with before checking the operands.
ExprResult Result = CorrectDelayedTyposInExpr(E);
if (!Result.isUsable()) return ExprError();
E = Result.get();
}
const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
if (!placeholderType) return E;
switch (placeholderType->getKind()) {
// Overloaded expressions.
case BuiltinType::Overload: {
// Try to resolve a single function template specialization.
// This is obligatory.
ExprResult Result = E;
if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
return Result;
// No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
// leaves Result unchanged on failure.
Result = E;
if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
return Result;
// If that failed, try to recover with a call.
tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
/*complain*/ true);
return Result;
}
// Bound member functions.
case BuiltinType::BoundMember: {
ExprResult result = E;
const Expr *BME = E->IgnoreParens();
PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
// Try to give a nicer diagnostic if it is a bound member that we recognize.
if (isa<CXXPseudoDestructorExpr>(BME)) {
PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
} else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
if (ME->getMemberNameInfo().getName().getNameKind() ==
DeclarationName::CXXDestructorName)
PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
}
tryToRecoverWithCall(result, PD,
/*complain*/ true);
return result;
}
// ARC unbridged casts.
case BuiltinType::ARCUnbridgedCast: {
Expr *realCast = stripARCUnbridgedCast(E);
diagnoseARCUnbridgedCast(realCast);
return realCast;
}
// Expressions of unknown type.
case BuiltinType::UnknownAny:
return diagnoseUnknownAnyExpr(*this, E);
// Pseudo-objects.
case BuiltinType::PseudoObject:
return checkPseudoObjectRValue(E);
case BuiltinType::BuiltinFn: {
// Accept __noop without parens by implicitly converting it to a call expr.
auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
if (DRE) {
auto *FD = cast<FunctionDecl>(DRE->getDecl());
if (FD->getBuiltinID() == Builtin::BI__noop) {
E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
CK_BuiltinFnToFnPtr).get();
return new (Context) CallExpr(Context, E, None, Context.IntTy,
VK_RValue, SourceLocation());
}
}
Diag(E->getLocStart(), diag::err_builtin_fn_use);
return ExprError();
}
// Expressions of unknown type.
case BuiltinType::OMPArraySection:
Diag(E->getLocStart(), diag::err_omp_array_section_use);
return ExprError();
// Everything else should be impossible.
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
case BuiltinType::Id:
#include "clang/Basic/OpenCLImageTypes.def"
#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
#define PLACEHOLDER_TYPE(Id, SingletonId)
#include "clang/AST/BuiltinTypes.def"
break;
}
llvm_unreachable("invalid placeholder type!");
}
bool Sema::CheckCaseExpression(Expr *E) {
if (E->isTypeDependent())
return true;
if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
return E->getType()->isIntegralOrEnumerationType();
return false;
}
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult
Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!");
QualType BoolT = Context.ObjCBuiltinBoolTy;
if (!Context.getBOOLDecl()) {
LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Sema::LookupOrdinaryName);
if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
NamedDecl *ND = Result.getFoundDecl();
if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
Context.setBOOLDecl(TD);
}
}
if (Context.getBOOLDecl())
BoolT = Context.getBOOLType();
return new (Context)
ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
}
ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
SourceLocation RParen) {
StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
[&](const AvailabilitySpec &Spec) {
return Spec.getPlatform() == Platform;
});
VersionTuple Version;
if (Spec != AvailSpecs.end())
Version = Spec->getVersion();
return new (Context)
ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
}
| [
"frankyroeder@web.de"
] | frankyroeder@web.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.