diff
stringlengths 41
2.03M
| msg
stringlengths 1
1.5k
⌀ | repo
stringlengths 5
40
| sha
stringlengths 40
40
| time
stringlengths 20
20
|
---|---|---|---|---|
mmm a / src / engine / threaded_engine_perdevice . cc <nl> ppp b / src / engine / threaded_engine_perdevice . cc <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> # ifndef _WIN32 <nl> pthread_atfork ( <nl> [ ] ( ) { <nl> - Engine : : Get ( ) - > WaitForAll ( ) ; <nl> Engine : : Get ( ) - > Stop ( ) ; <nl> } , <nl> [ ] ( ) { <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> # endif <nl> } <nl> ~ ThreadedEnginePerDevice ( ) noexcept ( false ) { <nl> - this - > Stop ( ) ; <nl> + this - > StopNoWait ( ) ; <nl> } <nl> <nl> - void Stop ( ) override { <nl> + void StopNoWait ( ) { <nl> SignalQueuesForKill ( ) ; <nl> gpu_normal_workers_ . Clear ( ) ; <nl> gpu_copy_workers_ . Clear ( ) ; <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> cpu_priority_worker_ . reset ( nullptr ) ; <nl> } <nl> <nl> + void Stop ( ) override { <nl> + if ( is_worker_ ) return ; <nl> + WaitForAll ( ) ; <nl> + StopNoWait ( ) ; <nl> + } <nl> + <nl> void Start ( ) override { <nl> + if ( is_worker_ ) return ; <nl> gpu_worker_nthreads_ = common : : GetNumThreadPerGPU ( ) ; <nl> cpu_worker_nthreads_ = dmlc : : GetEnv ( " MXNET_CPU_WORKER_NTHREADS " , 1 ) ; <nl> / / create CPU task <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> ~ ThreadWorkerBlock ( ) noexcept ( false ) { } <nl> } ; <nl> <nl> + / * ! \ brief whether this is a worker thread . * / <nl> + static MX_THREAD_LOCAL bool is_worker_ ; <nl> / * ! \ brief number of concurrent thread cpu worker uses * / <nl> int cpu_worker_nthreads_ ; <nl> / * ! \ brief number of concurrent thread each gpu worker uses * / <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> bool is_copy_worker , <nl> ThreadWorkerBlock < type > * block , <nl> std : : shared_ptr < ThreadPool : : SimpleEvent > ready_event ) { <nl> + this - > is_worker_ = true ; <nl> # if MXNET_USE_CUDA <nl> mshadow : : Stream < gpu > * stream ; <nl> do { <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> template < dmlc : : ConcurrentQueueType type > <nl> inline void CPUWorker ( Context ctx , <nl> ThreadWorkerBlock < type > * block ) { <nl> + this - > is_worker_ = true ; <nl> auto * task_queue = & ( block - > task_queue ) ; <nl> RunContext run_ctx { ctx , nullptr } ; <nl> / / execute task <nl> class ThreadedEnginePerDevice : public ThreadedEngine { <nl> Engine * CreateThreadedEnginePerDevice ( ) { <nl> return new ThreadedEnginePerDevice ( ) ; <nl> } <nl> + <nl> + MX_THREAD_LOCAL bool ThreadedEnginePerDevice : : is_worker_ = false ; <nl> + <nl> } / / namespace engine <nl> } / / namespace mxnet <nl> | Fix weird hang bug due to cuInit sometimes calls fork ( ) | apache/incubator-mxnet | 3953e79ad204a9a1a170dc83f97a27d0410b2a64 | 2017-11-23T20:53:55Z |
deleted file mode 100644 <nl> index f1f3302310c . . 00000000000 <nl> mmm a / dbms / include / DB / DataStreams / OriginalColumnNameSubstitutorBlockInputStream . h <nl> ppp / dev / null <nl> <nl> - # pragma once <nl> - <nl> - # include < Poco / SharedPtr . h > <nl> - <nl> - # include < DB / Interpreters / Expression . h > <nl> - # include < DB / DataStreams / IProfilingBlockInputStream . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - using Poco : : SharedPtr ; <nl> - <nl> - <nl> - / * * Подставляет в Block оригинальные имена столбцов до их переписывания при sign rewrite . <nl> - * <nl> - * При распределенной обработке запроса sign rewrite осуществляется на удаленных серверах , <nl> - * а Projection осуществляется на локальном сервере . Поэтому локальный сервер не знает <nl> - * о новых именах столбцов , которые получились после sign rewrite и будет искать в блоке <nl> - * оригинальные имена . <nl> - * / <nl> - class OriginalColumnNameSubstitutorBlockInputStream : public IProfilingBlockInputStream <nl> - { <nl> - public : <nl> - OriginalColumnNameSubstitutorBlockInputStream ( <nl> - BlockInputStreamPtr input_ , <nl> - ExpressionPtr expression_ ) <nl> - : expression ( expression_ ) <nl> - { <nl> - children . push_back ( input_ ) ; <nl> - } <nl> - <nl> - String getName ( ) const { return " OriginalColumnNameSubstitutorBlockInputStream " ; } <nl> - <nl> - String getID ( ) const <nl> - { <nl> - std : : stringstream res ; <nl> - res < < " OriginalColumnNameSubstitutor ( " < < children . back ( ) - > getID ( ) < < " ) " ; <nl> - return res . str ( ) ; <nl> - } <nl> - <nl> - protected : <nl> - Block readImpl ( ) <nl> - { <nl> - Block res = children . back ( ) - > read ( ) ; <nl> - if ( ! res ) <nl> - return res ; <nl> - <nl> - return expression - > substituteOriginalColumnNames ( res ) ; <nl> - } <nl> - <nl> - private : <nl> - ExpressionPtr expression ; <nl> - } ; <nl> - <nl> - } <nl> mmm a / dbms / include / DB / Interpreters / Expression . h <nl> ppp b / dbms / include / DB / Interpreters / Expression . h <nl> class Expression : private boost : : noncopyable <nl> / * * Пометить то , что должно быть вычислено до применения операции arrayJoin . <nl> * / <nl> void markBeforeArrayJoin ( unsigned part_id ) ; <nl> - <nl> - / * * Заменить названия столбцов в блоке на их оригиналы до sign rewrite <nl> - * / <nl> - Block substituteOriginalColumnNames ( Block & block ) ; <nl> <nl> private : <nl> ASTPtr ast ; <nl> class Expression : private boost : : noncopyable <nl> bool getArrayJoinInfoImpl ( ASTPtr ast , String & column_name ) ; <nl> <nl> void markBeforeArrayJoinImpl ( ASTPtr ast , unsigned part_id , bool below = false ) ; <nl> - <nl> - void substituteOriginalColumnNamesImpl ( ASTPtr ast , Block & src , Block & dst ) ; <nl> <nl> typedef std : : set < std : : string > NeedColumns ; <nl> <nl> mmm a / dbms / include / DB / Interpreters / InterpreterSelectQuery . h <nl> ppp b / dbms / include / DB / Interpreters / InterpreterSelectQuery . h <nl> class InterpreterSelectQuery <nl> void executePreLimit ( BlockInputStreams & streams , ExpressionPtr & expression ) ; <nl> void executeUnion ( BlockInputStreams & streams , ExpressionPtr & expression ) ; <nl> void executeLimit ( BlockInputStreams & streams , ExpressionPtr & expression ) ; <nl> - void executeOriginalColumnNameSubstitution ( BlockInputStreams & streams , ExpressionPtr & expression ) ; <nl> <nl> <nl> ASTPtr query_ptr ; <nl> mmm a / dbms / include / DB / Parsers / ASTFunction . h <nl> ppp b / dbms / include / DB / Parsers / ASTFunction . h <nl> class ASTFunction : public IAST <nl> ASTPtr parameters ; <nl> / / / алиас , если есть <nl> String alias ; <nl> - / / / оригинальное значение getColumnName ( ) для функции , которую переписали этой функцией по rewrite правилу <nl> - String original_column_name ; <nl> <nl> / / / сама функция <nl> FunctionPtr function ; <nl> mmm a / dbms / src / Interpreters / Expression . cpp <nl> ppp b / dbms / src / Interpreters / Expression . cpp <nl> ASTPtr Expression : : rewriteCount ( const ASTFunction * node ) <nl> ASTPtr sum_node = p_sum ; <nl> sum . name = " sum " ; <nl> sum . alias = node - > alias ; <nl> - sum . original_column_name = node - > getColumnName ( ) ; <nl> sum . arguments = exp_list_node ; <nl> sum . children . push_back ( exp_list_node ) ; <nl> sum . aggregate_function = context . getAggregateFunctionFactory ( ) . get ( sum . name , argument_types ) ; <nl> ASTPtr Expression : : rewriteSum ( const ASTFunction * node ) <nl> ASTPtr sum_node = p_sum ; <nl> sum . name = " sum " ; <nl> sum . alias = node - > alias ; <nl> - sum . original_column_name = node - > getColumnName ( ) ; <nl> sum . arguments = exp_list_node ; <nl> sum . children . push_back ( exp_list_node ) ; <nl> sum . aggregate_function = context . getAggregateFunctionFactory ( ) . get ( sum . name , argument_types ) ; <nl> ASTPtr Expression : : rewriteAvg ( const ASTFunction * node ) <nl> ASTExpressionList & div_exp_list = * p_div_exp_list ; <nl> ASTPtr div_exp_list_node = p_div_exp_list ; <nl> div_exp_list . children . push_back ( rewriteSum ( node ) ) ; <nl> - div_exp_list . children . push_back ( rewriteCount ( node ) ) ; <nl> + div_exp_list . children . push_back ( rewriteCount ( node ) ) ; <nl> <nl> / / / sum ( Sign * x ) / sum ( Sign ) <nl> ASTFunction * p_div = new ASTFunction ; <nl> ASTPtr Expression : : rewriteAvg ( const ASTFunction * node ) <nl> ASTPtr div_node = p_div ; <nl> div . name = " divide " ; <nl> div . alias = node - > alias ; <nl> - div . original_column_name = node - > getColumnName ( ) ; <nl> div . function = context . getFunctionFactory ( ) . get ( div . name , context ) ; <nl> div . arguments = div_exp_list_node ; <nl> div . children . push_back ( div_exp_list_node ) ; <nl> void Expression : : addSemantic ( ASTPtr & ast ) <nl> MapOfASTs tmp_map ; <nl> if ( needSignRewrite ( ) ) <nl> sign_column_name = getSignColumnName ( ) ; <nl> - addSemanticImpl ( ast , tmp_map , tmp_set ) ; <nl> + addSemanticImpl ( ast , tmp_map , tmp_set ) ; <nl> } <nl> <nl> <nl> void Expression : : resolveScalarSubqueriesImpl ( ASTPtr & ast , size_t subquery_depth <nl> } <nl> } <nl> <nl> - <nl> - Block Expression : : substituteOriginalColumnNames ( Block & block ) <nl> - { <nl> - Block res ; <nl> - substituteOriginalColumnNamesImpl ( ast , block , res ) ; <nl> - return res ; <nl> - } <nl> - <nl> - <nl> - void Expression : : substituteOriginalColumnNamesImpl ( ASTPtr ast , Block & src , Block & dst ) <nl> - { <nl> - / / / Обход в глубину , который не заходит внутрь функций и подзапросов . <nl> - if ( ASTIdentifier * ident = dynamic_cast < ASTIdentifier * > ( & * ast ) ) <nl> - { <nl> - if ( ident - > kind = = ASTIdentifier : : Column ) <nl> - { <nl> - dst . insert ( src . getByName ( ast - > getColumnName ( ) ) ) ; <nl> - } <nl> - } <nl> - else if ( dynamic_cast < ASTLiteral * > ( & * ast ) ) <nl> - { <nl> - dst . insert ( src . getByName ( ast - > getColumnName ( ) ) ) ; <nl> - } <nl> - else if ( ASTFunction * func = dynamic_cast < ASTFunction * > ( & * ast ) ) <nl> - { <nl> - ColumnWithNameAndType col = src . getByName ( ast - > getColumnName ( ) ) ; <nl> - if ( ! func - > original_column_name . empty ( ) ) <nl> - col . name = func - > original_column_name ; <nl> - dst . insert ( col ) ; <nl> - } <nl> - else <nl> - for ( ASTs : : iterator it = ast - > children . begin ( ) ; it ! = ast - > children . end ( ) ; + + it ) <nl> - if ( ! dynamic_cast < ASTSelectQuery * > ( & * * it ) ) <nl> - substituteOriginalColumnNamesImpl ( * it , src , dst ) ; <nl> - } <nl> - <nl> - <nl> } <nl> mmm a / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> <nl> # include < DB / DataStreams / ArrayJoiningBlockInputStream . h > <nl> # include < DB / DataStreams / NullBlockInputStream . h > <nl> # include < DB / DataStreams / narrowBlockInputStreams . h > <nl> - # include < DB / DataStreams / OriginalColumnNameSubstitutorBlockInputStream . h > <nl> # include < DB / DataStreams / copyData . h > <nl> <nl> # include < DB / Parsers / ASTSelectQuery . h > <nl> BlockInputStreamPtr InterpreterSelectQuery : : execute ( ) <nl> <nl> if ( need_aggregate ) <nl> executeAggregation ( streams , expression ) ; <nl> - <nl> - / / / Подставим оригинальные имена столбцов , если запрос шел из distributed таблицы <nl> - if ( settings . sign_rewrite & & to_stage = = QueryProcessingStage : : WithMergeableState ) <nl> - executeOriginalColumnNameSubstitution ( streams , expression ) ; <nl> } <nl> else if ( from_stage < = QueryProcessingStage : : WithMergeableState & & to_stage > QueryProcessingStage : : WithMergeableState ) <nl> { <nl> BlockInputStreamPtr InterpreterSelectQuery : : executeAndFormat ( WriteBuffer & buf ) <nl> } <nl> <nl> <nl> - void InterpreterSelectQuery : : executeOriginalColumnNameSubstitution ( BlockInputStreams & streams , ExpressionPtr & expression ) <nl> - { <nl> - for ( BlockInputStreams : : iterator it = streams . begin ( ) ; it ! = streams . end ( ) ; + + it ) <nl> - { <nl> - BlockInputStreamPtr & stream = * it ; <nl> - stream = new OriginalColumnNameSubstitutorBlockInputStream ( stream , expression ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> void InterpreterSelectQuery : : setPartID ( ASTPtr ast , unsigned part_id ) <nl> { <nl> ast - > part_id | = part_id ; <nl> | rolled back to revision 31455 [ # CONV - 6778 ] | ClickHouse/ClickHouse | 066f9ffa7c8781c30cb688aecccbe55d17afc63e | 2013-05-08T09:58:31Z |
mmm a / PRESUBMIT . py <nl> ppp b / PRESUBMIT . py <nl> def _CommonChecks ( input_api , output_api ) : <nl> _CheckNoInlineHeaderIncludesInNormalHeaders ( input_api , output_api ) ) <nl> results . extend ( _CheckJSONFiles ( input_api , output_api ) ) <nl> results . extend ( _CheckMacroUndefs ( input_api , output_api ) ) <nl> + results . extend ( _CheckNoexceptAnnotations ( input_api , output_api ) ) <nl> results . extend ( input_api . RunTests ( <nl> input_api . canned_checks . CheckVPythonSpec ( input_api , output_api ) ) ) <nl> return results <nl> def TouchesMacros ( f ) : <nl> return [ ] <nl> <nl> <nl> + def _CheckNoexceptAnnotations ( input_api , output_api ) : <nl> + " " " <nl> + Checks that all user - defined constructors and assignment operators are marked <nl> + V8_NOEXCEPT . <nl> + <nl> + This is required for standard containers to pick the right constructors . Our <nl> + macros ( like MOVE_ONLY_WITH_DEFAULT_CONSTRUCTORS ) add this automatically . <nl> + Omitting it at some places can result in weird compiler errors if this is <nl> + mixed with other classes that have the annotation . <nl> + <nl> + TODO ( clemensh ) : This check should eventually be enabled for all files via <nl> + tools / presubmit . py ( https : / / crbug . com / v8 / 8616 ) . <nl> + " " " <nl> + <nl> + # matches any class name . <nl> + class_name = r ' \ b ( [ A - Z ] [ A - Za - z0 - 9_ ] * ) ( ? : : : \ 1 ) ? ' <nl> + # initial class name is potentially followed by this to declare an assignment <nl> + # operator . <nl> + potential_assignment = r ' ( ? : & \ s + operator = ) ? \ s * ' <nl> + # matches an argument list that contains only a reference to a class named <nl> + # like the first capture group , potentially const . <nl> + single_class_ref_arg = r ' \ ( ( ? : const \ s + ) ? \ 1 ( ? : : : \ 1 ) ? & & ? [ ^ , ; ) ] * \ ) ' <nl> + # matches anything but a sequence of whitespaces followed by V8_NOEXCEPT . <nl> + not_followed_by_noexcept = r ' ( ? ! \ s + V8_NOEXCEPT \ b ) ' <nl> + full_pattern = r ' ^ . * ? ' + class_name + potential_assignment + \ <nl> + single_class_ref_arg + not_followed_by_noexcept + ' . * ? $ ' <nl> + regexp = input_api . re . compile ( full_pattern , re . MULTILINE ) <nl> + <nl> + errors = [ ] <nl> + for f in input_api . AffectedFiles ( include_deletes = False ) : <nl> + with open ( f . LocalPath ( ) ) as fh : <nl> + for match in re . finditer ( regexp , fh . read ( ) ) : <nl> + errors . append ( match . group ( ) . strip ( ) ) <nl> + <nl> + if errors : <nl> + return [ output_api . PresubmitPromptOrNotify ( <nl> + ' Copy constructors , move constructors , copy assignment operators and ' <nl> + ' move assignment operators should be marked V8_NOEXCEPT . \ n ' <nl> + ' Please report false positives on https : / / crbug . com / v8 / 8616 . ' , <nl> + errors ) ] <nl> + return [ ] <nl> + <nl> + <nl> def CheckChangeOnUpload ( input_api , output_api ) : <nl> results = [ ] <nl> results . extend ( _CommonChecks ( input_api , output_api ) ) <nl> | [ presubmit ] Check for proper V8_NOEXCEPT annotations | v8/v8 | 66451a6e02a107628f29462cfecf33215896a1d0 | 2018-12-20T13:55:39Z |
mmm a / test / functional / p2p_segwit . py <nl> ppp b / test / functional / p2p_segwit . py <nl> def test_segwit_versions ( self ) : <nl> temp_utxo . pop ( ) # last entry in temp_utxo was the output we just spent <nl> temp_utxo . append ( UTXO ( tx2 . sha256 , 0 , tx2 . vout [ 0 ] . nValue ) ) <nl> <nl> - # Spend everything in temp_utxo back to an OP_TRUE output . <nl> + # Spend everything in temp_utxo into an segwit v1 output . <nl> tx3 = CTransaction ( ) <nl> total_value = 0 <nl> for i in temp_utxo : <nl> def test_segwit_versions ( self ) : <nl> tx3 . wit . vtxinwit . append ( CTxInWitness ( ) ) <nl> total_value + = i . nValue <nl> tx3 . wit . vtxinwit [ - 1 ] . scriptWitness . stack = [ witness_program ] <nl> - tx3 . vout . append ( CTxOut ( total_value - 1000 , CScript ( [ OP_TRUE ] ) ) ) <nl> + tx3 . vout . append ( CTxOut ( total_value - 1000 , script_pubkey ) ) <nl> tx3 . rehash ( ) <nl> + <nl> + # First we test this transaction against fRequireStandard = true node <nl> + # making sure the txid is added to the reject filter <nl> + self . std_node . announce_tx_and_wait_for_getdata ( tx3 ) <nl> + test_transaction_acceptance ( self . nodes [ 1 ] , self . std_node , tx3 , with_witness = True , accepted = False , reason = " bad - txns - nonstandard - inputs " ) <nl> + # Now the node will no longer ask for getdata of this transaction when advertised by same txid <nl> + self . std_node . announce_tx_and_wait_for_getdata ( tx3 , timeout = 5 , success = False ) <nl> + <nl> # Spending a higher version witness output is not allowed by policy , <nl> # even with fRequireStandard = false . <nl> test_transaction_acceptance ( self . nodes [ 0 ] , self . test_node , tx3 , with_witness = True , accepted = False , reason = " reserved for soft - fork upgrades " ) <nl> | test addition of unknown segwit spends to txid reject filter | bitcoin/bitcoin | 9f88ded82b2898ca63d44c08072f1ba52f0e18d7 | 2020-08-04T17:29:40Z |
mmm a / python / mxnet / module / executor_group . py <nl> ppp b / python / mxnet / module / executor_group . py <nl> def update_metric ( self , eval_metric , labels ) : <nl> if islice . stop > valid_stop : <nl> islice = slice ( islice . start , valid_stop ) <nl> oslice = slice ( 0 , islice . stop - islice . start ) <nl> - for label , laxis , output , oaxis in \ <nl> - zip ( labels , self . label_layouts , texec . outputs , self . output_layouts ) : <nl> + for label , laxis in zip ( labels , self . label_layouts ) : <nl> labels_slice . append ( _slice_axis ( label , laxis , islice ) ) <nl> + for output , oaxis in zip ( texec . outputs , self . output_layouts ) : <nl> outputs_slice . append ( _slice_axis ( output , oaxis , oslice ) ) <nl> labels_ = OrderedDict ( zip ( self . label_names , labels_slice ) ) <nl> preds = OrderedDict ( zip ( self . output_names , outputs_slice ) ) <nl> | Update executor_group . py ( ) | apache/incubator-mxnet | 4aaefa04b1329e81c28cfa3ea4376e1a7e169611 | 2017-09-23T18:36:33Z |
mmm a / python / taichi / main . py <nl> ppp b / python / taichi / main . py <nl> def main ( ) : <nl> " ti statement [ statement ] | - > Execute a single statement ( with taichi imported as tc \ n " <nl> " ti [ script . py ] | - > Run script \ n " <nl> " ti doc | - > Build documentation \ n " <nl> + " ti merge | - > Merge images in folders horizontally \ n " <nl> " ti debug [ script . py ] | - > Debug script \ n " ) <nl> exit ( - 1 ) <nl> mode = sys . argv [ 1 ] <nl> def main ( ) : <nl> shutil . move ( fn , tmp_fn ) <nl> command = r ' sed - r " s / \ x1B \ [ ( [ 0 - 9 ] { 1 , 2 } ( ; [ 0 - 9 ] { 1 , 2 } ) ? ) ? [ m | K ] / / g " ' <nl> os . system ( ' { } { } > { } ' . format ( command , tmp_fn , fn ) ) <nl> + elif mode = = " merge " : <nl> + import cv2 # TODO : remove this dependency <nl> + import numpy as np <nl> + folders = sys . argv [ 2 : ] <nl> + os . makedirs ( ' merged ' , exist_ok = True ) <nl> + for fn in sorted ( os . listdir ( folders [ 0 ] ) ) : <nl> + imgs = [ ] <nl> + for fld in folders : <nl> + img = cv2 . imread ( os . path . join ( fld , fn ) ) <nl> + imgs . append ( img ) <nl> + img = np . hstack ( imgs ) <nl> + cv2 . imwrite ( os . path . join ( ' merged ' , fn ) , img ) <nl> else : <nl> print ( " Unknown command ' { } ' " . format ( mode ) ) <nl> exit ( - 1 ) <nl> | merge image util | taichi-dev/taichi | 11e366cebc148850c01cdcf22a61fee7b7aa2215 | 2018-11-01T16:37:29Z |
new file mode 100644 <nl> index 00000000000 . . 258e8dd41cf <nl> mmm / dev / null <nl> ppp b / samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / src / Model . cpp <nl> <nl> + / * <nl> + * Model . cpp <nl> + * <nl> + * Created on : Apr 9 , 2014 <nl> + * Author : edgar <nl> + * / <nl> + <nl> + # include " Model . h " <nl> + # include " CsvWriter . h " <nl> + <nl> + Model : : Model ( ) : list_points2d_in_ ( 0 ) , list_points2d_out_ ( 0 ) , list_points3d_in_ ( 0 ) <nl> + { <nl> + n_correspondences_ = 0 ; <nl> + } <nl> + <nl> + Model : : ~ Model ( ) <nl> + { <nl> + / / TODO Auto - generated destructor stub <nl> + } <nl> + <nl> + void Model : : add_correspondence ( const cv : : Point2f & point2d , const cv : : Point3f & point3d ) <nl> + { <nl> + list_points2d_in_ . push_back ( point2d ) ; <nl> + list_points3d_in_ . push_back ( point3d ) ; <nl> + n_correspondences_ + + ; <nl> + } <nl> + <nl> + void Model : : add_outlier ( const cv : : Point2f & point2d ) <nl> + { <nl> + list_points2d_out_ . push_back ( point2d ) ; <nl> + } <nl> + <nl> + void Model : : add_descriptor ( const cv : : Mat & descriptor ) <nl> + { <nl> + descriptors_ . push_back ( descriptor ) ; <nl> + } <nl> + <nl> + void Model : : add_keypoint ( const cv : : KeyPoint & kp ) <nl> + { <nl> + list_keypoints_ . push_back ( kp ) ; <nl> + } <nl> + <nl> + <nl> + / * * Save a CSV file and fill the object mesh * / <nl> + void Model : : save ( const std : : string path ) <nl> + { <nl> + cv : : Mat points3dmatrix = cv : : Mat ( list_points3d_in_ ) ; <nl> + cv : : Mat points2dmatrix = cv : : Mat ( list_points2d_in_ ) ; <nl> + / / cv : : Mat keyPointmatrix = cv : : Mat ( list_keypoints_ ) ; <nl> + <nl> + cv : : FileStorage storage ( path , cv : : FileStorage : : WRITE ) ; <nl> + storage < < " points_3d " < < points3dmatrix ; <nl> + storage < < " points_2d " < < points2dmatrix ; <nl> + storage < < " keypoints " < < list_keypoints_ ; <nl> + storage < < " descriptors " < < descriptors_ ; <nl> + <nl> + storage . release ( ) ; <nl> + } <nl> + <nl> + / * * Load a YAML file using OpenCv functions * * / <nl> + void Model : : load ( const std : : string path ) <nl> + { <nl> + cv : : Mat points3d_mat ; <nl> + <nl> + cv : : FileStorage storage ( path , cv : : FileStorage : : READ ) ; <nl> + storage [ " points_3d " ] > > points3d_mat ; <nl> + storage [ " descriptors " ] > > descriptors_ ; <nl> + <nl> + points3d_mat . copyTo ( list_points3d_in_ ) ; <nl> + <nl> + storage . release ( ) ; <nl> + <nl> + } <nl> + <nl> + <nl> | Code tutorial | opencv/opencv | 38c2cc85219486c608038baed267e56a9c5983e2 | 2014-07-30T10:56:55Z |
mmm a / brightray / browser / inspectable_web_contents_impl . cc <nl> ppp b / brightray / browser / inspectable_web_contents_impl . cc <nl> void InspectableWebContentsImpl : : LoadCompleted ( ) { <nl> / / If the devtools can dock , " SetIsDocked " will be called by devtools itself . <nl> if ( ! can_dock_ ) <nl> SetIsDocked ( DispatchCallback ( ) , false ) ; <nl> - <nl> - if ( view_ - > GetDelegate ( ) ) <nl> - view_ - > GetDelegate ( ) - > DevToolsLoaded ( ) ; <nl> } <nl> <nl> void InspectableWebContentsImpl : : SetInspectedPageBounds ( const gfx : : Rect & rect ) { <nl> mmm a / brightray / browser / inspectable_web_contents_view_delegate . h <nl> ppp b / brightray / browser / inspectable_web_contents_view_delegate . h <nl> class InspectableWebContentsViewDelegate { <nl> virtual void DevToolsFocused ( ) { } <nl> virtual void DevToolsOpened ( ) { } <nl> virtual void DevToolsClosed ( ) { } <nl> - virtual void DevToolsLoaded ( ) { } <nl> <nl> / / Returns the icon of devtools window . <nl> virtual gfx : : ImageSkia GetDevToolsWindowIcon ( ) ; <nl> | Revert " Merge pull request from deepak1556 / devtools_extensions_load_patch " | electron/electron | 7e0918f95a0eb4f7ee8b7f739e6c4dfe4919b083 | 2016-05-12T13:27:54Z |
mmm a / xbmc / cores / VideoPlayer / DVDDemuxers / DVDDemuxFFmpeg . cpp <nl> ppp b / xbmc / cores / VideoPlayer / DVDDemuxers / DVDDemuxFFmpeg . cpp <nl> DemuxPacket * CDVDDemuxFFmpeg : : Read ( ) <nl> } <nl> if ( ! stream ) <nl> { <nl> - CLog : : Log ( LOGERROR , " CDVDDemuxFFmpeg : : AddStream - internal error , stream is null " ) ; <nl> CDVDDemuxUtils : : FreeDemuxPacket ( pPacket ) ; <nl> - return NULL ; <nl> + pPacket = CDVDDemuxUtils : : AllocateDemuxPacket ( 0 ) ; <nl> + return pPacket ; <nl> } <nl> <nl> pPacket - > iStreamId = stream - > uniqueId ; <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> <nl> switch ( pStream - > codecpar - > codec_type ) <nl> { <nl> - case AVMEDIA_TYPE_AUDIO : <nl> + case AVMEDIA_TYPE_AUDIO : <nl> { <nl> CDemuxStreamAudioFFmpeg * st = new CDemuxStreamAudioFFmpeg ( pStream ) ; <nl> stream = st ; <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> <nl> break ; <nl> } <nl> - case AVMEDIA_TYPE_VIDEO : <nl> + case AVMEDIA_TYPE_VIDEO : <nl> { <nl> CDemuxStreamVideoFFmpeg * st = new CDemuxStreamVideoFFmpeg ( pStream ) ; <nl> stream = st ; <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> <nl> break ; <nl> } <nl> - case AVMEDIA_TYPE_DATA : <nl> + case AVMEDIA_TYPE_DATA : <nl> { <nl> stream = new CDemuxStream ( ) ; <nl> stream - > type = STREAM_DATA ; <nl> break ; <nl> } <nl> - case AVMEDIA_TYPE_SUBTITLE : <nl> + case AVMEDIA_TYPE_SUBTITLE : <nl> { <nl> if ( pStream - > codecpar - > codec_id = = AV_CODEC_ID_DVB_TELETEXT & & CServiceBroker : : GetSettings ( ) . GetBool ( CSettings : : SETTING_VIDEOPLAYER_TELETEXTENABLED ) ) <nl> { <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> break ; <nl> } <nl> } <nl> - case AVMEDIA_TYPE_ATTACHMENT : <nl> + case AVMEDIA_TYPE_ATTACHMENT : <nl> { / / mkv attachments . Only bothering with fonts for now . <nl> - if ( pStream - > codecpar - > codec_id = = AV_CODEC_ID_TTF | | <nl> - pStream - > codecpar - > codec_id = = AV_CODEC_ID_OTF ) <nl> + if ( pStream - > codecpar - > codec_id = = AV_CODEC_ID_TTF | | <nl> + pStream - > codecpar - > codec_id = = AV_CODEC_ID_OTF ) <nl> { <nl> std : : string fileName = " special : / / temp / fonts / " ; <nl> XFILE : : CDirectory : : Create ( fileName ) ; <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> stream - > type = STREAM_NONE ; <nl> break ; <nl> } <nl> - default : <nl> + default : <nl> { <nl> - stream = new CDemuxStream ( ) ; <nl> - stream - > type = STREAM_NONE ; <nl> - break ; <nl> + CLog : : Log ( LOGDEBUG , " CDVDDemuxFFmpeg : : AddStream - discarding unknown stream with id : % d " , pStream - > index ) ; <nl> + pStream - > discard = AVDISCARD_ALL ; <nl> + return nullptr ; ; <nl> } <nl> } <nl> <nl> CDemuxStream * CDVDDemuxFFmpeg : : AddStream ( int streamIdx ) <nl> return stream ; <nl> } <nl> else <nl> - return NULL ; <nl> + return nullptr ; <nl> } <nl> <nl> / * * <nl> void CDVDDemuxFFmpeg : : AddStream ( int streamIdx , CDemuxStream * stream ) <nl> delete res . first - > second ; <nl> res . first - > second = stream ; <nl> } <nl> - if ( g_advancedSettings . m_logLevel > LOG_LEVEL_NORMAL ) <nl> - CLog : : Log ( LOGDEBUG , " CDVDDemuxFFmpeg : : AddStream ID : % d " , streamIdx ) ; <nl> + CLog : : Log ( LOGDEBUG , " CDVDDemuxFFmpeg : : AddStream ID : % d " , streamIdx ) ; <nl> } <nl> <nl> <nl> | VideoPlayer : demux ffmpeg - discard unknown streams | xbmc/xbmc | 0c2d35b762c4561055e75c4ad7b0c06984485ae7 | 2017-11-24T18:33:04Z |
mmm a / modules / gapi / samples / privacy_masking_camera . cpp <nl> ppp b / modules / gapi / samples / privacy_masking_camera . cpp <nl> const std : : string keys = <nl> " { input | | Path to the input video file } " <nl> " { platm | vehicle - license - plate - detection - barrier - 0106 . xml | Path to OpenVINO IE vehicle / plate detection model ( . xml ) } " <nl> " { platd | CPU | Target device for vehicle / plate detection model ( e . g . CPU , GPU , VPU , . . . ) } " <nl> - " { facem | face - detection - adas - 0001 . xml | Path to OpenVINO IE face detection model ( . xml ) } " <nl> + " { facem | face - detection - retail - 0005 . xml | Path to OpenVINO IE face detection model ( . xml ) } " <nl> " { faced | CPU | Target device for face detection model ( e . g . CPU , GPU , VPU , . . . ) } " <nl> " { trad | false | Run processing in a traditional ( non - pipelined ) way } " <nl> " { noshow | false | Don ' t display UI ( improves performance ) } " ; <nl> new file mode 100755 <nl> index 00000000000 . . fdb56912f0a <nl> mmm / dev / null <nl> ppp b / modules / gapi / scripts / measure_privacy_masking . py <nl> <nl> + # ! / usr / bin / env python3 <nl> + <nl> + import sys <nl> + import subprocess <nl> + import re <nl> + from enum import Enum <nl> + <nl> + # # Helper functions # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> + # # <nl> + def fmt_bool ( x ) : <nl> + return ( " true " if x else " false " ) <nl> + <nl> + def fmt_bin ( base , prec , model ) : <nl> + return " % s / % s / % s / % s . xml " % ( base , model , prec , model ) <nl> + <nl> + # # The script itself # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> + # # <nl> + if len ( sys . argv ) ! = 3 : <nl> + print ( " Usage : % s / path / to / input / video / path / to / models " % sys . argv [ 0 ] ) <nl> + exit ( 1 ) <nl> + <nl> + input_file_path = sys . argv [ 1 ] <nl> + intel_models_path = sys . argv [ 2 ] <nl> + <nl> + app = " bin / example_gapi_privacy_masking_camera " <nl> + intel_fd_model = " face - detection - retail - 0005 " <nl> + intel_lpd_model = " vehicle - license - plate - detection - barrier - 0106 " <nl> + output_file = " out_results . csv " <nl> + <nl> + tgts = [ ( " CPU " , " INT8 " ) <nl> + , ( " CPU " , " FP32 " ) <nl> + , ( " GPU " , " FP16 " ) <nl> + ] <nl> + <nl> + class Policy ( Enum ) : <nl> + Traditional = 1 <nl> + Streaming = 2 <nl> + <nl> + # From mode to cmd arg <nl> + mods = [ ( Policy . Traditional , True ) <nl> + , ( Policy . Streaming , False ) <nl> + ] <nl> + <nl> + class UI ( Enum ) : <nl> + With = 1 <nl> + Without = 2 <nl> + <nl> + # From mode to cmd arg <nl> + ui = [ ( UI . With , False ) <nl> + , ( UI . Without , True ) <nl> + ] <nl> + <nl> + fd_fmt_bin = lambda prec : fmt_bin ( intel_models_path , prec , intel_fd_model ) <nl> + lpd_fmt_bin = lambda prec : fmt_bin ( intel_models_path , prec , intel_lpd_model ) <nl> + <nl> + # Performance comparison table <nl> + table = { } <nl> + <nl> + # Collect the performance data <nl> + for m in mods : # Execution mode ( trad / stream ) <nl> + for u in ui : # UI mode ( on / off ) <nl> + for f in tgts : # FD model <nl> + for p in tgts : # LPD model <nl> + cmd = [ app <nl> + , ( " - - input = % s " % input_file_path ) # input file <nl> + , ( " - - faced = % s " % f [ 0 ] ) # FD device target <nl> + , ( " - - facem = % s " % fd_fmt_bin ( f [ 1 ] ) ) # FD model @ precision <nl> + , ( " - - platd = % s " % p [ 0 ] ) # LPD device target <nl> + , ( " - - platm = % s " % lpd_fmt_bin ( p [ 1 ] ) ) # LPD model @ precision <nl> + , ( " - - trad = % s " % fmt_bool ( m [ 1 ] ) ) # Execution policy <nl> + , ( " - - noshow = % s " % fmt_bool ( u [ 1 ] ) ) # UI mode ( show / no show ) <nl> + ] <nl> + out = str ( subprocess . check_output ( cmd ) ) <nl> + match = re . search ( ' Processed [ 0 - 9 ] + frames \ ( ( [ 0 - 9 ] + \ . [ 0 - 9 ] + ) FPS \ ) ' , out ) <nl> + fps = float ( match . group ( 1 ) ) <nl> + print ( cmd , fps , " FPS " ) <nl> + table [ m [ 0 ] , u [ 0 ] , f , p ] = fps <nl> + <nl> + # Write the performance summary <nl> + # Columns : all other components ( mode , ui ) <nl> + with open ( output_file , ' w ' ) as csv : <nl> + # CSV header <nl> + csv . write ( " FD , LPD , Serial ( UI ) , Serial ( no - UI ) , Streaming ( UI ) , Streaming ( no - UI ) , Effect ( UI ) , Effect ( no - UI ) \ n " ) <nl> + <nl> + for f in tgts : # FD model <nl> + for p in tgts : # LPD model <nl> + row = " % s / % s , % s / % s " % ( f [ 0 ] , f [ 1 ] , p [ 0 ] , p [ 1 ] ) # FD precision , LPD precision <nl> + row + = " , % f " % table [ Policy . Traditional , UI . With , f , p ] # Serial / UI <nl> + row + = " , % f " % table [ Policy . Traditional , UI . Without , f , p ] # Serial / no UI <nl> + row + = " , % f " % table [ Policy . Streaming , UI . With , f , p ] # Streaming / UI <nl> + row + = " , % f " % table [ Policy . Streaming , UI . Without , f , p ] # Streaming / no UI <nl> + <nl> + effect_ui = table [ Policy . Streaming , UI . With , f , p ] / table [ Policy . Traditional , UI . With , f , p ] <nl> + effect_noui = table [ Policy . Streaming , UI . Without , f , p ] / table [ Policy . Traditional , UI . Without , f , p ] <nl> + row + = " , % f , % f " % ( effect_ui , effect_noui ) <nl> + row + = " \ n " <nl> + csv . write ( row ) <nl> + <nl> + print ( " DONE : " , output_file ) <nl> | Merge pull request from dmatveev : dm / pmc_script | opencv/opencv | 0b454486cff341f7763c9c60241db03bfcc088a2 | 2020-07-11T19:11:03Z |
mmm a / fdbserver / KeyValueStoreMemory . actor . cpp <nl> ppp b / fdbserver / KeyValueStoreMemory . actor . cpp <nl> class KeyValueStoreMemory : public IKeyValueStore , NonCopyable { <nl> int64_t availableSize = std : : min ( getAvailableSize ( ) , diskQueueBytes . free / 4 - uncommittedBytes ) ; <nl> int64_t totalSize = std : : min ( memoryLimit , diskQueueBytes . total / 4 - uncommittedBytes ) ; <nl> <nl> - return StorageBytes ( std : : max ( ( int64_t ) 0 , availableSize ) , std : : max ( ( int64_t ) 0 , totalSize ) , diskQueueBytes . used , diskQueueBytes . available ) ; <nl> + return StorageBytes ( std : : max ( ( int64_t ) 0 , availableSize ) , std : : max ( ( int64_t ) 0 , totalSize ) , diskQueueBytes . used , <nl> + std : : max ( ( int64_t ) 0 , std : : min ( diskQueueBytes . available , availableSize ) ) ) ; <nl> } <nl> <nl> void semiCommit ( ) { <nl> | Available space should take into account both memory and disk | apple/foundationdb | b46ffb4cbc8f5dd6009af514399351ba970362bb | 2018-03-20T21:38:04Z |
mmm a / validation - test / stdlib / StringMemoryTest . swift <nl> ppp b / validation - test / stdlib / StringMemoryTest . swift <nl> func lowercase ( _ str : String ) - > String { <nl> <nl> @ inline ( never ) <nl> func runTest ( ) { <nl> - for _ in 0 . . < 10_0000 { <nl> + for _ in 0 . . < 15_0000 { <nl> if lookup ( " \ u { 1F1E7 } \ u { 1F1E7 } " , dict ) { <nl> print ( " Found ? ! " ) <nl> } <nl> runTest ( ) <nl> let firstRun = getMemoryUsage ( ) - baseUsage <nl> runTest ( ) <nl> runTest ( ) <nl> + runTest ( ) <nl> let secondRun = getMemoryUsage ( ) - baseUsage <nl> <nl> / / CHECK - NOT : Found ? ! <nl> print ( " Not found " ) <nl> / / CHECK : success <nl> / / CHECK - NOT : failure <nl> <nl> - / / We should not need 50MB for this . <nl> - if firstRun * 2 < secondRun { <nl> - print ( " failure - should not linearly increase " ) <nl> + if firstRun * 3 < secondRun & & firstRun > 10_000 { <nl> + print ( " failure - should not linearly increase firstRun : \ ( firstRun ) secondRun : \ ( secondRun ) " ) <nl> } else { <nl> - print ( " success " ) <nl> + print ( " success firstRun : \ ( firstRun ) secondRun : \ ( secondRun ) " ) <nl> } <nl> | Merge pull request from aschwaighofer / string_memory_test | apple/swift | 9605f1d1ae271843faee610387c3105d3d9b5ef7 | 2019-03-15T02:29:32Z |
mmm a / tensorflow / compiler / mlir / python / mlir . i <nl> ppp b / tensorflow / compiler / mlir / python / mlir . i <nl> string ExperimentalConvertSavedModelToMlir ( <nl> return MlirModuleToString ( * module_or . ConsumeValueOrDie ( ) , show_debug_info ) ; <nl> } <nl> <nl> - / / Load a SavedModel V1 and return a textual MLIR string corresponding to it . <nl> - / / <nl> - / / Args : <nl> - / / saved_model_path : File path from which to load the SavedModel . <nl> - / / tags : Tags to identify MetaGraphDef that need to be loaded . <nl> - / / <nl> - / / Returns : <nl> - / / A string of textual MLIR representing the raw imported SavedModel . <nl> - string ExperimentalConvertSavedModelV1ToMlir ( <nl> - const string & saved_model_path , <nl> - const string & tags , <nl> - bool show_debug_info , <nl> - TF_Status * status ) { <nl> - / / Load the saved model into a SavedModelBundle . <nl> - <nl> - std : : unordered_set < string > tag_set <nl> - = absl : : StrSplit ( tags , ' , ' , absl : : SkipEmpty ( ) ) ; <nl> - <nl> - tensorflow : : SavedModelBundle bundle ; <nl> - auto load_status = tensorflow : : LoadSavedModel ( <nl> - { } , { } , <nl> - saved_model_path , tag_set , & bundle ) ; <nl> - if ( ! load_status . ok ( ) ) { <nl> - Set_TF_Status_from_Status ( status , load_status ) ; <nl> - return " / / error " ; <nl> - } <nl> - <nl> - / / Convert the SavedModelBundle to an MLIR module . <nl> - <nl> - mlir : : MLIRContext context ; <nl> - auto module_or = ConvertSavedModelV1ToMlir ( bundle , & context ) ; <nl> - if ( ! module_or . status ( ) . ok ( ) ) { <nl> - Set_TF_Status_from_Status ( status , module_or . status ( ) ) ; <nl> - return " / / error " ; <nl> - } <nl> - <nl> - return MlirModuleToString ( * module_or . ConsumeValueOrDie ( ) , show_debug_info ) ; <nl> - } <nl> - <nl> <nl> string ExperimentalRunPassPipeline ( <nl> const string & mlir_txt , <nl> string ExperimentalRunPassPipeline ( <nl> % unignore tensorflow : : swig ; <nl> % unignore tensorflow : : swig : : ImportGraphDef ; <nl> % unignore tensorflow : : swig : : ExperimentalConvertSavedModelToMlir ; <nl> - % unignore tensorflow : : swig : : ExperimentalConvertSavedModelV1ToMlir ; <nl> % unignore tensorflow : : swig : : ExperimentalRunPassPipeline ; <nl> <nl> / / Wrap this function <nl> static string ExperimentalConvertSavedModelToMlir ( <nl> const string & exported_names , <nl> bool show_debug_info , <nl> TF_Status * status ) ; <nl> - static string ExperimentalConvertSavedModelV1ToMlir ( <nl> - const string & saved_model_path , <nl> - const string & tags , <nl> - bool show_debug_info , <nl> - TF_Status * status ) ; <nl> static string ExperimentalRunPassPipeline ( <nl> const string & mlir_txt , <nl> const string & pass_pipeline , <nl> def experimental_convert_saved_model_to_mlir ( saved_model_path , <nl> show_debug_info <nl> ) . decode ( ' utf - 8 ' ) ; <nl> <nl> - def experimental_convert_saved_model_v1_to_mlir ( saved_model_path , <nl> - tags , show_debug_info ) : <nl> - return ExperimentalConvertSavedModelV1ToMlir ( <nl> - str ( saved_model_path ) . encode ( ' utf - 8 ' ) , <nl> - str ( tags ) . encode ( ' utf - 8 ' ) , <nl> - show_debug_info <nl> - ) . decode ( ' utf - 8 ' ) ; <nl> - <nl> def experimental_run_pass_pipeline ( mlir_txt , pass_pipeline , show_debug_info ) : <nl> return ExperimentalRunPassPipeline ( <nl> mlir_txt . encode ( ' utf - 8 ' ) , <nl> mmm a / tensorflow / compiler / mlir / tensorflow / BUILD <nl> ppp b / tensorflow / compiler / mlir / tensorflow / BUILD <nl> cc_library ( <nl> " : tensorflow " , <nl> " : tensorflow_passes " , <nl> " / / tensorflow / cc / saved_model : bundle_v2 " , <nl> - " / / tensorflow / cc / saved_model : loader_lite " , <nl> " / / tensorflow / compiler / jit : shape_inference_helpers " , <nl> " / / tensorflow / compiler / mlir : op_or_arg_name_mapper " , <nl> " / / tensorflow / compiler / tf2xla : functionalize_control_flow " , <nl> " / / tensorflow / compiler / xla : status_macros " , <nl> " / / tensorflow / core : core_cpu " , <nl> " / / tensorflow / core : framework " , <nl> - " / / tensorflow / core : framework_internal " , <nl> " / / tensorflow / core : graph " , <nl> " / / tensorflow / core : lib " , <nl> " / / tensorflow / core : protos_all_cc " , <nl> - " / / tensorflow / core / grappler / utils : transitive_fanin " , <nl> " / / tensorflow / core / platform : types " , <nl> " / / tensorflow / stream_executor / lib " , <nl> " @ com_google_absl / / absl / algorithm : container " , <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / BUILD <nl> ppp b / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / BUILD <nl> py_library ( <nl> ] , <nl> ) <nl> <nl> - py_library ( <nl> - name = " common_v1 " , <nl> - srcs = [ " common_v1 . py " ] , <nl> - srcs_version = " PY2AND3 " , <nl> - deps = [ <nl> - " / / tensorflow : tensorflow_py " , <nl> - ] , <nl> - ) <nl> - <nl> filegroup ( <nl> name = " test_utilities " , <nl> testonly = True , <nl> filegroup ( <nl> # Drop trailing " . py " from all test file names . <nl> all_test_basenames = [ py [ : - 3 ] for py in glob ( <nl> [ " * . py " ] , <nl> - exclude = [ <nl> - " common . py " , <nl> - " common_v1 . py " , <nl> - ] , <nl> + exclude = [ " common . py " ] , <nl> ) ] <nl> <nl> # Instantiate all the tests . <nl> deleted file mode 100644 <nl> index 8fb8b4e6e2d83 . . 0000000000000 <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / basic_v1 . py <nl> ppp / dev / null <nl> <nl> - # Copyright 2019 The TensorFlow Authors . All Rights Reserved . <nl> - # <nl> - # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - # you may not use this file except in compliance with the License . <nl> - # You may obtain a copy of the License at <nl> - # <nl> - # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - # <nl> - # Unless required by applicable law or agreed to in writing , software <nl> - # distributed under the License is distributed on an " AS IS " BASIS , <nl> - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - # See the License for the specific language governing permissions and <nl> - # limitations under the License . <nl> - # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - <nl> - # RUN : % p / basic_v1 | FileCheck % s <nl> - <nl> - # pylint : disable = missing - docstring , line - too - long <nl> - from __future__ import absolute_import <nl> - from __future__ import division <nl> - from __future__ import print_function <nl> - <nl> - import tensorflow . compat . v1 as tf <nl> - from tensorflow . compiler . mlir . tensorflow . tests . tf_saved_model import common_v1 <nl> - <nl> - # CHECK : " tf_saved_model . global_tensor " ( ) { is_mutable , sym_name = " y " , type = tensor < 1x3xf32 > , value = { { . * } } : tensor < 1x3xf32 > } : ( ) - > ( ) <nl> - # CHECK : func @ basic ( [ [ ARG0 : % . * ] ] : tensor < 3x1xf32 > , <nl> - # CHECK - SAME : [ [ ARG1 : % . * ] ] : tensor < ! tf . resource < tensor < 1x3xf32 > > > { tf_saved_model . bound_input = @ y } ) - > tensor < 3x3xf32 > <nl> - # CHECK - NEXT : [ [ R0 : % . * ] ] = " tf . ReadVariableOp " ( [ [ ARG1 ] ] ) { { { . * } } } : ( tensor < ! tf . resource < tensor < 1x3xf32 > > > ) - > tensor < 1x3xf32 > <nl> - # CHECK - NEXT : [ [ R1 : % . * ] ] = " tf . MatMul " ( [ [ ARG0 ] ] , [ [ R0 ] ] ) { { { . * } } } : ( tensor < 3x1xf32 > , tensor < 1x3xf32 > ) - > tensor < 3x3xf32 > <nl> - # CHECK - NEXT : return [ [ R1 ] ] : tensor < 3x3xf32 > <nl> - <nl> - <nl> - def Test ( ) : <nl> - <nl> - # Default TF1 . x uses reference variables that are not supported by SavedModel <nl> - # v1 Importer . To use SavedModel V1 Importer , resource variables should be <nl> - # enabled . <nl> - tf . compat . v1 . enable_resource_variables ( ) <nl> - <nl> - tf . compat . v1 . disable_eager_execution ( ) <nl> - <nl> - x = tf . constant ( [ [ 1 . 0 ] , [ 1 . 0 ] , [ 1 . 0 ] ] ) <nl> - y = tf . compat . v1 . get_variable ( <nl> - name = ' y ' , <nl> - shape = ( 1 , 3 ) , <nl> - initializer = tf . random_normal_initializer ( ) , <nl> - trainable = True ) <nl> - r = tf . matmul ( x , y ) <nl> - <nl> - tensor_info_x = tf . compat . v1 . saved_model . utils . build_tensor_info ( x ) <nl> - tensor_info_r = tf . compat . v1 . saved_model . utils . build_tensor_info ( r ) <nl> - <nl> - return { <nl> - ' basic ' : <nl> - ( tf . compat . v1 . saved_model . signature_def_utils . build_signature_def ( <nl> - inputs = { ' x ' : tensor_info_x } , <nl> - outputs = { ' r ' : tensor_info_r } , <nl> - method_name = tf . saved_model . PREDICT_METHOD_NAME ) ) <nl> - } <nl> - <nl> - <nl> - if __name__ = = ' __main__ ' : <nl> - common_v1 . do_test ( Test ( ) ) <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / build_defs . bzl <nl> ppp b / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / build_defs . bzl <nl> def tf_saved_model_test ( name , data ) : <nl> srcs = [ name + " . py " ] , <nl> deps = [ <nl> " / / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model : common " , <nl> - " / / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model : common_v1 " , <nl> ] , <nl> ) <nl> <nl> deleted file mode 100644 <nl> index 35858d2b38a6b . . 0000000000000 <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / common_v1 . py <nl> ppp / dev / null <nl> <nl> - # Copyright 2019 The TensorFlow Authors . All Rights Reserved . <nl> - # <nl> - # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - # you may not use this file except in compliance with the License . <nl> - # You may obtain a copy of the License at <nl> - # <nl> - # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - # <nl> - # Unless required by applicable law or agreed to in writing , software <nl> - # distributed under the License is distributed on an " AS IS " BASIS , <nl> - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - # See the License for the specific language governing permissions and <nl> - # limitations under the License . <nl> - # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - " " " Serves as a common " main " function for all the SavedModel tests . <nl> - <nl> - There is a fair amount of setup needed to initialize tensorflow and get it <nl> - into a proper TF2 execution mode . This hides that boilerplate . <nl> - " " " <nl> - <nl> - from __future__ import absolute_import <nl> - from __future__ import division <nl> - from __future__ import print_function <nl> - <nl> - import tempfile <nl> - from absl import app <nl> - from absl import flags <nl> - from absl import logging <nl> - import tensorflow . compat . v1 as tf <nl> - <nl> - from tensorflow . python import pywrap_tensorflow <nl> - <nl> - # Use / tmp to make debugging the tests easier ( see README . md ) <nl> - flags . DEFINE_string ( ' save_model_path ' , ' ' , ' Path to save the model to . ' ) <nl> - FLAGS = flags . FLAGS <nl> - <nl> - <nl> - # This function needs to take a " create_module_fn " , as opposed to just the <nl> - # module itself , because the creation of the module has to be delayed until <nl> - # after absl and tensorflow have run various initialization steps . <nl> - def do_test ( signature_def_map , show_debug_info = False ) : <nl> - " " " Runs test . <nl> - <nl> - 1 . Performs absl and tf " main " - like initialization that must run before almost <nl> - anything else . <nl> - 2 . Converts signature_def_map to SavedModel V1 <nl> - 3 . Converts SavedModel V1 to MLIR <nl> - 4 . Prints the textual MLIR to stdout ( it is expected that the caller will have <nl> - FileCheck checks in its file to check this output ) . <nl> - <nl> - This is only for use by the MLIR SavedModel importer tests . <nl> - <nl> - Args : <nl> - signature_def_map : A map from string key to signature_def . The key will be <nl> - used as function name in the resulting MLIR . <nl> - show_debug_info : If true , shows debug locations in the resulting MLIR . <nl> - " " " <nl> - <nl> - # Make LOG ( ERROR ) in C + + code show up on the console . <nl> - # All ` Status ` passed around in the C + + API seem to eventually go into <nl> - # ` LOG ( ERROR ) ` , so this makes them print out by default . <nl> - logging . set_stderrthreshold ( ' error ' ) <nl> - <nl> - def app_main ( argv ) : <nl> - " " " Function passed to absl . app . run . " " " <nl> - if len ( argv ) > 1 : <nl> - raise app . UsageError ( ' Too many command - line arguments . ' ) <nl> - if FLAGS . save_model_path : <nl> - save_model_path = FLAGS . save_model_path <nl> - else : <nl> - save_model_path = tempfile . mktemp ( suffix = ' . saved_model ' ) <nl> - <nl> - sess = tf . Session ( ) <nl> - sess . run ( tf . initializers . global_variables ( ) ) <nl> - builder = tf . saved_model . builder . SavedModelBuilder ( save_model_path ) <nl> - builder . add_meta_graph_and_variables ( <nl> - sess , [ tf . saved_model . tag_constants . SERVING ] , <nl> - signature_def_map , <nl> - strip_default_attrs = True ) <nl> - builder . save ( ) <nl> - <nl> - logging . info ( ' Saved model to : % s ' , save_model_path ) <nl> - mlir = pywrap_tensorflow . experimental_convert_saved_model_v1_to_mlir ( <nl> - save_model_path , ' , ' . join ( [ tf . saved_model . tag_constants . SERVING ] ) , <nl> - show_debug_info ) <nl> - # We don ' t strictly need this , but it serves as a handy sanity check <nl> - # for that API , which is otherwise a bit annoying to test . <nl> - # The canonicalization shouldn ' t affect these tests in any way . <nl> - mlir = pywrap_tensorflow . experimental_run_pass_pipeline ( <nl> - mlir , ' tf - standard - pipeline ' , show_debug_info ) <nl> - print ( mlir ) <nl> - <nl> - app . run ( app_main ) <nl> deleted file mode 100644 <nl> index 6ba51c2a3254c . . 0000000000000 <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf_saved_model / shared_variable_v1 . py <nl> ppp / dev / null <nl> <nl> - # Copyright 2019 The TensorFlow Authors . All Rights Reserved . <nl> - # <nl> - # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - # you may not use this file except in compliance with the License . <nl> - # You may obtain a copy of the License at <nl> - # <nl> - # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - # <nl> - # Unless required by applicable law or agreed to in writing , software <nl> - # distributed under the License is distributed on an " AS IS " BASIS , <nl> - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - # See the License for the specific language governing permissions and <nl> - # limitations under the License . <nl> - # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - <nl> - # RUN : % p / shared_variable_v1 | FileCheck % s <nl> - <nl> - # pylint : disable = missing - docstring , line - too - long <nl> - from __future__ import absolute_import <nl> - from __future__ import division <nl> - from __future__ import print_function <nl> - <nl> - import tensorflow . compat . v1 as tf <nl> - from tensorflow . compiler . mlir . tensorflow . tests . tf_saved_model import common_v1 <nl> - <nl> - # CHECK : " tf_saved_model . global_tensor " ( ) { is_mutable , sym_name = " y " , type = tensor < 1x3xf32 > , value = { { . * } } : tensor < 1x3xf32 > } : ( ) - > ( ) <nl> - # CHECK : func { { @ . * } } ( [ [ ARG0 : % . * ] ] : tensor < 3x1xf32 > , <nl> - # CHECK - SAME : [ [ ARG1 : % . * ] ] : tensor < ! tf . resource < tensor < 1x3xf32 > > > { tf_saved_model . bound_input = @ y } ) - > tensor < 3x3xf32 > <nl> - <nl> - # CHECK : func { { @ . * } } ( [ [ ARG2 : % . * ] ] : tensor < 3x1xf32 > , <nl> - # CHECK - SAME : [ [ ARG3 : % . * ] ] : tensor < ! tf . resource < tensor < 1x3xf32 > > > { tf_saved_model . bound_input = @ y } ) - > tensor < 3x3xf32 > <nl> - <nl> - <nl> - def Test ( ) : <nl> - <nl> - # Default TF1 . x uses reference variables that are not supported by SavedModel <nl> - # v1 Importer . To use SavedModel V1 Importer , resource variables should be <nl> - # enabled . <nl> - tf . enable_resource_variables ( ) <nl> - <nl> - tf . compat . v1 . disable_eager_execution ( ) <nl> - <nl> - x = tf . constant ( [ [ 1 . 0 ] , [ 1 . 0 ] , [ 1 . 0 ] ] ) <nl> - y = tf . get_variable ( <nl> - name = ' y ' , <nl> - shape = ( 1 , 3 ) , <nl> - initializer = tf . random_normal_initializer ( ) , <nl> - trainable = True ) <nl> - r = tf . matmul ( x , y ) <nl> - <nl> - tensor_info_x = tf . saved_model . utils . build_tensor_info ( x ) <nl> - tensor_info_r = tf . saved_model . utils . build_tensor_info ( r ) <nl> - <nl> - signature_def = tf . saved_model . signature_def_utils . build_signature_def ( <nl> - inputs = { ' x ' : tensor_info_x } , <nl> - outputs = { ' r ' : tensor_info_r } , <nl> - method_name = tf . saved_model . PREDICT_METHOD_NAME ) <nl> - <nl> - # Create two signatures that share the same variable . <nl> - return { ' basic ' : signature_def , ' basic_2 ' : signature_def } <nl> - <nl> - <nl> - if __name__ = = ' __main__ ' : <nl> - common_v1 . do_test ( Test ( ) ) <nl> mmm a / tensorflow / compiler / mlir / tensorflow / translate / import_model . cc <nl> ppp b / tensorflow / compiler / mlir / tensorflow / translate / import_model . cc <nl> limitations under the License . <nl> # include " llvm / ADT / ArrayRef . h " <nl> # include " llvm / ADT / DenseMap . h " <nl> # include " llvm / ADT / STLExtras . h " <nl> - # include " llvm / ADT / SetVector . h " <nl> # include " llvm / ADT / SmallVector . h " <nl> # include " llvm / ADT / StringRef . h " <nl> # include " llvm / ADT / Twine . h " <nl> limitations under the License . <nl> # include " tensorflow / core / framework / node_def . pb . h " <nl> # include " tensorflow / core / framework / node_def_util . h " <nl> # include " tensorflow / core / framework / op . h " <nl> - # include " tensorflow / core / framework / resource_var . h " <nl> # include " tensorflow / core / framework / shape_inference . h " <nl> # include " tensorflow / core / framework / tensor . pb . h " <nl> # include " tensorflow / core / framework / types . h " <nl> limitations under the License . <nl> # include " tensorflow / core / graph / graph_constructor . h " <nl> # include " tensorflow / core / graph / node_builder . h " <nl> # include " tensorflow / core / graph / tensor_id . h " <nl> - # include " tensorflow / core / grappler / utils / transitive_fanin . h " <nl> # include " tensorflow / core / lib / core / errors . h " <nl> # include " tensorflow / core / lib / strings / str_util . h " <nl> # include " tensorflow / core / platform / protobuf . h " <nl> class GraphDefImporter : public ImporterBase { <nl> static StatusOr < mlir : : OwningModuleRef > Convert ( <nl> mlir : : MLIRContext * context , const Graph & graph , <nl> const GraphDebugInfo & debug_info , <nl> - const FunctionLibraryDefinition & flib_def , const GraphImportConfig & specs , <nl> - llvm : : StringRef func_name ) ; <nl> + const FunctionLibraryDefinition & flib_def , <nl> + const GraphImportConfig & specs ) ; <nl> <nl> private : <nl> explicit GraphDefImporter ( <nl> class GraphDefImporter : public ImporterBase { <nl> StatusOr < mlir : : OwningModuleRef > GraphDefImporter : : Convert ( <nl> mlir : : MLIRContext * context , const Graph & graph , <nl> const GraphDebugInfo & debug_info , const FunctionLibraryDefinition & flib_def , <nl> - const GraphImportConfig & specs , llvm : : StringRef func_name ) { <nl> + const GraphImportConfig & specs ) { <nl> mlir : : OwningModuleRef module = <nl> mlir : : ModuleOp : : create ( mlir : : UnknownLoc : : get ( context ) ) ; <nl> std : : unordered_map < std : : string , std : : string > tf_name_to_mlir_name ; <nl> StatusOr < mlir : : OwningModuleRef > GraphDefImporter : : Convert ( <nl> { producer , min_consumer , bad_consumers } ) ) ) ; <nl> <nl> TF_RETURN_IF_ERROR ( importer . ImporterBase : : Convert ( <nl> - func_name , func_type , arg_nodes , ret_nodes , control_ret_nodes , attrs , <nl> + " main " , func_type , arg_nodes , ret_nodes , control_ret_nodes , attrs , <nl> resource_arg_unique_ids ) ) ; <nl> return module ; <nl> } <nl> StatusOr < mlir : : OwningModuleRef > SavedModelImporter : : Convert ( <nl> return module ; <nl> } <nl> <nl> - / / A helper class to import a TensorFlow model expressed in SavedModel V1 into <nl> - / / an MLIR Module . <nl> - class SavedModelV1Importer { <nl> - public : <nl> - / / Main entry point : converts all functions ( specified by SignatureDefs ) in <nl> - / / the given meta graph to an MLIR Module . <nl> - static StatusOr < mlir : : OwningModuleRef > Convert ( const SavedModelBundle & bundle , <nl> - mlir : : MLIRContext * context ) { <nl> - SavedModelV1Importer importer ( bundle , context ) ; <nl> - <nl> - return importer . ConvertSignatures ( ) ; <nl> - } <nl> - <nl> - private : <nl> - SavedModelV1Importer ( const SavedModelBundle & bundle , <nl> - mlir : : MLIRContext * context ) <nl> - : bundle_ ( bundle ) , <nl> - module_ ( mlir : : ModuleOp : : create ( mlir : : UnknownLoc : : get ( context ) ) ) { } <nl> - <nl> - / / Convert the SavedModel to TF Executor Dialect . It creates a MLIR function <nl> - / / for each signature . <nl> - StatusOr < mlir : : OwningModuleRef > ConvertSignatures ( ) ; <nl> - StatusOr < mlir : : OwningModuleRef > ConvertSignature ( <nl> - const GraphImportConfig & specs , llvm : : StringRef func_name , <nl> - const SignatureDef & signature_def , const GraphDef & sub_graph_def , <nl> - const GraphDebugInfo & debug_info , <nl> - const FunctionLibraryDefinition & flib_def ) ; <nl> - <nl> - / / Create GlobalTensorOp for each variable and move each VarHandle op to <nl> - / / the enclosing function ' s arugments . <nl> - Status LiftVariables ( ) ; <nl> - void LiftVariable ( mlir : : TF : : VarHandleOp op ) ; <nl> - <nl> - / / Read all variables from the SavedModel through session , and create <nl> - / / GlobalTensorOp for these variables . <nl> - Status ReadVariablesFromSession ( <nl> - const llvm : : SmallVectorImpl < mlir : : TF : : VarHandleOp > & ops ) ; <nl> - <nl> - GraphImportConfig : : InputArrays ParseInputArrays ( <nl> - const tensorflow : : protobuf : : Map < std : : string , TensorInfo > & inputs ) ; <nl> - <nl> - std : : vector < std : : string > ParseOutputArrays ( <nl> - const tensorflow : : protobuf : : Map < std : : string , TensorInfo > & outputs ) ; <nl> - <nl> - const SavedModelBundle & bundle_ ; <nl> - mlir : : OwningModuleRef module_ ; <nl> - } ; <nl> - <nl> - / / Convert the SavedModel to TF Executor Dialect . It creates a MLIR function <nl> - / / for each signature . <nl> - StatusOr < mlir : : OwningModuleRef > SavedModelV1Importer : : ConvertSignatures ( ) { <nl> - const auto & signatures = bundle_ . GetSignatures ( ) ; <nl> - const auto & graphdef = bundle_ . meta_graph_def . graph_def ( ) ; <nl> - <nl> - FunctionLibraryDefinition flib_def ( OpRegistry : : Global ( ) , graphdef . library ( ) ) ; <nl> - <nl> - / / debug_info might not be loaded with loader_lite . <nl> - GraphDebugInfo debug_info ; <nl> - if ( bundle_ . debug_info ! = nullptr ) debug_info = * bundle_ . debug_info ; <nl> - <nl> - for ( const auto & key_and_signature_def : signatures ) { <nl> - const auto & func_name = key_and_signature_def . first ; <nl> - const auto & signature_def = key_and_signature_def . second ; <nl> - GraphImportConfig specs ; <nl> - specs . inputs = ParseInputArrays ( signature_def . inputs ( ) ) ; <nl> - specs . outputs = ParseOutputArrays ( signature_def . outputs ( ) ) ; <nl> - <nl> - / / Remove unused nodes and create a sub graphdef . <nl> - GraphDef sub_graph_def ; <nl> - TF_RETURN_IF_ERROR ( tensorflow : : grappler : : SetTransitiveFaninGraph ( <nl> - graphdef , & sub_graph_def , <nl> - / * terminal_nodes = * / { specs . outputs . begin ( ) , specs . outputs . end ( ) } ) ) ; <nl> - <nl> - auto status_or_sub_module = ConvertSignature ( <nl> - specs , func_name , signature_def , sub_graph_def , debug_info , flib_def ) ; <nl> - if ( ! status_or_sub_module . ok ( ) ) { <nl> - LOG ( ERROR ) < < " Failed to convert SignatureDef for " < < func_name < < " : " <nl> - < < status_or_sub_module . status ( ) ; <nl> - continue ; <nl> - } <nl> - <nl> - auto & sub_module = status_or_sub_module . ValueOrDie ( ) ; <nl> - <nl> - / / Move the converted functions to top level MLIR module . <nl> - auto * block = module_ - > getBody ( ) ; <nl> - auto * sub_block = sub_module - > getBody ( ) ; <nl> - block - > getOperations ( ) . splice ( <nl> - mlir : : Block : : iterator ( block - > getTerminator ( ) ) , <nl> - sub_block - > getOperations ( ) , sub_block - > begin ( ) , <nl> - mlir : : Block : : iterator ( sub_block - > getTerminator ( ) ) ) ; <nl> - } <nl> - <nl> - TF_RETURN_IF_ERROR ( LiftVariables ( ) ) ; <nl> - <nl> - return std : : move ( module_ ) ; <nl> - } <nl> - <nl> - StatusOr < mlir : : OwningModuleRef > SavedModelV1Importer : : ConvertSignature ( <nl> - const GraphImportConfig & specs , llvm : : StringRef func_name , <nl> - const SignatureDef & signature_def , const GraphDef & sub_graph_def , <nl> - const GraphDebugInfo & debug_info , <nl> - const FunctionLibraryDefinition & flib_def ) { <nl> - / / Convert this sub graphdef to sub graph <nl> - GraphConstructorOptions options ; <nl> - options . allow_internal_ops = true ; <nl> - options . add_default_attributes = true ; <nl> - Graph sub_graph ( OpRegistry : : Global ( ) ) ; <nl> - <nl> - TF_RETURN_IF_ERROR ( <nl> - ConvertGraphDefToGraph ( options , sub_graph_def , & sub_graph ) ) ; <nl> - <nl> - / / Convert the sub graphdef to a MLIR function . <nl> - return GraphDefImporter : : Convert ( module_ - > getContext ( ) , sub_graph , debug_info , <nl> - flib_def , specs , func_name ) ; <nl> - } <nl> - <nl> - / / Create GlobalTensorOp for each variable and move each VarHandle op to <nl> - / / the enclosing function ' s arugments . <nl> - Status SavedModelV1Importer : : LiftVariables ( ) { <nl> - llvm : : SmallVector < mlir : : TF : : VarHandleOp , 4 > ops ; <nl> - <nl> - bool contains_ref_variable = false ; <nl> - <nl> - module_ - > walk ( [ & ops , & contains_ref_variable ] ( mlir : : Operation * op ) { <nl> - if ( auto var_handle_op = llvm : : dyn_cast < mlir : : TF : : VarHandleOp > ( op ) ) <nl> - ops . push_back ( var_handle_op ) ; <nl> - else if ( op - > getName ( ) . getStringRef ( ) = = " tf . VariableV2 " ) <nl> - contains_ref_variable = true ; <nl> - } ) ; <nl> - <nl> - if ( contains_ref_variable ) <nl> - return errors : : InvalidArgument ( <nl> - " Ref variable created by VariableV2 is not supported . " ) ; <nl> - <nl> - if ( ops . empty ( ) ) return Status : : OK ( ) ; <nl> - <nl> - TF_RETURN_IF_ERROR ( ReadVariablesFromSession ( ops ) ) ; <nl> - <nl> - for ( auto op : ops ) LiftVariable ( op ) ; <nl> - <nl> - return Status : : OK ( ) ; <nl> - } <nl> - <nl> - / / Move the result of the VarHandleOp to the enclosing function ' s arugment list <nl> - / / and erase this VarHandleOp . <nl> - void SavedModelV1Importer : : LiftVariable ( mlir : : TF : : VarHandleOp op ) { <nl> - mlir : : OpBuilder builder ( & module_ - > getBodyRegion ( ) ) ; <nl> - <nl> - auto func_op = op . getParentOfType < mlir : : FuncOp > ( ) ; <nl> - builder . setInsertionPoint ( func_op ) ; <nl> - <nl> - auto func_type = func_op . getType ( ) ; <nl> - <nl> - / / Create the new function type by adding variable type to the arguments . <nl> - llvm : : SmallVector < mlir : : Type , 4 > new_input_types ( <nl> - func_type . getInputs ( ) . begin ( ) , func_type . getInputs ( ) . end ( ) ) ; <nl> - new_input_types . push_back ( op . resource ( ) - > getType ( ) ) ; <nl> - auto new_func_type = <nl> - builder . getFunctionType ( new_input_types , func_type . getResults ( ) ) ; <nl> - <nl> - auto new_func_op = builder . create < mlir : : FuncOp > ( <nl> - func_op . getLoc ( ) , func_op . getName ( ) , new_func_type , <nl> - llvm : : ArrayRef < mlir : : NamedAttribute > ( ) ) ; <nl> - <nl> - / / Bind the argument to the corresponding global tensor op . <nl> - new_func_op . setArgAttr ( new_func_op . getNumArguments ( ) - 1 , <nl> - " tf_saved_model . bound_input " , <nl> - builder . getSymbolRefAttr ( op . shared_name ( ) ) ) ; <nl> - <nl> - / / Replace the function body and update its signature . <nl> - auto & new_region = new_func_op . getBody ( ) ; <nl> - new_region . getBlocks ( ) . splice ( new_region . end ( ) , <nl> - func_op . getBody ( ) . getBlocks ( ) ) ; <nl> - <nl> - func_op . getOperation ( ) - > erase ( ) ; <nl> - <nl> - auto & new_block = new_region . front ( ) ; <nl> - auto * new_value = new_block . addArgument ( op . resource ( ) - > getType ( ) ) ; <nl> - <nl> - op . getOperation ( ) - > replaceAllUsesWith ( <nl> - llvm : : ArrayRef < mlir : : Value * > ( new_value ) ) ; <nl> - <nl> - op . getOperation ( ) - > erase ( ) ; <nl> - } <nl> - <nl> - / / Read all variables from the SavedModel through session , and create <nl> - / / GlobalTensorOp for these variables . <nl> - Status SavedModelV1Importer : : ReadVariablesFromSession ( <nl> - const llvm : : SmallVectorImpl < mlir : : TF : : VarHandleOp > & ops ) { <nl> - mlir : : OpBuilder builder ( & module_ - > getBodyRegion ( ) ) ; <nl> - <nl> - / / Find all variables and their corresponding read ops . <nl> - <nl> - llvm : : MapVector < llvm : : StringRef , mlir : : TF : : VarHandleOp > <nl> - variable_names_and_ops ; <nl> - for ( auto op : ops ) { <nl> - variable_names_and_ops [ op . shared_name ( ) ] = op ; <nl> - } <nl> - <nl> - / / Read all resource variables from the session . <nl> - <nl> - std : : vector < std : : string > variable_names ; <nl> - variable_names . reserve ( variable_names_and_ops . size ( ) ) ; <nl> - for ( const auto & name_and_location : variable_names_and_ops ) <nl> - variable_names . push_back ( name_and_location . first ) ; <nl> - <nl> - std : : vector < Tensor > resource_tensors ; <nl> - TF_RETURN_IF_ERROR ( bundle_ . GetSession ( ) - > Run ( <nl> - / * inputs = * / { } , variable_names , <nl> - / * target_node_names = * / { } , & resource_tensors ) ) ; <nl> - <nl> - const DeviceMgr * device_manager ; <nl> - TF_RETURN_IF_ERROR ( bundle_ . GetSession ( ) - > LocalDeviceManager ( & device_manager ) ) ; <nl> - <nl> - / / Read all underlying tensors of the variables from the session . <nl> - std : : vector < Tensor > tensors ; <nl> - tensors . reserve ( resource_tensors . size ( ) ) ; <nl> - for ( const auto & resource_tensor : resource_tensors ) { <nl> - const auto & resource_handle = resource_tensor . scalar < ResourceHandle > ( ) ( ) ; <nl> - <nl> - Device * device ; <nl> - TF_RETURN_IF_ERROR ( <nl> - device_manager - > LookupDevice ( resource_handle . device ( ) , & device ) ) ; <nl> - <nl> - Var * var_ptr ; <nl> - TF_RETURN_IF_ERROR ( device - > resource_manager ( ) - > Lookup ( <nl> - resource_handle . container ( ) , resource_handle . name ( ) , & var_ptr ) ) ; <nl> - core : : RefCountPtr < Var > var ( var_ptr ) ; <nl> - <nl> - / / The variable tensor is already loaded into corresponding device ' s <nl> - / / resource manager when we load the saved model using LoadSavedModel ( ) . <nl> - / / Here we just read its value . <nl> - mutex_lock ml ( * var - > mu ( ) ) ; <nl> - tensors . push_back ( * var - > tensor ( ) ) ; <nl> - } <nl> - <nl> - for ( const auto & iter : llvm : : zip ( variable_names_and_ops , tensors ) ) { <nl> - const auto & name = std : : get < 0 > ( iter ) . first ; <nl> - auto location = std : : get < 0 > ( iter ) . second . getLoc ( ) ; <nl> - const auto & tensor = std : : get < 1 > ( iter ) ; <nl> - <nl> - / / Create tensor attribute for this variable . <nl> - TF_ASSIGN_OR_RETURN ( auto tensor_attr , ConvertTensor ( tensor , & builder ) ) ; <nl> - <nl> - builder . create < mlir : : tf_saved_model : : GlobalTensorOp > ( <nl> - location , builder . getStringAttr ( name ) , tensor_attr , <nl> - mlir : : TypeAttr : : get ( tensor_attr . getType ( ) ) , builder . getUnitAttr ( ) ) ; <nl> - } <nl> - <nl> - return Status : : OK ( ) ; <nl> - } <nl> - <nl> - GraphImportConfig : : InputArrays SavedModelV1Importer : : ParseInputArrays ( <nl> - const tensorflow : : protobuf : : Map < std : : string , TensorInfo > & inputs ) { <nl> - GraphImportConfig : : InputArrays results ; <nl> - for ( const auto & iter : inputs ) { <nl> - const auto & tensor_info = iter . second ; <nl> - <nl> - / / Only dense tensor is supported . <nl> - DCHECK_EQ ( tensor_info . encoding_case ( ) , tensorflow : : TensorInfo : : kName ) ; <nl> - <nl> - ArrayInfo array_info ; <nl> - array_info . imported_dtype = tensor_info . dtype ( ) ; <nl> - array_info . shape = tensor_info . tensor_shape ( ) ; <nl> - <nl> - std : : vector < absl : : string_view > node_names = <nl> - absl : : StrSplit ( tensor_info . name ( ) , ' : ' ) ; <nl> - <nl> - results . insert ( std : : pair < std : : string , ArrayInfo > { node_names . at ( 0 ) , <nl> - std : : move ( array_info ) } ) ; <nl> - } <nl> - return results ; <nl> - } <nl> - <nl> - std : : vector < std : : string > SavedModelV1Importer : : ParseOutputArrays ( <nl> - const tensorflow : : protobuf : : Map < std : : string , TensorInfo > & outputs ) { <nl> - std : : vector < std : : string > results ; <nl> - for ( const auto & iter : outputs ) { <nl> - const auto & tensor_info = iter . second ; <nl> - <nl> - std : : vector < absl : : string_view > node_names = <nl> - absl : : StrSplit ( tensor_info . name ( ) , ' : ' ) ; <nl> - results . push_back ( std : : string ( node_names . at ( 0 ) ) ) ; <nl> - } <nl> - return results ; <nl> - } <nl> - <nl> } / / namespace <nl> <nl> Status UpgradeLegacyGraph ( Graph * graph , FunctionLibraryDefinition * flib_def ) { <nl> StatusOr < mlir : : OwningModuleRef > ConvertGraphToMlir ( <nl> UpgradeLegacyGraph ( const_cast < Graph * > ( & graph ) , <nl> const_cast < FunctionLibraryDefinition * > ( & flib_def ) ) ) ; <nl> } <nl> - return GraphDefImporter : : Convert ( context , graph , debug_info , flib_def , specs , <nl> - / * func_name = * / " main " ) ; <nl> + return GraphDefImporter : : Convert ( context , graph , debug_info , flib_def , specs ) ; <nl> } <nl> <nl> StatusOr < mlir : : OwningModuleRef > ConvertSavedModelToMlir ( <nl> StatusOr < mlir : : OwningModuleRef > ConvertSavedModelToMlir ( <nl> add_default_attributes ) ; <nl> } <nl> <nl> - StatusOr < mlir : : OwningModuleRef > ConvertSavedModelV1ToMlir ( <nl> - const SavedModelBundle & saved_model , mlir : : MLIRContext * context ) { <nl> - return SavedModelV1Importer : : Convert ( saved_model , context ) ; <nl> - } <nl> - <nl> std : : string MlirModuleToString ( mlir : : ModuleOp module , bool show_debug_info ) { <nl> std : : string txt_module ; <nl> { <nl> mmm a / tensorflow / compiler / mlir / tensorflow / translate / import_model . h <nl> ppp b / tensorflow / compiler / mlir / tensorflow / translate / import_model . h <nl> limitations under the License . <nl> # include " mlir / IR / MLIRContext . h " / / TF : local_config_mlir <nl> # include " mlir / IR / Module . h " / / TF : local_config_mlir <nl> # include " tensorflow / cc / saved_model / bundle_v2 . h " <nl> - # include " tensorflow / cc / saved_model / loader . h " <nl> # include " tensorflow / compiler / mlir / tensorflow / translate / mlir_roundtrip_flags . h " <nl> # include " tensorflow / core / framework / function . h " <nl> # include " tensorflow / core / framework / graph . pb . h " <nl> stream_executor : : port : : StatusOr < mlir : : OwningModuleRef > ConvertSavedModelToMlir ( <nl> SavedModelV2Bundle * saved_model , mlir : : MLIRContext * context , <nl> absl : : Span < std : : string > exported_names , bool add_default_attributes = true ) ; <nl> <nl> - / / Given a V1 SavedModel , returns a MLIR module containing the functions , <nl> - / / expressed with tf_executor dialect . <nl> - stream_executor : : port : : StatusOr < mlir : : OwningModuleRef > <nl> - ConvertSavedModelV1ToMlir ( const SavedModelBundle & saved_model , <nl> - mlir : : MLIRContext * context ) ; <nl> - <nl> / / Serialize a MLIR module to a string . <nl> std : : string MlirModuleToString ( mlir : : ModuleOp m , bool show_debug_info = false ) ; <nl> <nl> mmm a / tensorflow / compiler / mlir / tensorflow / translate / tf_mlir_translate . cc <nl> ppp b / tensorflow / compiler / mlir / tensorflow / translate / tf_mlir_translate . cc <nl> mlir : : OwningModuleRef SavedModelToMlirImport ( <nl> return module_or . ConsumeValueOrDie ( ) ; <nl> } <nl> <nl> - mlir : : OwningModuleRef SavedModelV1ToMlirImport ( <nl> - absl : : string_view saved_model_dir , <nl> - const std : : unordered_set < std : : string > & tags , mlir : : MLIRContext * context ) { <nl> - tensorflow : : SavedModelBundle bundle ; <nl> - auto load_status = tensorflow : : LoadSavedModel ( <nl> - / * session_options = * / { } , / * run_options = * / { } , <nl> - std : : string ( saved_model_dir ) , tags , & bundle ) ; <nl> - if ( ! load_status . ok ( ) ) { <nl> - LOG ( ERROR ) < < " Failed to load saved model v1 ' " < < saved_model_dir <nl> - < < " ' : " < < load_status ; <nl> - return nullptr ; <nl> - } <nl> - <nl> - auto module_or = ConvertSavedModelV1ToMlir ( bundle , context ) ; <nl> - if ( ! module_or . status ( ) . ok ( ) ) { <nl> - LOG ( ERROR ) < < " SavedModel V1 import failed : " < < module_or . status ( ) ; <nl> - return nullptr ; <nl> - } <nl> - return module_or . ConsumeValueOrDie ( ) ; <nl> - } <nl> - <nl> mlir : : OwningModuleRef GraphdefToSplattedMlirTranslateFunction ( <nl> llvm : : StringRef input , absl : : string_view debug_info_file , <nl> absl : : string_view input_arrays , absl : : string_view input_dtypes , <nl> mmm a / tensorflow / compiler / mlir / tensorflow / translate / tf_mlir_translate . h <nl> ppp b / tensorflow / compiler / mlir / tensorflow / translate / tf_mlir_translate . h <nl> mlir : : OwningModuleRef SavedModelToMlirImport ( <nl> absl : : string_view saved_model_dir , <nl> const std : : unordered_set < std : : string > & tags , <nl> absl : : Span < std : : string > exported_names , mlir : : MLIRContext * context ) ; <nl> - <nl> - / / Converts a TensorFlow V1 SavedModel stored in the directory with the given <nl> - / / ` saved_model_dir ` into a MLIR module . Creates MLIR entities into the <nl> - / / given MLIR ` context ` . <nl> - mlir : : OwningModuleRef SavedModelV1ToMlirImport ( <nl> - absl : : string_view saved_model_dir , <nl> - const std : : unordered_set < std : : string > & tags , mlir : : MLIRContext * context ) ; <nl> - <nl> } / / namespace tensorflow <nl> <nl> # endif / / TENSORFLOW_COMPILER_MLIR_TENSORFLOW_TRANSLATE_TF_MLIR_TRANSLATE_H_ <nl> mmm a / tensorflow / compiler / mlir / tf_mlir_translate_main . cc <nl> ppp b / tensorflow / compiler / mlir / tf_mlir_translate_main . cc <nl> static llvm : : cl : : opt < bool > import_saved_model ( <nl> llvm : : cl : : desc ( " Import a saved model to its MLIR representation " ) , <nl> llvm : : cl : : value_desc ( " dir " ) ) ; <nl> <nl> - / / NOLINTNEXTLINE <nl> - static llvm : : cl : : opt < bool > import_saved_model_v1 ( <nl> - " savedmodel - v1 - to - mlir " , <nl> - llvm : : cl : : desc ( " Import a saved model V1 to its MLIR representation " ) , <nl> - llvm : : cl : : value_desc ( " dir " ) ) ; <nl> - <nl> / / NOLINTNEXTLINE <nl> static llvm : : cl : : opt < std : : string > saved_model_tags ( <nl> " tf - savedmodel - tags " , <nl> int main ( int argc , char * * argv ) { <nl> <nl> llvm : : cl : : ParseCommandLineOptions ( argc , argv , " TF MLIR translation driver \ n " ) ; <nl> <nl> - if ( ! import_saved_model & & ! import_saved_model_v1 & & ! requested_translation ) { <nl> + if ( ! import_saved_model & & ! requested_translation ) { <nl> llvm : : errs ( ) < < " error : need to specify one translation to perform \ n " ; <nl> return 1 ; <nl> - } else if ( import_saved_model & & import_saved_model_v1 & & <nl> - requested_translation ) { <nl> + } else if ( import_saved_model & & requested_translation ) { <nl> llvm : : errs ( ) <nl> < < " error : cannot specify more than one translation to perform \ n " ; <nl> return 1 ; <nl> int main ( int argc , char * * argv ) { <nl> & context ) ; <nl> if ( ! module ) return 1 ; <nl> <nl> - module - > print ( output - > os ( ) ) ; <nl> - } else if ( import_saved_model_v1 ) { <nl> - std : : unordered_set < std : : string > tags = <nl> - absl : : StrSplit ( saved_model_tags , ' , ' ) ; <nl> - mlir : : MLIRContext context ; <nl> - <nl> - auto module = <nl> - tensorflow : : SavedModelV1ToMlirImport ( input_filename , tags , & context ) ; <nl> - if ( ! module ) return 1 ; <nl> - <nl> module - > print ( output - > os ( ) ) ; <nl> } else { <nl> auto input = mlir : : openInputFile ( input_filename , & error_message ) ; <nl> | Initial version of SavedModel V1 Importer that converts a V1 SavedModel to a | tensorflow/tensorflow | 0927dc4cc4b4eee2c29bce24e448aa8b9813a8ae | 2019-12-23T01:51:42Z |
mmm a / cocos / 2d / CCProgressTimer . cpp <nl> ppp b / cocos / 2d / CCProgressTimer . cpp <nl> ProgressTimer : : ProgressTimer ( ) <nl> ProgressTimer * ProgressTimer : : create ( Sprite * sp ) <nl> { <nl> ProgressTimer * progressTimer = new ( std : : nothrow ) ProgressTimer ( ) ; <nl> - if ( progressTimer - > initWithSprite ( sp ) ) <nl> + if ( progressTimer & & progressTimer - > initWithSprite ( sp ) ) <nl> { <nl> progressTimer - > autorelease ( ) ; <nl> + return progressTimer ; <nl> } <nl> - else <nl> - { <nl> - delete progressTimer ; <nl> - progressTimer = nullptr ; <nl> - } <nl> - <nl> - return progressTimer ; <nl> + <nl> + delete progressTimer ; <nl> + return nullptr ; <nl> } <nl> <nl> bool ProgressTimer : : initWithSprite ( Sprite * sp ) <nl> mmm a / cocos / 2d / CCSprite . cpp <nl> ppp b / cocos / 2d / CCSprite . cpp <nl> Sprite * Sprite : : create ( ) <nl> return nullptr ; <nl> } <nl> <nl> - bool Sprite : : init ( void ) <nl> + bool Sprite : : init ( ) <nl> { <nl> - return initWithTexture ( nullptr , Rect : : ZERO ) ; <nl> + initWithTexture ( nullptr , Rect : : ZERO ) ; <nl> + <nl> + return true ; <nl> } <nl> <nl> bool Sprite : : initWithTexture ( Texture2D * texture ) <nl> bool Sprite : : initWithTexture ( Texture2D * texture ) <nl> CCASSERT ( texture ! = nullptr , " Invalid texture for sprite " ) ; <nl> <nl> Rect rect = Rect : : ZERO ; <nl> - rect . size = texture - > getContentSize ( ) ; <nl> + if ( texture ) { <nl> + rect . size = texture - > getContentSize ( ) ; <nl> + } <nl> <nl> - return initWithTexture ( texture , rect ) ; <nl> + return initWithTexture ( texture , rect , false ) ; <nl> } <nl> <nl> bool Sprite : : initWithTexture ( Texture2D * texture , const Rect & rect ) <nl> bool Sprite : : initWithFile ( const std : : string & filename ) <nl> _fileName = filename ; <nl> _fileType = 0 ; <nl> <nl> - Texture2D * texture = Director : : getInstance ( ) - > getTextureCache ( ) - > addImage ( filename ) ; <nl> + Texture2D * texture = _director - > getTextureCache ( ) - > addImage ( filename ) ; <nl> if ( texture ) <nl> { <nl> Rect rect = Rect : : ZERO ; <nl> bool Sprite : : initWithFile ( const std : : string & filename ) <nl> <nl> bool Sprite : : initWithFile ( const std : : string & filename , const Rect & rect ) <nl> { <nl> - CCASSERT ( filename . size ( ) > 0 , " Invalid filename " ) ; <nl> - <nl> + CCASSERT ( ! filename . empty ( ) , " Invalid filename " ) ; <nl> + if ( filename . empty ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> _fileName = filename ; <nl> _fileType = 0 ; <nl> <nl> - Texture2D * texture = Director : : getInstance ( ) - > getTextureCache ( ) - > addImage ( filename ) ; <nl> + Texture2D * texture = _director - > getTextureCache ( ) - > addImage ( filename ) ; <nl> if ( texture ) <nl> { <nl> return initWithTexture ( texture , rect ) ; <nl> bool Sprite : : initWithFile ( const std : : string & filename , const Rect & rect ) <nl> <nl> bool Sprite : : initWithSpriteFrameName ( const std : : string & spriteFrameName ) <nl> { <nl> - CCASSERT ( spriteFrameName . size ( ) > 0 , " Invalid spriteFrameName " ) ; <nl> - <nl> + CCASSERT ( ! spriteFrameName . empty ( ) , " Invalid spriteFrameName " ) ; <nl> + if ( spriteFrameName . empty ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> _fileName = spriteFrameName ; <nl> _fileType = 1 ; <nl> <nl> bool Sprite : : initWithSpriteFrameName ( const std : : string & spriteFrameName ) <nl> bool Sprite : : initWithSpriteFrame ( SpriteFrame * spriteFrame ) <nl> { <nl> CCASSERT ( spriteFrame ! = nullptr , " spriteFrame can ' t be nullptr ! " ) ; <nl> - <nl> + if ( spriteFrame = = nullptr ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> bool bRet = initWithTexture ( spriteFrame - > getTexture ( ) , spriteFrame - > getRect ( ) ) ; <nl> setSpriteFrame ( spriteFrame ) ; <nl> <nl> bool Sprite : : initWithSpriteFrame ( SpriteFrame * spriteFrame ) <nl> <nl> bool Sprite : : initWithPolygon ( const cocos2d : : PolygonInfo & info ) <nl> { <nl> - Texture2D * texture = Director : : getInstance ( ) - > getTextureCache ( ) - > addImage ( info . filename ) ; <nl> - bool res = false ; <nl> - if ( initWithTexture ( texture ) ) <nl> + bool ret = false ; <nl> + <nl> + Texture2D * texture = _director - > getTextureCache ( ) - > addImage ( info . filename ) ; <nl> + if ( texture & & initWithTexture ( texture ) ) <nl> { <nl> _polyInfo = info ; <nl> - setContentSize ( _polyInfo . rect . size / Director : : getInstance ( ) - > getContentScaleFactor ( ) ) ; <nl> - res = true ; <nl> + setContentSize ( _polyInfo . rect . size / _director - > getContentScaleFactor ( ) ) ; <nl> + ret = true ; <nl> } <nl> - return res ; <nl> + <nl> + return ret ; <nl> } <nl> <nl> / / designated initializer <nl> bool Sprite : : initWithTexture ( Texture2D * texture , const Rect & rect , bool rotated ) <nl> { <nl> - bool result ; <nl> + bool result = false ; <nl> if ( Node : : init ( ) ) <nl> { <nl> _batchNode = nullptr ; <nl> bool Sprite : : initWithTexture ( Texture2D * texture , const Rect & rect , bool rotated ) <nl> setBatchNode ( nullptr ) ; <nl> result = true ; <nl> } <nl> - else <nl> - { <nl> - result = false ; <nl> - } <nl> + <nl> _recursiveDirty = true ; <nl> setDirty ( true ) ; <nl> + <nl> return result ; <nl> } <nl> <nl> void Sprite : : setTexture ( Texture2D * texture ) <nl> if ( texture = = nullptr ) <nl> { <nl> / / Gets the texture by key firstly . <nl> - texture = Director : : getInstance ( ) - > getTextureCache ( ) - > getTextureForKey ( CC_2x2_WHITE_IMAGE_KEY ) ; <nl> + texture = _director - > getTextureCache ( ) - > getTextureForKey ( CC_2x2_WHITE_IMAGE_KEY ) ; <nl> <nl> / / If texture wasn ' t in cache , create it from RAW data . <nl> if ( texture = = nullptr ) <nl> void Sprite : : setTexture ( Texture2D * texture ) <nl> CC_UNUSED_PARAM ( isOK ) ; <nl> CCASSERT ( isOK , " The 2x2 empty texture was created unsuccessfully . " ) ; <nl> <nl> - texture = Director : : getInstance ( ) - > getTextureCache ( ) - > addImage ( image , CC_2x2_WHITE_IMAGE_KEY ) ; <nl> + texture = _director - > getTextureCache ( ) - > addImage ( image , CC_2x2_WHITE_IMAGE_KEY ) ; <nl> CC_SAFE_RELEASE ( image ) ; <nl> } <nl> } <nl> void Sprite : : setVertexRect ( const Rect & rect ) <nl> <nl> void Sprite : : setTextureCoords ( Rect rect ) <nl> { <nl> - rect = CC_RECT_POINTS_TO_PIXELS ( rect ) ; <nl> - <nl> Texture2D * tex = _batchNode ? _textureAtlas - > getTexture ( ) : _texture ; <nl> - if ( ! tex ) <nl> + if ( tex = = nullptr ) <nl> { <nl> return ; <nl> } <nl> + <nl> + rect = CC_RECT_POINTS_TO_PIXELS ( rect ) ; <nl> <nl> float atlasWidth = ( float ) tex - > getPixelsWide ( ) ; <nl> float atlasHeight = ( float ) tex - > getPixelsHigh ( ) ; <nl> void Sprite : : updateTransform ( void ) <nl> <nl> void Sprite : : draw ( Renderer * renderer , const Mat4 & transform , uint32_t flags ) <nl> { <nl> + if ( _texture = = nullptr ) <nl> + { <nl> + return ; <nl> + } <nl> + <nl> # if CC_USE_CULLING <nl> / / Don ' t do calculate the culling if the transform was not updated <nl> auto visitingCamera = Camera : : getVisitingCamera ( ) ; <nl> void Sprite : : draw ( Renderer * renderer , const Mat4 & transform , uint32_t flags ) <nl> void Sprite : : addChild ( Node * child , int zOrder , int tag ) <nl> { <nl> CCASSERT ( child ! = nullptr , " Argument must be non - nullptr " ) ; <nl> - <nl> + if ( child = = nullptr ) <nl> + { <nl> + return ; <nl> + } <nl> + <nl> if ( _batchNode ) <nl> { <nl> Sprite * childSprite = dynamic_cast < Sprite * > ( child ) ; <nl> void Sprite : : addChild ( Node * child , int zOrder , int tag ) <nl> void Sprite : : addChild ( Node * child , int zOrder , const std : : string & name ) <nl> { <nl> CCASSERT ( child ! = nullptr , " Argument must be non - nullptr " ) ; <nl> + if ( child = = nullptr ) <nl> + { <nl> + return ; <nl> + } <nl> <nl> if ( _batchNode ) <nl> { <nl> bool Sprite : : isOpacityModifyRGB ( void ) const <nl> <nl> void Sprite : : setSpriteFrame ( const std : : string & spriteFrameName ) <nl> { <nl> + CCASSERT ( ! spriteFrameName . empty ( ) , " spriteFrameName must not be empty " ) ; <nl> + if ( spriteFrameName . empty ( ) ) <nl> + { <nl> + return ; <nl> + } <nl> + <nl> SpriteFrameCache * cache = SpriteFrameCache : : getInstance ( ) ; <nl> SpriteFrame * spriteFrame = cache - > getSpriteFrameByName ( spriteFrameName ) ; <nl> <nl> void Sprite : : setSpriteFrame ( SpriteFrame * spriteFrame ) <nl> <nl> void Sprite : : setDisplayFrameWithAnimationName ( const std : : string & animationName , ssize_t frameIndex ) <nl> { <nl> - CCASSERT ( animationName . size ( ) > 0 , " CCSprite # setDisplayFrameWithAnimationName . animationName must not be nullptr " ) ; <nl> - <nl> + CCASSERT ( ! animationName . empty ( ) , " CCSprite # setDisplayFrameWithAnimationName . animationName must not be nullptr " ) ; <nl> + if ( animationName . empty ( ) ) <nl> + { <nl> + return ; <nl> + } <nl> + <nl> Animation * a = AnimationCache : : getInstance ( ) - > getAnimation ( animationName ) ; <nl> <nl> CCASSERT ( a , " CCSprite # setDisplayFrameWithAnimationName : Frame not found " ) ; <nl> mmm a / cocos / 2d / CCSpriteBatchNode . cpp <nl> ppp b / cocos / 2d / CCSpriteBatchNode . cpp <nl> NS_CC_BEGIN <nl> SpriteBatchNode * SpriteBatchNode : : createWithTexture ( Texture2D * tex , ssize_t capacity / * = DEFAULT_CAPACITY * / ) <nl> { <nl> SpriteBatchNode * batchNode = new ( std : : nothrow ) SpriteBatchNode ( ) ; <nl> - batchNode - > initWithTexture ( tex , capacity ) ; <nl> - batchNode - > autorelease ( ) ; <nl> - <nl> - return batchNode ; <nl> + if ( batchNode & & batchNode - > initWithTexture ( tex , capacity ) ) <nl> + { <nl> + batchNode - > autorelease ( ) ; <nl> + return batchNode ; <nl> + } <nl> + <nl> + delete batchNode ; <nl> + return nullptr ; <nl> } <nl> <nl> / * <nl> SpriteBatchNode * SpriteBatchNode : : createWithTexture ( Texture2D * tex , ssize_t capa <nl> SpriteBatchNode * SpriteBatchNode : : create ( const std : : string & fileImage , ssize_t capacity / * = DEFAULT_CAPACITY * / ) <nl> { <nl> SpriteBatchNode * batchNode = new ( std : : nothrow ) SpriteBatchNode ( ) ; <nl> - batchNode - > initWithFile ( fileImage , capacity ) ; <nl> - batchNode - > autorelease ( ) ; <nl> - <nl> - return batchNode ; <nl> + if ( batchNode & & batchNode - > initWithFile ( fileImage , capacity ) ) <nl> + { <nl> + batchNode - > autorelease ( ) ; <nl> + return batchNode ; <nl> + } <nl> + <nl> + delete batchNode ; <nl> + return nullptr ; <nl> } <nl> <nl> / * <nl> SpriteBatchNode * SpriteBatchNode : : create ( const std : : string & fileImage , ssize_t c <nl> * / <nl> bool SpriteBatchNode : : initWithTexture ( Texture2D * tex , ssize_t capacity / * = DEFAULT_CAPACITY * / ) <nl> { <nl> + if ( tex = = nullptr ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> CCASSERT ( capacity > = 0 , " Capacity must be > = 0 " ) ; <nl> <nl> _blendFunc = BlendFunc : : ALPHA_PREMULTIPLIED ; <nl> bool SpriteBatchNode : : initWithTexture ( Texture2D * tex , ssize_t capacity / * = DEFAU <nl> } <nl> _textureAtlas = new ( std : : nothrow ) TextureAtlas ( ) ; <nl> <nl> - if ( capacity = = 0 ) <nl> + if ( capacity < = 0 ) <nl> { <nl> capacity = DEFAULT_CAPACITY ; <nl> } <nl> void SpriteBatchNode : : visit ( Renderer * renderer , const Mat4 & parentTransform , uin <nl> / / IMPORTANT : <nl> / / To ease the migration to v3 . 0 , we still support the Mat4 stack , <nl> / / but it is deprecated and your code should not rely on it <nl> - Director * director = Director : : getInstance ( ) ; <nl> - director - > pushMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW ) ; <nl> - director - > loadMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW , _modelViewTransform ) ; <nl> + _director - > pushMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW ) ; <nl> + _director - > loadMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW , _modelViewTransform ) ; <nl> <nl> draw ( renderer , _modelViewTransform , flags ) ; <nl> <nl> - director - > popMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW ) ; <nl> + _director - > popMatrix ( MATRIX_STACK_TYPE : : MATRIX_STACK_MODELVIEW ) ; <nl> / / FIX ME : Why need to set _orderOfArrival to 0 ? ? <nl> / / Please refer to https : / / github . com / cocos2d / cocos2d - x / pull / 6920 <nl> / / setOrderOfArrival ( 0 ) ; <nl> mmm a / cocos / ui / UIScale9Sprite . cpp <nl> ppp b / cocos / ui / UIScale9Sprite . cpp <nl> namespace ui { <nl> bool Scale9Sprite : : initWithSpriteFrame ( SpriteFrame * spriteFrame , <nl> const Rect & capInsets ) <nl> { <nl> - Texture2D * texture = spriteFrame - > getTexture ( ) ; <nl> - CCASSERT ( texture ! = NULL , " CCTexture must be not nil " ) ; <nl> - Sprite * sprite = Sprite : : createWithSpriteFrame ( spriteFrame ) ; <nl> - CCASSERT ( sprite ! = NULL , " sprite must be not nil " ) ; <nl> - bool pReturn = this - > init ( sprite , <nl> - spriteFrame - > getRect ( ) , <nl> - spriteFrame - > isRotated ( ) , <nl> - spriteFrame - > getOffset ( ) , <nl> - spriteFrame - > getOriginalSize ( ) , <nl> - capInsets ) ; <nl> - return pReturn ; <nl> + bool ret = false ; <nl> + do { <nl> + Texture2D * texture = spriteFrame - > getTexture ( ) ; <nl> + CCASSERT ( texture ! = NULL , " CCTexture must be not nil " ) ; <nl> + if ( texture = = nullptr ) break ; <nl> + <nl> + Sprite * sprite = Sprite : : createWithSpriteFrame ( spriteFrame ) ; <nl> + CCASSERT ( sprite ! = NULL , " sprite must be not nil " ) ; <nl> + if ( sprite = = nullptr ) break ; <nl> + <nl> + ret = this - > init ( sprite , <nl> + spriteFrame - > getRect ( ) , <nl> + spriteFrame - > isRotated ( ) , <nl> + spriteFrame - > getOffset ( ) , <nl> + spriteFrame - > getOriginalSize ( ) , <nl> + capInsets ) ; <nl> + } while ( false ) ; <nl> + <nl> + return ret ; <nl> } <nl> bool Scale9Sprite : : initWithSpriteFrame ( SpriteFrame * spriteFrame ) <nl> { <nl> namespace ui { <nl> bool Scale9Sprite : : initWithSpriteFrameName ( const std : : string & spriteFrameName , <nl> const Rect & capInsets ) <nl> { <nl> - CCASSERT ( ( SpriteFrameCache : : getInstance ( ) ) ! = NULL , <nl> - " SpriteFrameCache : : getInstance ( ) must be non - NULL " ) ; <nl> - <nl> - SpriteFrame * frame = SpriteFrameCache : : getInstance ( ) - > getSpriteFrameByName ( spriteFrameName ) ; <nl> - CCASSERT ( frame ! = NULL , " CCSpriteFrame must be non - NULL " ) ; <nl> - <nl> - if ( NULL = = frame ) return false ; <nl> - bool pReturn = this - > initWithSpriteFrame ( frame , capInsets ) ; <nl> - return pReturn ; <nl> + bool ret = false ; <nl> + do { <nl> + auto spriteFrameCache = SpriteFrameCache : : getInstance ( ) ; <nl> + CCASSERT ( spriteFrameCache ! = nullptr , <nl> + " SpriteFrameCache : : getInstance ( ) must be non - NULL " ) ; <nl> + <nl> + SpriteFrame * frame = spriteFrameCache - > getSpriteFrameByName ( spriteFrameName ) ; <nl> + CCASSERT ( frame ! = nullptr , " CCSpriteFrame must be non - NULL " ) ; <nl> + if ( frame = = nullptr ) return false ; <nl> + <nl> + ret = initWithSpriteFrame ( frame , capInsets ) ; <nl> + } while ( false ) ; <nl> + <nl> + return ret ; <nl> } <nl> bool Scale9Sprite : : initWithSpriteFrameName ( const std : : string & spriteFrameName ) <nl> { <nl> namespace ui { <nl> const Rect & rect , <nl> const Rect & capInsets ) <nl> { <nl> - Sprite * sprite = nullptr ; <nl> - sprite = Sprite : : create ( file ) ; <nl> - bool pReturn = this - > init ( sprite , rect , capInsets ) ; <nl> - return pReturn ; <nl> + CCASSERT ( ! file . empty ( ) , " file must not be empty string ! " ) ; <nl> + if ( file . empty ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + auto sprite = Sprite : : create ( file ) ; <nl> + return init ( sprite , rect , capInsets ) ; <nl> } <nl> <nl> bool Scale9Sprite : : initWithFile ( const std : : string & file , const Rect & rect ) <nl> { <nl> - bool pReturn = this - > initWithFile ( file , rect , Rect : : ZERO ) ; <nl> - return pReturn ; <nl> + return initWithFile ( file , rect , Rect : : ZERO ) ; <nl> } <nl> <nl> Scale9Sprite * Scale9Sprite : : create ( ) <nl> | Improved robustness in release mode | cocos2d/cocos2d-x | e5952ad44018c768ff7fabdd518cf7e971481702 | 2015-12-16T03:53:59Z |
mmm a / tensorflow / compiler / mlir / lite / tests / legalize - tf . mlir <nl> ppp b / tensorflow / compiler / mlir / lite / tests / legalize - tf . mlir <nl> func @ concatv2With3Tensors ( % arg0 : tensor < 2x1xi32 > , % arg1 : tensor < 2x1xi32 > , % arg2 <nl> / / CHECK : " tfl . concatenation " ( % arg0 , % arg1 , % arg2 ) { axis = - 1 : i32 , fused_activation_function = " NONE " } : ( tensor < 2x1xi32 > , tensor < 2x1xi32 > , tensor < 2x1xi32 > ) - > tensor < 2x3xi32 > <nl> } <nl> <nl> + func @ concatv2I64Axis ( % arg0 : tensor < 2x1xi32 > , % arg1 : tensor < 2x1xi32 > , % arg2 : tensor < 2x1xi32 > ) - > tensor < 2x3xi32 > { <nl> + % 0 = " tf . Const " ( ) { value = dense < - 1 > : tensor < i64 > } : ( ) - > tensor < i64 > <nl> + % 1 = " tf . ConcatV2 " ( % arg0 , % arg1 , % arg2 , % 0 ) : ( tensor < 2x1xi32 > , tensor < 2x1xi32 > , tensor < 2x1xi32 > , tensor < i64 > ) - > tensor < 2x3xi32 > <nl> + return % 1 : tensor < 2x3xi32 > <nl> + <nl> + / / CHECK - LABEL : concatv2I64Axis <nl> + / / CHECK : " tfl . concatenation " ( % arg0 , % arg1 , % arg2 ) { axis = - 1 : i32 , fused_activation_function = " NONE " } : ( tensor < 2x1xi32 > , tensor < 2x1xi32 > , tensor < 2x1xi32 > ) - > tensor < 2x3xi32 > <nl> + } <nl> + <nl> func @ resize_with_bilinear ( % arg0 : tensor < 1x100x100x3xf32 > , % arg1 : tensor < 4xi32 > ) - > tensor < ? xf32 > { <nl> % 0 = " tf . ResizeBilinear " ( % arg0 , % arg1 ) { align_corners = true } : ( tensor < 1x100x100x3xf32 > , tensor < 4xi32 > ) - > tensor < ? xf32 > <nl> return % 0 : tensor < ? xf32 > <nl> mmm a / tensorflow / compiler / mlir / lite / transforms / legalize_tf . cc <nl> ppp b / tensorflow / compiler / mlir / lite / transforms / legalize_tf . cc <nl> limitations under the License . <nl> # include " mlir / IR / StandardTypes . h " / / from @ llvm - project <nl> # include " mlir / Pass / Pass . h " / / from @ llvm - project <nl> # include " mlir / Support / LLVM . h " / / from @ llvm - project <nl> + # include " mlir / Support / LogicalResult . h " / / from @ llvm - project <nl> # include " mlir / Transforms / DialectConversion . h " / / from @ llvm - project <nl> # include " tensorflow / compiler / mlir / lite / ir / tfl_ops . h " <nl> # include " tensorflow / compiler / mlir / lite / quantization / quantization_utils . h " <nl> LogicalResult ConvertTFConcatOp : : matchAndRewrite ( <nl> return success ( ) ; <nl> } <nl> <nl> + / / Converts any IntegerAttr to an IntegerAttr of an i32 type . <nl> + / / The value won ' t change in the new attribute , but if the value is out of <nl> + / / the bound of i32 , the function returns a failure . <nl> + LogicalResult ConvertToI32Attr ( IntegerAttr attr , IntegerAttr * attr_i32 ) { <nl> + if ( attr . getType ( ) . isInteger ( / * width = * / 32 ) ) { <nl> + * attr_i32 = attr ; <nl> + return success ( ) ; <nl> + } <nl> + <nl> + int64_t value = attr . getInt ( ) ; <nl> + if ( value > std : : numeric_limits < int > : : max ( ) | | <nl> + value < std : : numeric_limits < int > : : min ( ) ) { <nl> + return failure ( ) ; <nl> + } <nl> + <nl> + * attr_i32 = IntegerAttr : : get ( <nl> + IntegerType : : get ( / * width = * / 32 , attr . getContext ( ) ) , value ) ; <nl> + return success ( ) ; <nl> + } <nl> + <nl> LogicalResult ConvertTFConcatV2Op : : matchAndRewrite ( <nl> Operation * op , PatternRewriter & rewriter ) const { <nl> auto tf_concat_op = cast < TF : : ConcatV2Op > ( op ) ; <nl> LogicalResult ConvertTFConcatV2Op : : matchAndRewrite ( <nl> / / Extract axis attribute from constant axis tensor <nl> ElementsAttr axis ; <nl> if ( ! matchPattern ( tf_concat_op . axis ( ) , m_Constant ( & axis ) ) ) return failure ( ) ; <nl> + IntegerAttr axis_int = ExtractSingleElementAsInteger ( axis ) ; <nl> + <nl> + / / " axis " operand could be a i64 tensor . Resolve it here . <nl> + IntegerAttr axis_i32 ; <nl> + if ( failed ( ConvertToI32Attr ( axis_int , & axis_i32 ) ) ) return failure ( ) ; <nl> <nl> StringAttr fused_activation_function = <nl> StringAttr : : get ( " NONE " , rewriter . getContext ( ) ) ; <nl> rewriter . replaceOpWithNewOp < ConcatenationOp > ( <nl> - op , output_type , values , ExtractSingleElementAsInteger ( axis ) , <nl> - fused_activation_function ) ; <nl> + op , output_type , values , axis_i32 , fused_activation_function ) ; <nl> return success ( ) ; <nl> } <nl> <nl> | Fix TF_ConcatV2Op conversion pattern when the axis is a I64 Tensor . | tensorflow/tensorflow | 63926472df4f777b43146c608a0027a42569fe57 | 2020-05-19T02:38:08Z |
mmm a / lib / SILOptimizer / Utils / Local . cpp <nl> ppp b / lib / SILOptimizer / Utils / Local . cpp <nl> optimizeUnconditionalCheckedCastAddrInst ( UnconditionalCheckedCastAddrInst * Inst ) <nl> } <nl> <nl> if ( ResultNotUsed ) { <nl> - SILBuilder B ( Inst ) ; <nl> + SILBuilderWithScope B ( Inst ) ; <nl> B . createDestroyAddr ( Inst - > getLoc ( ) , Inst - > getSrc ( ) ) ; <nl> if ( DestroyDestInst ) <nl> EraseInstAction ( DestroyDestInst ) ; <nl> new file mode 100644 <nl> index 000000000000 . . b40c72cfe419 <nl> mmm / dev / null <nl> ppp b / test / SILOptimizer / constantprop - wrongscope . swift <nl> <nl> + / / RUN : % empty - directory ( % t ) <nl> + / / RUN : % build - clang - importer - objc - overlays <nl> + / / RUN : % target - swift - frontend ( mock - sdk : % clang - importer - sdk - nosource - I % t ) - I \ <nl> + / / RUN : % S / . . / ClangImporter / Inputs / custom - modules - emit - sil - o / dev / null \ <nl> + / / RUN : - primary - file % s - Xllvm - sil - print - debuginfo - module - name patatino \ <nl> + / / RUN : - Onone - Xllvm - sil - print - after = diagnostic - constant - propagation \ <nl> + / / RUN : - Xllvm - sil - print - only - functions = $ S8patatino19indexedSubscripting1b3idx1aySo1BC_SiSo1ACtF \ <nl> + / / RUN : 2 > & 1 | % FileCheck % s <nl> + <nl> + / / REQUIRES : objc_interop <nl> + / / REQUIRES : OS = macosx <nl> + <nl> + / / Make sure that the destroy_addr instruction has the same scope of the <nl> + / / instructions surrounding it . <nl> + <nl> + / / CHECK : % 60 = unchecked_take_enum_data_addr % 12 : $ * Optional < Any > , # Optional . some ! enumelt . 1 , loc { { . * } } : 24 : 13 , scope 2 <nl> + / / CHECK : destroy_addr % 7 : $ * Any , loc { { . * } } : 24 : 19 , scope 2 <nl> + / / CHECK : dealloc_stack % 12 : $ * Optional < Any > , loc { { . * } } : 24 : 23 , scope 2 <nl> + / / CHECK : dealloc_stack % 7 : $ * Any , loc { { . * } } : 24 : 23 , scope 2 <nl> + / / CHECK : dealloc_stack % 6 : $ * A , loc { { . * } } : 24 : 7 , scope 2 <nl> + <nl> + import Foundation <nl> + func indexedSubscripting ( b b : B , idx : Int , a : A ) { <nl> + var a2 = b [ idx ] as ! A <nl> + } <nl> | Merge remote - tracking branch ' origin / master ' into master - llvm - swift5 - transition | apple/swift | a06c30f45ac679b1a0cdae74324e3d2c5012cd2d | 2018-01-10T22:58:55Z |
mmm a / lib / AST / ModuleNameLookup . cpp <nl> ppp b / lib / AST / ModuleNameLookup . cpp <nl> static void lookupInModule ( Module * module , Module : : AccessPathTy accessPath , <nl> auto newEndIter = std : : remove_if ( localDecls . begin ( ) , localDecls . end ( ) , <nl> [ = ] ( ValueDecl * VD ) { <nl> if ( typeResolver ) { <nl> - / / Do not resolve values in a type context - doing so could potentially <nl> - / / lead to an infinitely recursive validation loop . <nl> - if ( ( resolutionKind ! = ResolutionKind : : TypesOnly ) | | <nl> - dyn_cast < TypeDecl > ( VD ) ) { <nl> - typeResolver - > resolveDeclSignature ( VD ) ; <nl> - } <nl> + typeResolver - > resolveAccessibility ( VD ) ; <nl> } <nl> if ( ! VD - > hasAccessibility ( ) ) <nl> return false ; <nl> | We only need to resolve accessibility to check accessibility . | apple/swift | 40db77a6a3c06eba4fb4c123b5a29d4dcb984d59 | 2015-10-07T22:37:18Z |
mmm a / tests / fuzzer / flatbuffers_parser_fuzzer . cc <nl> ppp b / tests / fuzzer / flatbuffers_parser_fuzzer . cc <nl> extern " C " int LLVMFuzzerTestOneInput ( const uint8_t * data , size_t size ) { <nl> / / Reserve one byte for Parser flags and one byte for repetition counter . <nl> if ( size < 3 ) return 0 ; <nl> const uint8_t flags = data [ 0 ] ; <nl> - / / normalize to ascii alphabet <nl> - const int extra_rep_number = <nl> - std : : max ( 5 , ( data [ 1 ] < ' 0 ' ? ( data [ 1 ] - ' 0 ' ) : 0 ) ) ; <nl> + ( void ) data [ 1 ] ; / / reserved <nl> data + = 2 ; <nl> size - = 2 ; / / bypass <nl> <nl> extern " C " int LLVMFuzzerTestOneInput ( const uint8_t * data , size_t size ) { <nl> / / Guarantee 0 - termination in the input . <nl> auto parse_input = input . c_str ( ) ; <nl> <nl> - / / The fuzzer can adjust the number repetition if a side - effects have found . <nl> - / / Each test should pass at least two times to ensure that the parser doesn ' t <nl> - / / have any hidden - states or locale - depended effects . <nl> - for ( auto cnt = 0 ; cnt < ( extra_rep_number + 2 ) ; cnt + + ) { <nl> - / / Each even run ( 0 , 2 , 4 . . ) will test locale independed code . <nl> - auto use_locale = ! ! OneTimeTestInit : : test_locale ( ) & & ( 0 = = ( cnt % 2 ) ) ; <nl> - / / Set new locale . <nl> - if ( use_locale ) { <nl> - FLATBUFFERS_ASSERT ( setlocale ( LC_ALL , OneTimeTestInit : : test_locale ( ) ) ) ; <nl> - } <nl> - <nl> - / / Check Parser . <nl> - parser . Parse ( parse_input ) ; <nl> - <nl> - / / Restore locale . <nl> - if ( use_locale ) { FLATBUFFERS_ASSERT ( setlocale ( LC_ALL , " C " ) ) ; } <nl> - } <nl> - <nl> + / / Check Parser . <nl> + parser . Parse ( parse_input ) ; <nl> + / / TODO : <nl> + / / Need to add additional checks for inputs passed Parse ( parse_input ) successfully : <nl> + / / 1 . Serialization to bfbs . <nl> + / / 2 . Generation of a default object . <nl> + / / 3 . Verification of the object using reflection . <nl> + / / 3 . Printing to json . <nl> return 0 ; <nl> } <nl> mmm a / tests / fuzzer / flatbuffers_scalar_fuzzer . cc <nl> ppp b / tests / fuzzer / flatbuffers_scalar_fuzzer . cc <nl> extern " C " int LLVMFuzzerTestOneInput ( const uint8_t * data , size_t size ) { <nl> const uint8_t flags = data [ 0 ] ; <nl> / / normalize to ascii alphabet <nl> const int extra_rep_number = <nl> - std : : max ( 5 , ( data [ 1 ] < ' 0 ' ? ( data [ 1 ] - ' 0 ' ) : 0 ) ) ; <nl> + std : : max ( 5 , ( data [ 1 ] > ' 0 ' ? ( data [ 1 ] - ' 0 ' ) : 0 ) ) ; <nl> data + = 2 ; <nl> size - = 2 ; / / bypass <nl> <nl> | [ fuzzer ] Fix mistakes in the ` parser ` and ` scalar ` fuzzers . ( ) | google/flatbuffers | bc7eb8adeb1ce73b13bacdf7a6904de27a1e5913 | 2020-12-07T19:47:33Z |
mmm a / tensorflow / contrib / lite / examples / ios / download_models . sh <nl> ppp b / tensorflow / contrib / lite / examples / ios / download_models . sh <nl> file $ { DOWNLOADS_DIR } / models <nl> <nl> cp $ { DOWNLOADS_DIR } / models / models / * simple / data / <nl> cp " $ { DOWNLOADS_DIR } / quantized_models / labels . txt " camera / data / <nl> - cp " $ { DOWNLOADS_DIR } / quantized_models / mobilenet_quant_v1_224 . tflite ' \ <nl> + cp " $ { DOWNLOADS_DIR } / quantized_models / mobilenet_quant_v1_224 . tflite " \ <nl> ' camera / data / mobilenet_v1_1 . 0_224 . tflite ' <nl> | Fix iOS examples download model script | tensorflow/tensorflow | 5fb63e97c0a7c85025f38c727a5355baf369fd62 | 2018-10-25T22:30:33Z |
mmm a / vendor / libchromiumcontent <nl> ppp b / vendor / libchromiumcontent <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit c810070b5c37d7e706e9f7bed7763992e3a42f23 <nl> + Subproject commit da5e68c0f85bc89a904135421536527081903428 <nl> | Update libcc ref | electron/electron | 24db18f34ec953704e5b6e5654eaa89725311cda | 2018-06-19T01:49:42Z |
mmm a / Source / SGDLib / SGD . cpp <nl> ppp b / Source / SGDLib / SGD . cpp <nl> void SGD < ElemType > : : TrainOrAdaptModel ( int startEpoch , ComputationNetworkPtr net , <nl> / / persist model and check - point info <nl> if ( ( g_mpi = = nullptr ) | | g_mpi - > IsMainNode ( ) ) <nl> { <nl> - net - > Save ( GetModelNameForEpoch ( i ) ) ; <nl> SaveCheckPointInfo ( i , totalSamplesSeen , learnRatePerSample , smoothedGradients , prevCriterion , chosenMinibatchSize ) ; <nl> + net - > Save ( GetModelNameForEpoch ( i ) ) ; <nl> if ( ! m_keepCheckPointFiles ) <nl> { <nl> / / delete previous checkpoint file to save space <nl> | Write checkpoint file before writing model file , so that a checkpoint file is guaranteed to exist for the latest successfully written model file | microsoft/CNTK | e9f5ca471b56928b3733b19afcc2389c221543c0 | 2016-02-09T00:12:05Z |
mmm a / hphp / hack / hhi / collections / Pair . hhi <nl> ppp b / hphp / hack / hhi / collections / Pair . hhi <nl> final class Pair < + Tv1 , + Tv2 > implements ConstVector < mixed > { <nl> * <nl> * Pairs must be constructed with " Pair { $ first , $ second } " . <nl> * / <nl> - < < __Rx , __MaybeMutable > > <nl> + < < __Rx > > <nl> private function __construct ( ) ; <nl> <nl> / * * <nl> mmm a / hphp / hack / src / parser / full_fidelity_parser_errors . ml <nl> ppp b / hphp / hack / src / parser / full_fidelity_parser_errors . ml <nl> let methodish_errors env node errors = <nl> then make_error_from_node node <nl> SyntaxError . mutability_annotation_on_static_method : : errors <nl> else errors in <nl> + let errors = <nl> + if String . lowercase method_name = SN . Members . __construct & & ( <nl> + attribute_specification_contains method_attrs SN . UserAttributes . uaMutable | | <nl> + attribute_specification_contains method_attrs SN . UserAttributes . uaMaybeMutable | | <nl> + attribute_specification_contains method_attrs SN . UserAttributes . uaMutableReturn <nl> + ) <nl> + then make_error_from_node node <nl> + SyntaxError . mutability_annotation_on_constructor : : errors <nl> + else errors in <nl> let fun_semicolon = md . methodish_semicolon in <nl> let errors = <nl> produce_error errors <nl> mmm a / hphp / hack / src / parser / full_fidelity_syntax_error . ml <nl> ppp b / hphp / hack / src / parser / full_fidelity_syntax_error . ml <nl> let invalid_await_position_dependent = <nl> let misplaced_reactivity_annotation = <nl> " Reactive annotations are not allowed on classes , interfaces or traits . " <nl> <nl> + let mutability_annotation_on_constructor = <nl> + " __Mutable , __MaybeMutable , and __MutableReturn annotations are not allowed on constructors . " <nl> + <nl> let mutability_annotation_on_static_method = <nl> " __Mutable and __MaybeMutable annotations are not allowed on static methods . " <nl> <nl> mmm a / hphp / hack / src / parser / full_fidelity_syntax_error . mli <nl> ppp b / hphp / hack / src / parser / full_fidelity_syntax_error . mli <nl> val static_closures_are_disabled : string <nl> val invalid_await_position : string <nl> val invalid_await_position_dependent : string <nl> val misplaced_reactivity_annotation : string <nl> + val mutability_annotation_on_constructor : string <nl> val mutability_annotation_on_static_method : string <nl> val mutability_annotation_on_inout_parameter : string <nl> val mutable_parameter_in_memoize_function : is_this : bool - > string <nl> new file mode 100644 <nl> index 00000000000 . . dbbe18821b4 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / reactive / mutable_on_constructor2 . php <nl> <nl> + < ? hh / / strict <nl> + <nl> + class A { <nl> + <nl> + < < __Rx , __MaybeMutable > > <nl> + public function ok ( ) : void { <nl> + } <nl> + <nl> + < < __Rx , __MaybeMutable > > <nl> + public function __construct ( int $ a ) { <nl> + } <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 7c47ee54d6a <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / reactive / mutable_on_constructor2 . php . exp <nl> <nl> + File " mutable_on_constructor2 . php " , line 9 , characters 3 - 69 : <nl> + __Mutable , __MaybeMutable , and __MutableReturn annotations are not allowed on constructors . ( Parsing [ 1002 ] ) <nl> mmm a / hphp / hack / test / typecheck / reactive / mutable_return1 . php <nl> ppp b / hphp / hack / test / typecheck / reactive / mutable_return1 . php <nl> <nl> < ? hh / / strict <nl> <nl> class A { <nl> - < < __Rx , __Mutable > > <nl> + < < __Rx > > <nl> public function __construct ( private int $ x ) { <nl> } <nl> < < __Rx , __MutableReturn > > <nl> mmm a / hphp / hack / test / typecheck / reactive / test_mutable_args3 . php <nl> ppp b / hphp / hack / test / typecheck / reactive / test_mutable_args3 . php <nl> <nl> < ? hh / / strict <nl> <nl> class Test { <nl> - < < __Rx , __Mutable > > <nl> + < < __Rx > > <nl> public function __construct ( public int $ val ) { } <nl> } <nl> <nl> | parser ban ( Maybe ) ? Mutable ( Return ) ? from ctor | facebook/hhvm | 73342e7d0e5398b1259a0246d5200ea8b3798e48 | 2019-06-18T19:11:15Z |
mmm a / stdlib / cmake / modules / AddSwiftStdlib . cmake <nl> ppp b / stdlib / cmake / modules / AddSwiftStdlib . cmake <nl> function ( add_swift_target_library name ) <nl> <nl> # Add PrivateFrameworks , rdar : / / 28466433 <nl> set ( swiftlib_c_compile_flags_all $ { SWIFTLIB_C_COMPILE_FLAGS } ) <nl> + set ( swiftlib_link_flags_all $ { SWIFTLIB_LINK_FLAGS } ) <nl> <nl> # Add flags to prepend framework search paths for the parallel framework <nl> # hierarchy rooted at / System / iOSSupport / . . . <nl> mmm a / stdlib / public / core / Misc . swift <nl> ppp b / stdlib / public / core / Misc . swift <nl> public func _getMangledTypeName ( _ type : Any . Type ) <nl> / / / Returns the mangled name for a given type . <nl> @ available ( macOS 9999 , iOS 9999 , tvOS 9999 , watchOS 9999 , * ) <nl> public / / SPI <nl> - func _mangledTypeName < T > ( _ type : T . Type ) - > String ? { <nl> + func _mangledTypeName ( _ type : Any . Type ) - > String ? { <nl> let ( stringPtr , count ) = _getMangledTypeName ( type ) <nl> guard count > 0 else { <nl> return nil <nl> mmm a / test / Runtime / demangleToMetadata . swift <nl> ppp b / test / Runtime / demangleToMetadata . swift <nl> if # available ( macOS 9999 , iOS 9999 , tvOS 9999 , watchOS 9999 , * ) { <nl> expectEqual ( " Int " , _typeName ( Int . self , qualified : false ) ) <nl> } <nl> } <nl> + <nl> + DemangleToMetadataTests . test ( " Check _mangledTypeName with Any . Type " ) { <nl> + let type : Any . Type = Int . self <nl> + expectEqual ( " Si " , _mangledTypeName ( type ) ) <nl> + } <nl> } <nl> <nl> <nl> | Merge remote - tracking branch ' origin / master ' into master - next | apple/swift | 0a38659f5e4662776502de9418434e145661df04 | 2020-04-07T04:48:57Z |
mmm a / cocos / 2d / CCParticleSystemQuad . cpp <nl> ppp b / cocos / 2d / CCParticleSystemQuad . cpp <nl> void ParticleSystemQuad : : initTexCoordsWithRect ( const Rect & pointRect ) <nl> quads [ i ] . tr . texCoords . v = top ; <nl> } <nl> } <nl> + <nl> + void ParticleSystemQuad : : updateTexCoords ( ) <nl> + { <nl> + if ( _texture ) <nl> + { <nl> + const Size & s = _texture - > getContentSize ( ) ; <nl> + initTexCoordsWithRect ( Rect ( 0 , 0 , s . width , s . height ) ) ; <nl> + } <nl> + } <nl> + <nl> void ParticleSystemQuad : : setTextureWithRect ( Texture2D * texture , const Rect & rect ) <nl> { <nl> / / Only update the texture if is different from the current one <nl> void ParticleSystemQuad : : setTextureWithRect ( Texture2D * texture , const Rect & rect <nl> <nl> this - > initTexCoordsWithRect ( rect ) ; <nl> } <nl> + <nl> void ParticleSystemQuad : : setTexture ( Texture2D * texture ) <nl> { <nl> const Size & s = texture - > getContentSize ( ) ; <nl> this - > setTextureWithRect ( texture , Rect ( 0 , 0 , s . width , s . height ) ) ; <nl> } <nl> + <nl> void ParticleSystemQuad : : setDisplayFrame ( SpriteFrame * spriteFrame ) <nl> { <nl> CCASSERT ( spriteFrame - > getOffsetInPixels ( ) . equals ( Point : : ZERO ) , <nl> void ParticleSystemQuad : : setTotalParticles ( int tp ) <nl> _indices = indicesNew ; <nl> <nl> / / Clear the memory <nl> - / / XXX : Bug ? If the quads are cleared , then drawing doesn ' t work . . . WHY ? ? ? XXX <nl> memset ( _particles , 0 , particlesSize ) ; <nl> memset ( _quads , 0 , quadsSize ) ; <nl> memset ( _indices , 0 , indicesSize ) ; <nl> - <nl> + <nl> _allocatedParticles = tp ; <nl> } <nl> else <nl> void ParticleSystemQuad : : setTotalParticles ( int tp ) <nl> { <nl> setupVBO ( ) ; <nl> } <nl> + <nl> + / / fixed http : / / www . cocos2d - x . org / issues / 3990 <nl> + / / Updates texture coords . <nl> + updateTexCoords ( ) ; <nl> } <nl> else <nl> { <nl> _totalParticles = tp ; <nl> } <nl> <nl> + _emissionRate = _totalParticles / _life ; <nl> resetSystem ( ) ; <nl> } <nl> <nl> mmm a / cocos / 2d / CCParticleSystemQuad . h <nl> ppp b / cocos / 2d / CCParticleSystemQuad . h <nl> class CC_DLL ParticleSystemQuad : public ParticleSystem <nl> / * * initializes the texture with a rectangle measured Points * / <nl> void initTexCoordsWithRect ( const Rect & rect ) ; <nl> <nl> + / * * Updates texture coords * / <nl> + void updateTexCoords ( ) ; <nl> + <nl> / / Overrides <nl> / * * <nl> * @ js NA <nl> mmm a / tests / test - cpp / Classes / ParticleTest / ParticleTest . cpp <nl> ppp b / tests / test - cpp / Classes / ParticleTest / ParticleTest . cpp <nl> enum <nl> <nl> static int sceneIdx = - 1 ; <nl> <nl> - # define MAX_LAYER 44 <nl> + # define MAX_LAYER 45 <nl> <nl> Layer * createParticleLayer ( int nIndex ) <nl> { <nl> Layer * createParticleLayer ( int nIndex ) <nl> case 41 : return new ReorderParticleSystems ( ) ; <nl> case 42 : return new PremultipliedAlphaTest ( ) ; <nl> case 43 : return new PremultipliedAlphaTest2 ( ) ; <nl> + case 44 : return new Issue3990 ( ) ; <nl> default : <nl> break ; <nl> } <nl> std : : string PremultipliedAlphaTest2 : : subtitle ( ) const <nl> return " Arrows should be faded " ; <nl> } <nl> <nl> + <nl> + / / Issue3990 <nl> + <nl> + void Issue3990 : : onEnter ( ) <nl> + { <nl> + ParticleDemo : : onEnter ( ) ; <nl> + <nl> + _color - > setColor ( Color3B : : BLACK ) ; <nl> + this - > removeChild ( _background , true ) ; <nl> + _background = NULL ; <nl> + <nl> + _emitter = ParticleSystemQuad : : create ( " Particles / Spiral . plist " ) ; <nl> + <nl> + _emitter - > setPositionType ( ParticleSystem : : PositionType : : GROUPED ) ; <nl> + _emitter - > setTotalParticles ( 1000 ) ; <nl> + <nl> + _emitter - > setPosition ( VisibleRect : : center ( ) ) ; <nl> + <nl> + _emitter - > retain ( ) ; <nl> + this - > addChild ( _emitter , 10 ) ; <nl> + } <nl> + <nl> + std : : string Issue3990 : : title ( ) const <nl> + { <nl> + return " Issue3990 , setTotalParticle should work " ; <nl> + } <nl> + <nl> + std : : string Issue3990 : : subtitle ( ) const <nl> + { <nl> + return " Show ' 998 ' or ' 999 ' at bottom right side " ; <nl> + } <nl> + <nl> + / / <nl> void ParticleTestScene : : runThisTest ( ) <nl> { <nl> addChild ( nextParticleAction ( ) ) ; <nl> <nl> Director : : getInstance ( ) - > replaceScene ( this ) ; <nl> } <nl> + <nl> mmm a / tests / test - cpp / Classes / ParticleTest / ParticleTest . h <nl> ppp b / tests / test - cpp / Classes / ParticleTest / ParticleTest . h <nl> class Issue704 : public ParticleDemo <nl> class Issue870 : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> void updateQuads ( float dt ) ; <nl> class Issue870 : public ParticleDemo <nl> class Issue1201 : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> } ; <nl> class Issue1201 : public ParticleDemo <nl> class ParticleBatchHybrid : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> void switchRender ( float dt ) ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> class ParticleBatchHybrid : public ParticleDemo <nl> class ParticleBatchMultipleEmitters : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> } ; <nl> class ParticleBatchMultipleEmitters : public ParticleDemo <nl> class ParticleReorder : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> void reorderParticles ( float dt ) ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> class ParticleReorder : public ParticleDemo <nl> class MultipleParticleSystems : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> virtual void update ( float dt ) ; <nl> class MultipleParticleSystems : public ParticleDemo <nl> class MultipleParticleSystemsBatched : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> - virtual void update ( float dt ) ; <nl> + virtual void onEnter ( ) override ; <nl> + virtual void update ( float dt ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> private : <nl> class MultipleParticleSystemsBatched : public ParticleDemo <nl> class AddAndDeleteParticleSystems : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> - virtual void update ( float dt ) ; <nl> + virtual void onEnter ( ) override ; <nl> + virtual void update ( float dt ) override ; <nl> void removeSystem ( float dt ) ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> class AddAndDeleteParticleSystems : public ParticleDemo <nl> class ReorderParticleSystems : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> void reorderSystem ( float time ) ; <nl> - virtual void update ( float dt ) ; <nl> + virtual void update ( float dt ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> private : <nl> class ReorderParticleSystems : public ParticleDemo <nl> class PremultipliedAlphaTest : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> } ; <nl> class PremultipliedAlphaTest : public ParticleDemo <nl> class PremultipliedAlphaTest2 : public ParticleDemo <nl> { <nl> public : <nl> - virtual void onEnter ( ) ; <nl> + virtual void onEnter ( ) override ; <nl> + virtual std : : string title ( ) const override ; <nl> + virtual std : : string subtitle ( ) const override ; <nl> + } ; <nl> + <nl> + class Issue3990 : public ParticleDemo <nl> + { <nl> + public : <nl> + virtual void onEnter ( ) override ; <nl> virtual std : : string title ( ) const override ; <nl> virtual std : : string subtitle ( ) const override ; <nl> } ; <nl> | Merge pull request from dumganhar / iss3990 - particle | cocos2d/cocos2d-x | 4ca47b3e5fcd497f749f326d6e75c5b74aa49731 | 2014-02-13T09:03:52Z |
mmm a / language / English / strings . xml <nl> ppp b / language / English / strings . xml <nl> <nl> < string id = " 1034 " > Submenu < / string > <nl> < string id = " 1035 " > Enable submenu buttons < / string > <nl> < string id = " 1036 " > Favourites < / string > <nl> - < string id = " 1037 " > Video plugins < / string > <nl> - < string id = " 1038 " > Music plugins < / string > <nl> - < string id = " 1039 " > Picture plugins < / string > <nl> + < string id = " 1037 " > Video Add - ons < / string > <nl> + < string id = " 1038 " > Music Add - ons < / string > <nl> + < string id = " 1039 " > Picture Add - ons < / string > <nl> < string id = " 1040 " > Loading directory < / string > <nl> < string id = " 1041 " > Retrieved % i items < / string > <nl> < string id = " 1042 " > Retrieved % i of % i items < / string > <nl> - < string id = " 1043 " > Program plugins < / string > <nl> + < string id = " 1043 " > Program Add - ons < / string > <nl> < string id = " 1044 " > Set plugin thumb < / string > <nl> < string id = " 1045 " > Plugin settings < / string > <nl> < string id = " 1046 " > Access points < / string > <nl> mmm a / xbmc / FileSystem / AddonsDirectory . cpp <nl> ppp b / xbmc / FileSystem / AddonsDirectory . cpp <nl> <nl> # include " DirectoryCache . h " <nl> # include " FileItem . h " <nl> # include " addons / Repository . h " <nl> + # include " addons / PluginSource . h " <nl> # include " StringUtils . h " <nl> <nl> using namespace ADDON ; <nl> bool CAddonsDirectory : : GetDirectory ( const CStdString & strPath , CFileItemList & it <nl> { <nl> CAddonMgr : : Get ( ) . GetAddons ( ADDON_REPOSITORY , addons , true ) ; <nl> } <nl> + else if ( path . GetHostName ( ) . Equals ( " sources " ) ) <nl> + { <nl> + return GetScriptsAndPlugins ( path . GetFileName ( ) , items ) ; <nl> + } <nl> else if ( path . GetHostName ( ) . Equals ( " all " ) ) <nl> { <nl> CAddonDatabase database ; <nl> CFileItemPtr CAddonsDirectory : : FileItemFromAddon ( AddonPtr & addon , const CStdStri <nl> item - > SetLabel ( addon - > Name ( ) ) ; <nl> item - > SetLabel2 ( addon - > Summary ( ) ) ; <nl> item - > SetThumbnailImage ( addon - > Icon ( ) ) ; <nl> - item - > SetIconImage ( " DefaultAddon . png " ) ; <nl> + item - > SetIconImage ( " DefaultAddon . png " ) ; <nl> item - > SetProperty ( " fanart_image " , addon - > FanArt ( ) ) ; <nl> CAddonDatabase : : SetPropertiesFromAddon ( addon , item ) ; <nl> return item ; <nl> } <nl> <nl> + bool CAddonsDirectory : : GetScriptsAndPlugins ( const CStdString & content , CFileItemList & items ) <nl> + { <nl> + items . Clear ( ) ; <nl> + <nl> + CPluginSource : : Content type = CPluginSource : : Translate ( content ) ; <nl> + if ( type = = CPluginSource : : UNKNOWN ) <nl> + return false ; <nl> + <nl> + VECADDONS addons ; <nl> + CAddonMgr : : Get ( ) . GetAddons ( ADDON_PLUGIN , addons ) ; <nl> + for ( unsigned i = 0 ; i < addons . size ( ) ; i + + ) <nl> + { <nl> + PluginPtr plugin = boost : : dynamic_pointer_cast < CPluginSource > ( addons [ i ] ) ; <nl> + if ( ! plugin | | ! plugin - > Provides ( type ) ) <nl> + continue ; <nl> + items . Add ( FileItemFromAddon ( addons [ i ] , " plugin : / / " , true ) ) ; <nl> + } <nl> + <nl> + addons . clear ( ) ; <nl> + CAddonMgr : : Get ( ) . GetAddons ( ADDON_SCRIPT , addons ) ; <nl> + for ( unsigned i = 0 ; i < addons . size ( ) ; i + + ) <nl> + { <nl> + PluginPtr plugin = boost : : dynamic_pointer_cast < CPluginSource > ( addons [ i ] ) ; <nl> + if ( ! plugin | | ! plugin - > Provides ( type ) ) <nl> + continue ; <nl> + items . Add ( FileItemFromAddon ( addons [ i ] , " script : / / " , false ) ) ; <nl> + } <nl> + return items . Size ( ) > 0 ; <nl> + } <nl> + <nl> } <nl> <nl> mmm a / xbmc / FileSystem / AddonsDirectory . h <nl> ppp b / xbmc / FileSystem / AddonsDirectory . h <nl> namespace XFILE <nl> virtual bool Create ( const char * strPath ) { return true ; } <nl> virtual bool Exists ( const char * strPath ) { return true ; } <nl> <nl> + / * ! \ brief Fetch scripts and plugins of a given content type <nl> + \ param content the content type to fetch <nl> + \ param items the list to fill with scripts and content <nl> + \ return true if more than one item is found , false otherwise . <nl> + * / <nl> + static bool GetScriptsAndPlugins ( const CStdString & content , CFileItemList & items ) ; <nl> static void GenerateListing ( CURL & path , ADDON : : VECADDONS & addons , CFileItemList & items ) ; <nl> static CFileItemPtr FileItemFromAddon ( ADDON : : AddonPtr & addon , const CStdString & basePath , bool folder = false ) ; <nl> } ; <nl> mmm a / xbmc / GUIViewState . cpp <nl> ppp b / xbmc / GUIViewState . cpp <nl> <nl> # include " Settings . h " <nl> # include " FileItem . h " <nl> # include " Key . h " <nl> + # include " FileSystem / AddonsDirectory . h " <nl> <nl> using namespace std ; <nl> <nl> CGUIViewState * CGUIViewState : : GetViewState ( int windowId , const CFileItemList & it <nl> return new CGUIViewStateGeneral ( items ) ; <nl> } <nl> <nl> - CGUIViewState : : CGUIViewState ( const CFileItemList & items , const CPluginSource : : Content & content / * = CONTENT_NONE * / ) : m_items ( items ) <nl> + CGUIViewState : : CGUIViewState ( const CFileItemList & items ) : m_items ( items ) <nl> { <nl> m_currentViewAsControl = 0 ; <nl> m_currentSortMethod = 0 ; <nl> m_sortOrder = SORT_ORDER_ASC ; <nl> - m_content = content ; <nl> } <nl> <nl> CGUIViewState : : ~ CGUIViewState ( ) <nl> CStdString CGUIViewState : : GetExtensions ( ) <nl> return " " ; <nl> } <nl> <nl> - CMediaSource SourceFromPlugin ( const PluginPtr & plugin , const CStdString & type ) <nl> + VECSOURCES & CGUIViewState : : GetSources ( ) <nl> { <nl> - / / format for sources ' s path is <nl> - / / eg . type : / / id <nl> - CMediaSource source ; <nl> - CURL path ; <nl> - path . SetProtocol ( type ) ; <nl> - path . SetHostName ( plugin - > ID ( ) ) ; <nl> - source . strPath = path . Get ( ) ; <nl> - source . strName = plugin - > Name ( ) ; <nl> - source . m_strThumbnailImage = plugin - > Icon ( ) ; <nl> - source . m_iDriveType = CMediaSource : : SOURCE_TYPE_REMOTE ; <nl> - return source ; <nl> + return m_sources ; <nl> } <nl> <nl> - VECSOURCES & CGUIViewState : : GetSources ( ) <nl> + void CGUIViewState : : AddAddonsSource ( const CStdString & content , const CStdString & label ) <nl> { <nl> - / / more consolidation could happen here for all content types <nl> - / / - playlists , autoconfig network shares , whatnot <nl> - <nl> - VECADDONS addons ; <nl> - ADDON : : CAddonMgr : : Get ( ) . GetAddons ( ADDON_PLUGIN , addons ) ; <nl> - <nl> - for ( unsigned i = 0 ; i < addons . size ( ) ; i + + ) <nl> - { <nl> - PluginPtr plugin = boost : : dynamic_pointer_cast < CPluginSource > ( addons [ i ] ) ; <nl> - if ( ! plugin | | ! plugin - > Provides ( m_content ) ) <nl> - continue ; <nl> - m_sources . push_back ( SourceFromPlugin ( plugin , " plugin " ) ) ; <nl> + CFileItemList items ; <nl> + if ( XFILE : : CAddonsDirectory : : GetScriptsAndPlugins ( content , items ) ) <nl> + { / / add the plugin source <nl> + CMediaSource source ; <nl> + source . strPath = " addons : / / sources / " + content + " / " ; <nl> + source . strName = label ; <nl> + source . m_strThumbnailImage = " " ; <nl> + source . m_iDriveType = CMediaSource : : SOURCE_TYPE_REMOTE ; <nl> + m_sources . push_back ( source ) ; <nl> } <nl> - <nl> - addons . clear ( ) ; <nl> - ADDON : : CAddonMgr : : Get ( ) . GetAddons ( ADDON_SCRIPT , addons ) ; <nl> - for ( unsigned i = 0 ; i < addons . size ( ) ; i + + ) <nl> - { <nl> - PluginPtr plugin = boost : : dynamic_pointer_cast < CPluginSource > ( addons [ i ] ) ; <nl> - if ( ! plugin | | ! plugin - > Provides ( m_content ) ) <nl> - continue ; <nl> - m_sources . push_back ( SourceFromPlugin ( plugin , " script " ) ) ; <nl> - } <nl> - <nl> - return m_sources ; <nl> } <nl> <nl> CGUIViewStateGeneral : : CGUIViewStateGeneral ( const CFileItemList & items ) : CGUIViewState ( items ) <nl> mmm a / xbmc / GUIViewState . h <nl> ppp b / xbmc / GUIViewState . h <nl> <nl> # include " SortFileItem . h " <nl> # include " GUIBaseContainer . h " <nl> # include " MediaSource . h " <nl> - # include " addons / PluginSource . h " <nl> <nl> class CViewState ; / / forward <nl> class CFileItemList ; <nl> class CGUIViewState <nl> virtual VECSOURCES & GetSources ( ) ; <nl> <nl> protected : <nl> - CGUIViewState ( const CFileItemList & items , const ADDON : : CPluginSource : : Content & content = ADDON : : CPluginSource : : UNKNOWN ) ; / / no direct object creation , use GetViewState ( ) <nl> + CGUIViewState ( const CFileItemList & items ) ; / / no direct object creation , use GetViewState ( ) <nl> virtual void SaveViewState ( ) = 0 ; <nl> virtual void SaveViewToDb ( const CStdString & path , int windowID , CViewState * viewState = NULL ) ; <nl> void LoadViewState ( const CStdString & path , int windowID ) ; <nl> + <nl> + / * ! \ brief Add the addons source for the given content type , if the user has suitable addons <nl> + \ param content the type of addon content desired <nl> + \ param label the name of the addons source <nl> + * / <nl> + void AddAddonsSource ( const CStdString & content , const CStdString & label ) ; <nl> <nl> void AddSortMethod ( SORT_METHOD sortMethod , int buttonLabel , LABEL_MASKS labelmasks ) ; <nl> void SetSortMethod ( SORT_METHOD sortMethod ) ; <nl> class CGUIViewState <nl> const CFileItemList & m_items ; <nl> <nl> static VECSOURCES m_sources ; <nl> - ADDON : : CPluginSource : : Content m_content ; <nl> <nl> int m_currentViewAsControl ; <nl> <nl> mmm a / xbmc / GUIViewStateMusic . cpp <nl> ppp b / xbmc / GUIViewStateMusic . cpp <nl> CStdString CGUIViewStateWindowMusic : : GetExtensions ( ) <nl> return g_settings . m_musicExtensions ; <nl> } <nl> <nl> + VECSOURCES & CGUIViewStateWindowMusic : : GetSources ( ) <nl> + { <nl> + AddAddonsSource ( " audio " , g_localizeStrings . Get ( 1038 ) ) ; <nl> + return CGUIViewState : : GetSources ( ) ; <nl> + } <nl> + <nl> CGUIViewStateMusicSearch : : CGUIViewStateMusicSearch ( const CFileItemList & items ) : CGUIViewStateWindowMusic ( items ) <nl> { <nl> CStdString strTrackLeft = g_guiSettings . GetString ( " musicfiles . librarytrackformat " ) ; <nl> void CGUIViewStateWindowMusicSongs : : SaveViewState ( ) <nl> <nl> VECSOURCES & CGUIViewStateWindowMusicSongs : : GetSources ( ) <nl> { <nl> - AddOrReplace ( g_settings . m_musicSources , CGUIViewState : : GetSources ( ) ) ; <nl> + AddOrReplace ( g_settings . m_musicSources , CGUIViewStateWindowMusic : : GetSources ( ) ) ; <nl> return g_settings . m_musicSources ; <nl> } <nl> <nl> mmm a / xbmc / GUIViewStateMusic . h <nl> ppp b / xbmc / GUIViewStateMusic . h <nl> <nl> <nl> # include " GUIViewState . h " <nl> <nl> - using namespace ADDON ; <nl> - <nl> class CGUIViewStateWindowMusic : public CGUIViewState <nl> { <nl> public : <nl> - CGUIViewStateWindowMusic ( const CFileItemList & items ) : CGUIViewState ( items , CPluginSource : : AUDIO ) { } <nl> + CGUIViewStateWindowMusic ( const CFileItemList & items ) : CGUIViewState ( items ) { } <nl> protected : <nl> + virtual VECSOURCES & GetSources ( ) ; <nl> virtual int GetPlaylist ( ) ; <nl> virtual bool AutoPlayNextItem ( ) ; <nl> virtual CStdString GetLockType ( ) ; <nl> mmm a / xbmc / GUIViewStatePictures . cpp <nl> ppp b / xbmc / GUIViewStatePictures . cpp <nl> <nl> using namespace XFILE ; <nl> using namespace ADDON ; <nl> <nl> - CGUIViewStateWindowPictures : : CGUIViewStateWindowPictures ( const CFileItemList & items ) : CGUIViewState ( items , CPluginSource : : IMAGE ) <nl> + CGUIViewStateWindowPictures : : CGUIViewStateWindowPictures ( const CFileItemList & items ) : CGUIViewState ( items ) <nl> { <nl> if ( items . IsVirtualDirectoryRoot ( ) ) <nl> { <nl> CStdString CGUIViewStateWindowPictures : : GetExtensions ( ) <nl> <nl> VECSOURCES & CGUIViewStateWindowPictures : : GetSources ( ) <nl> { <nl> + AddAddonsSource ( " image " , g_localizeStrings . Get ( 1039 ) ) ; <nl> AddOrReplace ( g_settings . m_pictureSources , CGUIViewState : : GetSources ( ) ) ; <nl> return g_settings . m_pictureSources ; <nl> } <nl> mmm a / xbmc / GUIViewStatePrograms . cpp <nl> ppp b / xbmc / GUIViewStatePrograms . cpp <nl> <nl> using namespace XFILE ; <nl> using namespace ADDON ; <nl> <nl> - CGUIViewStateWindowPrograms : : CGUIViewStateWindowPrograms ( const CFileItemList & items ) : CGUIViewState ( items , CPluginSource : : EXECUTABLE ) <nl> + CGUIViewStateWindowPrograms : : CGUIViewStateWindowPrograms ( const CFileItemList & items ) : CGUIViewState ( items ) <nl> { <nl> if ( g_guiSettings . GetBool ( " filelists . ignorethewhensorting " ) ) <nl> AddSortMethod ( SORT_METHOD_LABEL_IGNORE_THE , 551 , LABEL_MASKS ( " % K " , " % I " , " % L " , " " ) ) ; / / Titel , Size | Foldername , empty <nl> CStdString CGUIViewStateWindowPrograms : : GetExtensions ( ) <nl> <nl> VECSOURCES & CGUIViewStateWindowPrograms : : GetSources ( ) <nl> { <nl> + AddAddonsSource ( " executable " , g_localizeStrings . Get ( 1043 ) ) ; <nl> AddOrReplace ( g_settings . m_programSources , CGUIViewState : : GetSources ( ) ) ; <nl> return g_settings . m_programSources ; <nl> } <nl> mmm a / xbmc / GUIViewStateVideo . cpp <nl> ppp b / xbmc / GUIViewStateVideo . cpp <nl> int CGUIViewStateWindowVideo : : GetPlaylist ( ) <nl> return PLAYLIST_VIDEO ; <nl> } <nl> <nl> + VECSOURCES & CGUIViewStateWindowVideo : : GetSources ( ) <nl> + { <nl> + AddAddonsSource ( " video " , g_localizeStrings . Get ( 1037 ) ) ; <nl> + return CGUIViewState : : GetSources ( ) ; <nl> + } <nl> + <nl> CGUIViewStateWindowVideoFiles : : CGUIViewStateWindowVideoFiles ( const CFileItemList & items ) : CGUIViewStateWindowVideo ( items ) <nl> { <nl> if ( items . IsVirtualDirectoryRoot ( ) ) <nl> void CGUIViewStateWindowVideoFiles : : SaveViewState ( ) <nl> <nl> VECSOURCES & CGUIViewStateWindowVideoFiles : : GetSources ( ) <nl> { <nl> - AddOrReplace ( g_settings . m_videoSources , CGUIViewState : : GetSources ( ) ) ; <nl> + AddOrReplace ( g_settings . m_videoSources , CGUIViewStateWindowVideo : : GetSources ( ) ) ; <nl> return g_settings . m_videoSources ; <nl> } <nl> <nl> mmm a / xbmc / GUIViewStateVideo . h <nl> ppp b / xbmc / GUIViewStateVideo . h <nl> <nl> <nl> # include " GUIViewState . h " <nl> <nl> - using namespace ADDON ; <nl> - <nl> class CGUIViewStateWindowVideo : public CGUIViewState <nl> { <nl> public : <nl> - CGUIViewStateWindowVideo ( const CFileItemList & items ) : CGUIViewState ( items , CPluginSource : : VIDEO ) { } <nl> + CGUIViewStateWindowVideo ( const CFileItemList & items ) : CGUIViewState ( items ) { } <nl> <nl> protected : <nl> + virtual VECSOURCES & GetSources ( ) ; <nl> virtual CStdString GetLockType ( ) ; <nl> virtual int GetPlaylist ( ) ; <nl> virtual CStdString GetExtensions ( ) ; <nl> mmm a / xbmc / addons / PluginSource . h <nl> ppp b / xbmc / addons / PluginSource . h <nl> class CPluginSource : public CAddon <nl> bool Provides ( const Content & content ) { <nl> return content = = UNKNOWN ? false : m_providedContent . count ( content ) > 0 ; } <nl> <nl> + static Content Translate ( const CStdString & content ) ; <nl> private : <nl> std : : set < Content > m_providedContent ; <nl> - static Content Translate ( const CStdString & content ) ; <nl> } ; <nl> <nl> } / * namespace ADDON * / <nl> | changed : Switch back to a separate node / folder for addons in media views | xbmc/xbmc | d0435f632e77c859dcbba806afefbcac211004e7 | 2010-06-19T10:27:19Z |
mmm a / dbms / src / Client / Connection . cpp <nl> ppp b / dbms / src / Client / Connection . cpp <nl> Block Connection : : receiveData ( ) <nl> <nl> String Connection : : getServerAddress ( ) const <nl> { <nl> - std : : stringstream s ; <nl> - / / / Для IPv6 адресов будет не хватать квадратных скобочек , но это не важно . <nl> - s < < host < < ' : ' < < port ; <nl> - return s . str ( ) ; <nl> + return Poco : : Net : : SocketAddress ( host , port ) . toString ( ) ; <nl> } <nl> <nl> <nl> | dbms : reverted prev . modification [ # CONV - 2944 ] . | ClickHouse/ClickHouse | fdd6df2095a67d38fc23d534749b4553c102260f | 2012-10-12T18:37:25Z |
mmm a / src / builtins / builtins - definitions . h <nl> ppp b / src / builtins / builtins - definitions . h <nl> namespace internal { <nl> ASM ( WasmCompileLazy , Dummy ) \ <nl> ASM ( WasmDebugBreak , Dummy ) \ <nl> TFC ( WasmAtomicNotify , WasmAtomicNotify ) \ <nl> - TFC ( WasmI32AtomicWait , WasmI32AtomicWait ) \ <nl> - TFC ( WasmI64AtomicWait , WasmI64AtomicWait ) \ <nl> + TFC ( WasmI32AtomicWait32 , WasmI32AtomicWait32 ) \ <nl> + TFC ( WasmI32AtomicWait64 , WasmI32AtomicWait64 ) \ <nl> + TFC ( WasmI64AtomicWait32 , WasmI64AtomicWait32 ) \ <nl> + TFC ( WasmI64AtomicWait64 , WasmI64AtomicWait64 ) \ <nl> TFC ( WasmMemoryGrow , WasmMemoryGrow ) \ <nl> TFC ( WasmTableGet , WasmTableGet ) \ <nl> TFC ( WasmTableSet , WasmTableSet ) \ <nl> mmm a / src / builtins / builtins - wasm - gen . cc <nl> ppp b / src / builtins / builtins - wasm - gen . cc <nl> TF_BUILTIN ( WasmAtomicNotify , WasmBuiltinsAssembler ) { <nl> Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> } <nl> <nl> - TF_BUILTIN ( WasmI32AtomicWait , WasmBuiltinsAssembler ) { <nl> + TF_BUILTIN ( WasmI32AtomicWait32 , WasmBuiltinsAssembler ) { <nl> + if ( ! Is32 ( ) ) { <nl> + Unreachable ( ) ; <nl> + return ; <nl> + } <nl> + <nl> TNode < Uint32T > address = <nl> UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kAddress ) ) ; <nl> + TNode < Number > address_number = ChangeUint32ToTagged ( address ) ; <nl> + <nl> TNode < Int32T > expected_value = <nl> UncheckedCast < Int32T > ( Parameter ( Descriptor : : kExpectedValue ) ) ; <nl> - TNode < Float64T > timeout = <nl> - UncheckedCast < Float64T > ( Parameter ( Descriptor : : kTimeout ) ) ; <nl> + TNode < Number > expected_value_number = ChangeInt32ToTagged ( expected_value ) ; <nl> + <nl> + TNode < IntPtrT > timeout_low = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeoutLow ) ) ; <nl> + TNode < IntPtrT > timeout_high = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeoutHigh ) ) ; <nl> + TNode < BigInt > timeout = BigIntFromInt32Pair ( timeout_low , timeout_high ) ; <nl> <nl> TNode < WasmInstanceObject > instance = LoadInstanceFromFrame ( ) ; <nl> + TNode < Context > context = LoadContextFromInstance ( instance ) ; <nl> + <nl> + TNode < Smi > result_smi = <nl> + CAST ( CallRuntime ( Runtime : : kWasmI32AtomicWait , context , instance , <nl> + address_number , expected_value_number , timeout ) ) ; <nl> + Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> + } <nl> + <nl> + TF_BUILTIN ( WasmI32AtomicWait64 , WasmBuiltinsAssembler ) { <nl> + if ( ! Is64 ( ) ) { <nl> + Unreachable ( ) ; <nl> + return ; <nl> + } <nl> + <nl> + TNode < Uint32T > address = <nl> + UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kAddress ) ) ; <nl> TNode < Number > address_number = ChangeUint32ToTagged ( address ) ; <nl> + <nl> + TNode < Int32T > expected_value = <nl> + UncheckedCast < Int32T > ( Parameter ( Descriptor : : kExpectedValue ) ) ; <nl> TNode < Number > expected_value_number = ChangeInt32ToTagged ( expected_value ) ; <nl> - TNode < Number > timeout_number = ChangeFloat64ToTagged ( timeout ) ; <nl> + <nl> + TNode < IntPtrT > timeout_raw = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeout ) ) ; <nl> + TNode < BigInt > timeout = BigIntFromInt64 ( timeout_raw ) ; <nl> + <nl> + TNode < WasmInstanceObject > instance = LoadInstanceFromFrame ( ) ; <nl> TNode < Context > context = LoadContextFromInstance ( instance ) ; <nl> <nl> TNode < Smi > result_smi = <nl> CAST ( CallRuntime ( Runtime : : kWasmI32AtomicWait , context , instance , <nl> - address_number , expected_value_number , timeout_number ) ) ; <nl> + address_number , expected_value_number , timeout ) ) ; <nl> Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> } <nl> <nl> - TF_BUILTIN ( WasmI64AtomicWait , WasmBuiltinsAssembler ) { <nl> + TF_BUILTIN ( WasmI64AtomicWait32 , WasmBuiltinsAssembler ) { <nl> + if ( ! Is32 ( ) ) { <nl> + Unreachable ( ) ; <nl> + return ; <nl> + } <nl> + <nl> TNode < Uint32T > address = <nl> UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kAddress ) ) ; <nl> - TNode < Uint32T > expected_value_high = <nl> - UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kExpectedValueHigh ) ) ; <nl> - TNode < Uint32T > expected_value_low = <nl> - UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kExpectedValueLow ) ) ; <nl> - TNode < Float64T > timeout = <nl> - UncheckedCast < Float64T > ( Parameter ( Descriptor : : kTimeout ) ) ; <nl> + TNode < Number > address_number = ChangeUint32ToTagged ( address ) ; <nl> + <nl> + TNode < IntPtrT > expected_value_low = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kExpectedValueLow ) ) ; <nl> + TNode < IntPtrT > expected_value_high = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kExpectedValueHigh ) ) ; <nl> + TNode < BigInt > expected_value = <nl> + BigIntFromInt32Pair ( expected_value_low , expected_value_high ) ; <nl> + <nl> + TNode < IntPtrT > timeout_low = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeoutLow ) ) ; <nl> + TNode < IntPtrT > timeout_high = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeoutHigh ) ) ; <nl> + TNode < BigInt > timeout = BigIntFromInt32Pair ( timeout_low , timeout_high ) ; <nl> <nl> TNode < WasmInstanceObject > instance = LoadInstanceFromFrame ( ) ; <nl> + TNode < Context > context = LoadContextFromInstance ( instance ) ; <nl> + <nl> + TNode < Smi > result_smi = <nl> + CAST ( CallRuntime ( Runtime : : kWasmI64AtomicWait , context , instance , <nl> + address_number , expected_value , timeout ) ) ; <nl> + Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> + } <nl> + <nl> + TF_BUILTIN ( WasmI64AtomicWait64 , WasmBuiltinsAssembler ) { <nl> + if ( ! Is64 ( ) ) { <nl> + Unreachable ( ) ; <nl> + return ; <nl> + } <nl> + <nl> + TNode < Uint32T > address = <nl> + UncheckedCast < Uint32T > ( Parameter ( Descriptor : : kAddress ) ) ; <nl> TNode < Number > address_number = ChangeUint32ToTagged ( address ) ; <nl> - TNode < Number > expected_value_high_number = <nl> - ChangeUint32ToTagged ( expected_value_high ) ; <nl> - TNode < Number > expected_value_low_number = <nl> - ChangeUint32ToTagged ( expected_value_low ) ; <nl> - TNode < Number > timeout_number = ChangeFloat64ToTagged ( timeout ) ; <nl> + <nl> + TNode < IntPtrT > expected_value_raw = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kExpectedValue ) ) ; <nl> + TNode < BigInt > expected_value = BigIntFromInt64 ( expected_value_raw ) ; <nl> + <nl> + TNode < IntPtrT > timeout_raw = <nl> + UncheckedCast < IntPtrT > ( Parameter ( Descriptor : : kTimeout ) ) ; <nl> + TNode < BigInt > timeout = BigIntFromInt64 ( timeout_raw ) ; <nl> + <nl> + TNode < WasmInstanceObject > instance = LoadInstanceFromFrame ( ) ; <nl> TNode < Context > context = LoadContextFromInstance ( instance ) ; <nl> <nl> - TNode < Smi > result_smi = CAST ( CallRuntime ( <nl> - Runtime : : kWasmI64AtomicWait , context , instance , address_number , <nl> - expected_value_high_number , expected_value_low_number , timeout_number ) ) ; <nl> + TNode < Smi > result_smi = <nl> + CAST ( CallRuntime ( Runtime : : kWasmI64AtomicWait , context , instance , <nl> + address_number , expected_value , timeout ) ) ; <nl> Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> } <nl> <nl> mmm a / src / codegen / interface - descriptors . cc <nl> ppp b / src / codegen / interface - descriptors . cc <nl> void WasmAtomicNotifyDescriptor : : InitializePlatformSpecific ( <nl> } <nl> <nl> # if ! defined ( V8_TARGET_ARCH_MIPS ) & & ! defined ( V8_TARGET_ARCH_MIPS64 ) <nl> - void WasmI32AtomicWaitDescriptor : : InitializePlatformSpecific ( <nl> + void WasmI32AtomicWait32Descriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> DefaultInitializePlatformSpecific ( data , kParameterCount ) ; <nl> } <nl> <nl> - void WasmI64AtomicWaitDescriptor : : InitializePlatformSpecific ( <nl> + void WasmI32AtomicWait64Descriptor : : InitializePlatformSpecific ( <nl> + CallInterfaceDescriptorData * data ) { <nl> + DefaultInitializePlatformSpecific ( data , kParameterCount ) ; <nl> + } <nl> + <nl> + void WasmI64AtomicWait32Descriptor : : InitializePlatformSpecific ( <nl> + CallInterfaceDescriptorData * data ) { <nl> + DefaultInitializePlatformSpecific ( data , <nl> + kParameterCount - kStackArgumentsCount ) ; <nl> + } <nl> + <nl> + void WasmI64AtomicWait64Descriptor : : InitializePlatformSpecific ( <nl> CallInterfaceDescriptorData * data ) { <nl> DefaultInitializePlatformSpecific ( data , kParameterCount ) ; <nl> } <nl> mmm a / src / codegen / interface - descriptors . h <nl> ppp b / src / codegen / interface - descriptors . h <nl> namespace internal { <nl> V ( Typeof ) \ <nl> V ( Void ) \ <nl> V ( WasmAtomicNotify ) \ <nl> - V ( WasmI32AtomicWait ) \ <nl> - V ( WasmI64AtomicWait ) \ <nl> + V ( WasmI32AtomicWait32 ) \ <nl> + V ( WasmI32AtomicWait64 ) \ <nl> + V ( WasmI64AtomicWait32 ) \ <nl> + V ( WasmI64AtomicWait64 ) \ <nl> V ( WasmMemoryGrow ) \ <nl> V ( WasmTableGet ) \ <nl> V ( WasmTableSet ) \ <nl> STATIC_ASSERT ( kMaxTFSBuiltinRegisterParams < = kMaxBuiltinRegisterParams ) ; <nl> DEFINE_FLAGS_AND_RESULT_AND_PARAMETERS ( \ <nl> CallInterfaceDescriptorData : : kAllowVarArgs , 1 , # # __VA_ARGS__ ) <nl> <nl> - # define DEFINE_RESULT_AND_PARAMETER_TYPES ( . . . ) \ <nl> - void InitializePlatformIndependent ( CallInterfaceDescriptorData * data ) \ <nl> - override { \ <nl> - MachineType machine_types [ ] = { __VA_ARGS__ } ; \ <nl> - static_assert ( \ <nl> - kReturnCount + kParameterCount = = arraysize ( machine_types ) , \ <nl> - " Parameter names definition is not consistent with parameter types " ) ; \ <nl> - data - > InitializePlatformIndependent ( Flags ( kDescriptorFlags ) , kReturnCount , \ <nl> - kParameterCount , machine_types , \ <nl> - arraysize ( machine_types ) ) ; \ <nl> + # define DEFINE_RESULT_AND_PARAMETER_TYPES_WITH_FLAG ( flag , . . . ) \ <nl> + void InitializePlatformIndependent ( CallInterfaceDescriptorData * data ) \ <nl> + override { \ <nl> + MachineType machine_types [ ] = { __VA_ARGS__ } ; \ <nl> + static_assert ( \ <nl> + kReturnCount + kParameterCount = = arraysize ( machine_types ) , \ <nl> + " Parameter names definition is not consistent with parameter types " ) ; \ <nl> + data - > InitializePlatformIndependent ( \ <nl> + Flags ( flag | kDescriptorFlags ) , kReturnCount , kParameterCount , \ <nl> + machine_types , arraysize ( machine_types ) ) ; \ <nl> } <nl> <nl> + # define DEFINE_RESULT_AND_PARAMETER_TYPES ( . . . ) \ <nl> + DEFINE_RESULT_AND_PARAMETER_TYPES_WITH_FLAG ( \ <nl> + CallInterfaceDescriptorData : : kNoFlags , __VA_ARGS__ ) <nl> + <nl> # define DEFINE_PARAMETER_TYPES ( . . . ) \ <nl> DEFINE_RESULT_AND_PARAMETER_TYPES ( MachineType : : AnyTagged ( ) / * result * / , \ <nl> # # __VA_ARGS__ ) <nl> class WasmAtomicNotifyDescriptor final : public CallInterfaceDescriptor { <nl> DECLARE_DESCRIPTOR ( WasmAtomicNotifyDescriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> - class WasmI32AtomicWaitDescriptor final : public CallInterfaceDescriptor { <nl> + class WasmI32AtomicWait32Descriptor final : public CallInterfaceDescriptor { <nl> + public : <nl> + DEFINE_PARAMETERS_NO_CONTEXT ( kAddress , kExpectedValue , kTimeoutLow , <nl> + kTimeoutHigh ) <nl> + DEFINE_RESULT_AND_PARAMETER_TYPES ( MachineType : : Uint32 ( ) , / / result 1 <nl> + MachineType : : Uint32 ( ) , / / kAddress <nl> + MachineType : : Int32 ( ) , / / kExpectedValue <nl> + MachineType : : Uint32 ( ) , / / kTimeoutLow <nl> + MachineType : : Uint32 ( ) ) / / kTimeoutHigh <nl> + DECLARE_DESCRIPTOR ( WasmI32AtomicWait32Descriptor , CallInterfaceDescriptor ) <nl> + } ; <nl> + <nl> + class WasmI64AtomicWait32Descriptor final : public CallInterfaceDescriptor { <nl> + public : <nl> + DEFINE_PARAMETERS_NO_CONTEXT ( kAddress , kExpectedValueLow , kExpectedValueHigh , <nl> + kTimeoutLow , kTimeoutHigh ) <nl> + <nl> + DEFINE_RESULT_AND_PARAMETER_TYPES_WITH_FLAG ( <nl> + CallInterfaceDescriptorData : : kNoStackScan , / / allow untagged stack params <nl> + MachineType : : Uint32 ( ) , / / result 1 <nl> + MachineType : : Uint32 ( ) , / / kAddress <nl> + MachineType : : Uint32 ( ) , / / kExpectedValueLow <nl> + MachineType : : Uint32 ( ) , / / kExpectedValueHigh <nl> + MachineType : : Uint32 ( ) , / / kTimeoutLow <nl> + MachineType : : Uint32 ( ) ) / / kTimeoutHigh <nl> + <nl> + # if V8_TARGET_ARCH_IA32 <nl> + static constexpr bool kPassLastArgOnStack = true ; <nl> + # else <nl> + static constexpr bool kPassLastArgOnStack = false ; <nl> + # endif <nl> + <nl> + / / Pass the last parameter through the stack . <nl> + static constexpr int kStackArgumentsCount = kPassLastArgOnStack ? 1 : 0 ; <nl> + <nl> + DECLARE_DESCRIPTOR ( WasmI64AtomicWait32Descriptor , CallInterfaceDescriptor ) <nl> + } ; <nl> + <nl> + class WasmI32AtomicWait64Descriptor final : public CallInterfaceDescriptor { <nl> public : <nl> DEFINE_PARAMETERS_NO_CONTEXT ( kAddress , kExpectedValue , kTimeout ) <nl> - DEFINE_RESULT_AND_PARAMETER_TYPES ( MachineType : : Uint32 ( ) , / / result 1 <nl> - MachineType : : Uint32 ( ) , / / kAddress <nl> - MachineType : : Int32 ( ) , / / kExpectedValue <nl> - MachineType : : Float64 ( ) ) / / kTimeout <nl> - DECLARE_DESCRIPTOR ( WasmI32AtomicWaitDescriptor , CallInterfaceDescriptor ) <nl> + DEFINE_RESULT_AND_PARAMETER_TYPES ( MachineType : : Uint32 ( ) , / / result 1 <nl> + MachineType : : Uint32 ( ) , / / kAddress <nl> + MachineType : : Int32 ( ) , / / kExpectedValue <nl> + MachineType : : Uint64 ( ) ) / / kTimeout <nl> + DECLARE_DESCRIPTOR ( WasmI32AtomicWait64Descriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> - class WasmI64AtomicWaitDescriptor final : public CallInterfaceDescriptor { <nl> + class WasmI64AtomicWait64Descriptor final : public CallInterfaceDescriptor { <nl> public : <nl> - DEFINE_PARAMETERS_NO_CONTEXT ( kAddress , kExpectedValueHigh , kExpectedValueLow , <nl> - kTimeout ) <nl> - DEFINE_RESULT_AND_PARAMETER_TYPES ( <nl> - MachineType : : Uint32 ( ) , / / result 1 <nl> - MachineType : : Uint32 ( ) , / / kAddress <nl> - MachineType : : Uint32 ( ) , / / kExpectedValueHigh <nl> - MachineType : : Uint32 ( ) , / / kExpectedValueLow <nl> - MachineType : : Float64 ( ) ) / / kTimeout <nl> - DECLARE_DESCRIPTOR ( WasmI64AtomicWaitDescriptor , CallInterfaceDescriptor ) <nl> + DEFINE_PARAMETERS_NO_CONTEXT ( kAddress , kExpectedValue , kTimeout ) <nl> + DEFINE_RESULT_AND_PARAMETER_TYPES ( MachineType : : Uint32 ( ) , / / result 1 <nl> + MachineType : : Uint32 ( ) , / / kAddress <nl> + MachineType : : Uint64 ( ) , / / kExpectedValue <nl> + MachineType : : Uint64 ( ) ) / / kTimeout <nl> + DECLARE_DESCRIPTOR ( WasmI64AtomicWait64Descriptor , CallInterfaceDescriptor ) <nl> } ; <nl> <nl> class CloneObjectWithVectorDescriptor final : public CallInterfaceDescriptor { <nl> mmm a / src / compiler / linkage . cc <nl> ppp b / src / compiler / linkage . cc <nl> CallDescriptor * Linkage : : GetStubCallDescriptor ( <nl> / / The rest of the parameters go on the stack . <nl> int stack_slot = i - register_parameter_count - stack_parameter_count ; <nl> locations . AddParam ( LinkageLocation : : ForCallerFrameSlot ( <nl> - stack_slot , MachineType : : AnyTagged ( ) ) ) ; <nl> + stack_slot , i < descriptor . GetParameterCount ( ) <nl> + ? descriptor . GetParameterType ( i ) <nl> + : MachineType : : AnyTagged ( ) ) ) ; <nl> } <nl> } <nl> / / Add context . <nl> mmm a / src / compiler / wasm - compiler . cc <nl> ppp b / src / compiler / wasm - compiler . cc <nl> Signature < MachineRepresentation > * CreateMachineSignature ( <nl> } <nl> return builder . Build ( ) ; <nl> } <nl> + <nl> + template < typename BuiltinDescriptor > <nl> + CallDescriptor * GetBuiltinCallDescriptor ( WasmGraphBuilder * builder , <nl> + StubCallMode stub_mode ) { <nl> + BuiltinDescriptor interface_descriptor ; <nl> + return Linkage : : GetStubCallDescriptor ( <nl> + builder - > mcgraph ( ) - > zone ( ) , / / zone <nl> + interface_descriptor , / / descriptor <nl> + interface_descriptor . GetStackParameterCount ( ) , / / stack parameter count <nl> + CallDescriptor : : kNoFlags , / / flags <nl> + Operator : : kNoProperties , / / properties <nl> + stub_mode ) ; / / stub call mode <nl> + } <nl> + <nl> } / / namespace <nl> <nl> + void WasmGraphBuilder : : AddInt64LoweringReplacement ( <nl> + CallDescriptor * original , CallDescriptor * replacement ) { <nl> + if ( ! lowering_special_case_ ) { <nl> + lowering_special_case_ = std : : make_unique < Int64LoweringSpecialCase > ( ) ; <nl> + } <nl> + lowering_special_case_ - > replacements . insert ( { original , replacement } ) ; <nl> + } <nl> + <nl> + CallDescriptor * WasmGraphBuilder : : GetI32AtomicWaitCallDescriptor ( ) { <nl> + if ( i32_atomic_wait_descriptor_ ) return i32_atomic_wait_descriptor_ ; <nl> + <nl> + i32_atomic_wait_descriptor_ = <nl> + GetBuiltinCallDescriptor < WasmI32AtomicWait64Descriptor > ( <nl> + this , StubCallMode : : kCallWasmRuntimeStub ) ; <nl> + <nl> + AddInt64LoweringReplacement ( <nl> + i32_atomic_wait_descriptor_ , <nl> + GetBuiltinCallDescriptor < WasmI32AtomicWait32Descriptor > ( <nl> + this , StubCallMode : : kCallWasmRuntimeStub ) ) ; <nl> + <nl> + return i32_atomic_wait_descriptor_ ; <nl> + } <nl> + <nl> + CallDescriptor * WasmGraphBuilder : : GetI64AtomicWaitCallDescriptor ( ) { <nl> + if ( i64_atomic_wait_descriptor_ ) return i64_atomic_wait_descriptor_ ; <nl> + <nl> + i64_atomic_wait_descriptor_ = <nl> + GetBuiltinCallDescriptor < WasmI64AtomicWait64Descriptor > ( <nl> + this , StubCallMode : : kCallWasmRuntimeStub ) ; <nl> + <nl> + AddInt64LoweringReplacement ( <nl> + i64_atomic_wait_descriptor_ , <nl> + GetBuiltinCallDescriptor < WasmI64AtomicWait32Descriptor > ( <nl> + this , StubCallMode : : kCallWasmRuntimeStub ) ) ; <nl> + <nl> + return i64_atomic_wait_descriptor_ ; <nl> + } <nl> + <nl> void WasmGraphBuilder : : LowerInt64 ( CallOrigin origin ) { <nl> if ( mcgraph ( ) - > machine ( ) - > Is64 ( ) ) return ; <nl> Int64Lowering r ( mcgraph ( ) - > graph ( ) , mcgraph ( ) - > machine ( ) , mcgraph ( ) - > common ( ) , <nl> Node * WasmGraphBuilder : : AtomicOp ( wasm : : WasmOpcode opcode , Node * const * inputs , <nl> / / Now that we ' ve bounds - checked , compute the effective address . <nl> Node * address = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > Int32Add ( ) , <nl> Uint32Constant ( offset ) , index ) ; <nl> - Node * timeout ; <nl> - if ( mcgraph ( ) - > machine ( ) - > Is32 ( ) ) { <nl> - timeout = BuildF64SConvertI64 ( inputs [ 2 ] ) ; <nl> - } else { <nl> - timeout = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > RoundInt64ToFloat64 ( ) , <nl> - inputs [ 2 ] ) ; <nl> - } <nl> - WasmI32AtomicWaitDescriptor interface_descriptor ; <nl> - auto call_descriptor = Linkage : : GetStubCallDescriptor ( <nl> - mcgraph ( ) - > zone ( ) , interface_descriptor , <nl> - interface_descriptor . GetStackParameterCount ( ) , <nl> - CallDescriptor : : kNoFlags , Operator : : kNoProperties , <nl> - StubCallMode : : kCallWasmRuntimeStub ) ; <nl> + <nl> + auto call_descriptor = GetI32AtomicWaitCallDescriptor ( ) ; <nl> + <nl> + intptr_t target = mcgraph ( ) - > machine ( ) - > Is64 ( ) <nl> + ? wasm : : WasmCode : : kWasmI32AtomicWait64 <nl> + : wasm : : WasmCode : : kWasmI32AtomicWait32 ; <nl> Node * call_target = mcgraph ( ) - > RelocatableIntPtrConstant ( <nl> - wasm : : WasmCode : : kWasmI32AtomicWait , RelocInfo : : WASM_STUB_CALL ) ; <nl> + target , RelocInfo : : WASM_STUB_CALL ) ; <nl> + <nl> node = graph ( ) - > NewNode ( mcgraph ( ) - > common ( ) - > Call ( call_descriptor ) , <nl> - call_target , address , inputs [ 1 ] , timeout , <nl> + call_target , address , inputs [ 1 ] , inputs [ 2 ] , <nl> effect ( ) , control ( ) ) ; <nl> break ; <nl> } <nl> Node * WasmGraphBuilder : : AtomicOp ( wasm : : WasmOpcode opcode , Node * const * inputs , <nl> / / Now that we ' ve bounds - checked , compute the effective address . <nl> Node * address = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > Int32Add ( ) , <nl> Uint32Constant ( offset ) , index ) ; <nl> - Node * timeout ; <nl> - if ( mcgraph ( ) - > machine ( ) - > Is32 ( ) ) { <nl> - timeout = BuildF64SConvertI64 ( inputs [ 2 ] ) ; <nl> - } else { <nl> - timeout = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > RoundInt64ToFloat64 ( ) , <nl> - inputs [ 2 ] ) ; <nl> - } <nl> - Node * expected_value_low = graph ( ) - > NewNode ( <nl> - mcgraph ( ) - > machine ( ) - > TruncateInt64ToInt32 ( ) , inputs [ 1 ] ) ; <nl> - Node * tmp = graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > Word64Shr ( ) , inputs [ 1 ] , <nl> - Int64Constant ( 32 ) ) ; <nl> - Node * expected_value_high = <nl> - graph ( ) - > NewNode ( mcgraph ( ) - > machine ( ) - > TruncateInt64ToInt32 ( ) , tmp ) ; <nl> - WasmI64AtomicWaitDescriptor interface_descriptor ; <nl> - auto call_descriptor = Linkage : : GetStubCallDescriptor ( <nl> - mcgraph ( ) - > zone ( ) , interface_descriptor , <nl> - interface_descriptor . GetStackParameterCount ( ) , <nl> - CallDescriptor : : kNoFlags , Operator : : kNoProperties , <nl> - StubCallMode : : kCallWasmRuntimeStub ) ; <nl> + <nl> + CallDescriptor * call_descriptor = GetI64AtomicWaitCallDescriptor ( ) ; <nl> + <nl> + intptr_t target = mcgraph ( ) - > machine ( ) - > Is64 ( ) <nl> + ? wasm : : WasmCode : : kWasmI64AtomicWait64 <nl> + : wasm : : WasmCode : : kWasmI64AtomicWait32 ; <nl> Node * call_target = mcgraph ( ) - > RelocatableIntPtrConstant ( <nl> - wasm : : WasmCode : : kWasmI64AtomicWait , RelocInfo : : WASM_STUB_CALL ) ; <nl> + target , RelocInfo : : WASM_STUB_CALL ) ; <nl> + <nl> node = graph ( ) - > NewNode ( mcgraph ( ) - > common ( ) - > Call ( call_descriptor ) , <nl> - call_target , address , expected_value_high , <nl> - expected_value_low , timeout , effect ( ) , control ( ) ) ; <nl> + call_target , address , inputs [ 1 ] , inputs [ 2 ] , <nl> + effect ( ) , control ( ) ) ; <nl> break ; <nl> } <nl> <nl> void WasmGraphBuilder : : RemoveBytecodePositionDecorator ( ) { <nl> } <nl> <nl> namespace { <nl> - template < typename BuiltinDescriptor > <nl> - CallDescriptor * GetBuiltinCallDescriptor ( WasmGraphBuilder * builder , <nl> - StubCallMode stub_mode ) { <nl> - BuiltinDescriptor interface_descriptor ; <nl> - return Linkage : : GetStubCallDescriptor ( <nl> - builder - > mcgraph ( ) - > zone ( ) , / / zone <nl> - interface_descriptor , / / descriptor <nl> - interface_descriptor . GetStackParameterCount ( ) , / / stack parameter count <nl> - CallDescriptor : : kNoFlags , / / flags <nl> - Operator : : kNoProperties , / / properties <nl> - stub_mode ) ; / / stub call mode <nl> - } <nl> <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> public : <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> <nl> CallDescriptor * GetI64ToBigIntCallDescriptor ( ) { <nl> if ( i64_to_bigint_descriptor_ ) return i64_to_bigint_descriptor_ ; <nl> + <nl> i64_to_bigint_descriptor_ = <nl> GetBuiltinCallDescriptor < I64ToBigIntDescriptor > ( this , stub_mode_ ) ; <nl> - if ( ! lowering_special_case_ ) { <nl> - lowering_special_case_ = std : : make_unique < Int64LoweringSpecialCase > ( ) ; <nl> - } <nl> - lowering_special_case_ - > replacements . insert ( <nl> - { i64_to_bigint_descriptor_ , <nl> - GetBuiltinCallDescriptor < I32PairToBigIntDescriptor > ( this , <nl> - stub_mode_ ) } ) ; <nl> + <nl> + AddInt64LoweringReplacement ( <nl> + i64_to_bigint_descriptor_ , <nl> + GetBuiltinCallDescriptor < I32PairToBigIntDescriptor > ( this , stub_mode_ ) ) ; <nl> return i64_to_bigint_descriptor_ ; <nl> } <nl> <nl> CallDescriptor * GetBigIntToI64CallDescriptor ( ) { <nl> if ( bigint_to_i64_descriptor_ ) return bigint_to_i64_descriptor_ ; <nl> - if ( ! lowering_special_case_ ) { <nl> - lowering_special_case_ = std : : make_unique < Int64LoweringSpecialCase > ( ) ; <nl> - } <nl> <nl> bigint_to_i64_descriptor_ = <nl> GetBuiltinCallDescriptor < BigIntToI64Descriptor > ( this , stub_mode_ ) ; <nl> <nl> - lowering_special_case_ - > replacements . insert ( <nl> - { bigint_to_i64_descriptor_ , <nl> - GetBuiltinCallDescriptor < BigIntToI32PairDescriptor > ( this , <nl> - stub_mode_ ) } ) ; <nl> + AddInt64LoweringReplacement ( <nl> + bigint_to_i64_descriptor_ , <nl> + GetBuiltinCallDescriptor < BigIntToI32PairDescriptor > ( this , stub_mode_ ) ) ; <nl> return bigint_to_i64_descriptor_ ; <nl> } <nl> <nl> mmm a / src / compiler / wasm - compiler . h <nl> ppp b / src / compiler / wasm - compiler . h <nl> class WasmGraphBuilder { <nl> Node * * parameters , int parameter_count ) ; <nl> TrapId GetTrapIdForTrap ( wasm : : TrapReason reason ) ; <nl> <nl> + void AddInt64LoweringReplacement ( CallDescriptor * original , <nl> + CallDescriptor * replacement ) ; <nl> + <nl> + CallDescriptor * GetI32AtomicWaitCallDescriptor ( ) ; <nl> + <nl> + CallDescriptor * GetI64AtomicWaitCallDescriptor ( ) ; <nl> + <nl> std : : unique_ptr < WasmGraphAssembler > gasm_ ; <nl> Zone * const zone_ ; <nl> MachineGraph * const mcgraph_ ; <nl> class WasmGraphBuilder { <nl> compiler : : SourcePositionTable * const source_position_table_ = nullptr ; <nl> <nl> std : : unique_ptr < Int64LoweringSpecialCase > lowering_special_case_ ; <nl> + CallDescriptor * i32_atomic_wait_descriptor_ = nullptr ; <nl> + CallDescriptor * i64_atomic_wait_descriptor_ = nullptr ; <nl> } ; <nl> <nl> enum WasmCallKind { kWasmFunction , kWasmImportWrapper , kWasmCapiFunction } ; <nl> mmm a / src / execution / futex - emulation . cc <nl> ppp b / src / execution / futex - emulation . cc <nl> Object WaitJsTranslateReturn ( Isolate * isolate , Object res ) { <nl> Object FutexEmulation : : WaitJs32 ( Isolate * isolate , <nl> Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> int32_t value , double rel_timeout_ms ) { <nl> - Object res = Wait32 ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> + Object res = <nl> + Wait < int32_t > ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> return WaitJsTranslateReturn ( isolate , res ) ; <nl> } <nl> <nl> Object FutexEmulation : : WaitJs64 ( Isolate * isolate , <nl> Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> int64_t value , double rel_timeout_ms ) { <nl> - Object res = Wait64 ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> + Object res = <nl> + Wait < int64_t > ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> return WaitJsTranslateReturn ( isolate , res ) ; <nl> } <nl> <nl> - Object FutexEmulation : : Wait32 ( Isolate * isolate , <nl> - Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> - int32_t value , double rel_timeout_ms ) { <nl> - return Wait < int32_t > ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> + Object FutexEmulation : : WaitWasm32 ( Isolate * isolate , <nl> + Handle < JSArrayBuffer > array_buffer , <nl> + size_t addr , int32_t value , <nl> + int64_t rel_timeout_ns ) { <nl> + return Wait < int32_t > ( isolate , array_buffer , addr , value , rel_timeout_ns > = 0 , <nl> + rel_timeout_ns ) ; <nl> } <nl> <nl> - Object FutexEmulation : : Wait64 ( Isolate * isolate , <nl> - Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> - int64_t value , double rel_timeout_ms ) { <nl> - return Wait < int64_t > ( isolate , array_buffer , addr , value , rel_timeout_ms ) ; <nl> + Object FutexEmulation : : WaitWasm64 ( Isolate * isolate , <nl> + Handle < JSArrayBuffer > array_buffer , <nl> + size_t addr , int64_t value , <nl> + int64_t rel_timeout_ns ) { <nl> + return Wait < int64_t > ( isolate , array_buffer , addr , value , rel_timeout_ns > = 0 , <nl> + rel_timeout_ns ) ; <nl> } <nl> <nl> template < typename T > <nl> Object FutexEmulation : : Wait ( Isolate * isolate , <nl> Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> T value , double rel_timeout_ms ) { <nl> - VMState < ATOMICS_WAIT > state ( isolate ) ; <nl> DCHECK_LT ( addr , array_buffer - > byte_length ( ) ) ; <nl> <nl> bool use_timeout = rel_timeout_ms ! = V8_INFINITY ; <nl> + int64_t rel_timeout_ns = - 1 ; <nl> <nl> - base : : TimeDelta rel_timeout ; <nl> if ( use_timeout ) { <nl> / / Convert to nanoseconds . <nl> - double rel_timeout_ns = rel_timeout_ms * <nl> - base : : Time : : kNanosecondsPerMicrosecond * <nl> - base : : Time : : kMicrosecondsPerMillisecond ; <nl> - if ( rel_timeout_ns > <nl> - static_cast < double > ( std : : numeric_limits < int64_t > : : max ( ) ) ) { <nl> + double timeout_ns = rel_timeout_ms * <nl> + base : : Time : : kNanosecondsPerMicrosecond * <nl> + base : : Time : : kMicrosecondsPerMillisecond ; <nl> + if ( timeout_ns > static_cast < double > ( std : : numeric_limits < int64_t > : : max ( ) ) ) { <nl> / / 2 * * 63 nanoseconds is 292 years . Let ' s just treat anything greater as <nl> / / infinite . <nl> use_timeout = false ; <nl> } else { <nl> - rel_timeout = base : : TimeDelta : : FromNanoseconds ( <nl> - static_cast < int64_t > ( rel_timeout_ns ) ) ; <nl> + rel_timeout_ns = static_cast < int64_t > ( timeout_ns ) ; <nl> } <nl> } <nl> + return Wait ( isolate , array_buffer , addr , value , use_timeout , rel_timeout_ns ) ; <nl> + } <nl> + <nl> + namespace { <nl> + double WaitTimeoutInMs ( double timeout_ns ) { <nl> + return timeout_ns < 0 <nl> + ? V8_INFINITY <nl> + : timeout_ns / ( base : : Time : : kNanosecondsPerMicrosecond * <nl> + base : : Time : : kMicrosecondsPerMillisecond ) ; <nl> + } <nl> + } / / namespace <nl> + <nl> + template < typename T > <nl> + Object FutexEmulation : : Wait ( Isolate * isolate , <nl> + Handle < JSArrayBuffer > array_buffer , size_t addr , <nl> + T value , bool use_timeout , int64_t rel_timeout_ns ) { <nl> + VMState < ATOMICS_WAIT > state ( isolate ) ; <nl> + base : : TimeDelta rel_timeout = <nl> + base : : TimeDelta : : FromNanoseconds ( rel_timeout_ns ) ; <nl> <nl> + / / We have to convert the timeout back to double for the AtomicsWaitCallback . <nl> + double rel_timeout_ms = WaitTimeoutInMs ( static_cast < double > ( rel_timeout_ns ) ) ; <nl> AtomicsWaitWakeHandle stop_handle ( isolate ) ; <nl> <nl> isolate - > RunAtomicsWaitCallback ( AtomicsWaitEvent : : kStartWait , array_buffer , <nl> mmm a / src / execution / futex - emulation . h <nl> ppp b / src / execution / futex - emulation . h <nl> class FutexEmulation : public AllStatic { <nl> <nl> / / Same as WaitJs above except it returns 0 ( ok ) , 1 ( not equal ) and 2 ( timed <nl> / / out ) as expected by Wasm . <nl> - static Object Wait32 ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> - size_t addr , int32_t value , double rel_timeout_ms ) ; <nl> + static Object WaitWasm32 ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> + size_t addr , int32_t value , int64_t rel_timeout_ns ) ; <nl> <nl> / / Same as Wait32 above except it checks for an int64_t value in the <nl> / / array_buffer . <nl> - static Object Wait64 ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> - size_t addr , int64_t value , double rel_timeout_ms ) ; <nl> + static Object WaitWasm64 ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> + size_t addr , int64_t value , int64_t rel_timeout_ns ) ; <nl> <nl> / / Wake | num_waiters_to_wake | threads that are waiting on the given | addr | . <nl> / / | num_waiters_to_wake | can be kWakeAll , in which case all waiters are <nl> class FutexEmulation : public AllStatic { <nl> static Object Wait ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> size_t addr , T value , double rel_timeout_ms ) ; <nl> <nl> + template < typename T > <nl> + static Object Wait ( Isolate * isolate , Handle < JSArrayBuffer > array_buffer , <nl> + size_t addr , T value , bool use_timeout , <nl> + int64_t rel_timeout_ns ) ; <nl> + <nl> / / ` mutex_ ` protects the composition of ` wait_list_ ` ( i . e . no elements may be <nl> / / added or removed without holding this mutex ) , as well as the ` waiting_ ` <nl> / / and ` interrupted_ ` fields for each individual list node that is currently <nl> mmm a / src / runtime / runtime - wasm . cc <nl> ppp b / src / runtime / runtime - wasm . cc <nl> RUNTIME_FUNCTION ( Runtime_WasmAtomicNotify ) { <nl> return FutexEmulation : : Wake ( array_buffer , address , count ) ; <nl> } <nl> <nl> - double WaitTimeoutInMs ( double timeout_ns ) { <nl> - return timeout_ns < 0 <nl> - ? V8_INFINITY <nl> - : timeout_ns / ( base : : Time : : kNanosecondsPerMicrosecond * <nl> - base : : Time : : kMicrosecondsPerMillisecond ) ; <nl> - } <nl> - <nl> RUNTIME_FUNCTION ( Runtime_WasmI32AtomicWait ) { <nl> ClearThreadInWasmScope clear_wasm_flag ; <nl> HandleScope scope ( isolate ) ; <nl> RUNTIME_FUNCTION ( Runtime_WasmI32AtomicWait ) { <nl> CONVERT_ARG_HANDLE_CHECKED ( WasmInstanceObject , instance , 0 ) ; <nl> CONVERT_NUMBER_CHECKED ( uint32_t , address , Uint32 , args [ 1 ] ) ; <nl> CONVERT_NUMBER_CHECKED ( int32_t , expected_value , Int32 , args [ 2 ] ) ; <nl> - CONVERT_DOUBLE_ARG_CHECKED ( timeout_ns , 3 ) ; <nl> - double timeout_ms = WaitTimeoutInMs ( timeout_ns ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( BigInt , timeout_ns , 3 ) ; <nl> + <nl> Handle < JSArrayBuffer > array_buffer = <nl> getSharedArrayBuffer ( instance , isolate , address ) ; <nl> - return FutexEmulation : : Wait32 ( isolate , array_buffer , address , expected_value , <nl> - timeout_ms ) ; <nl> + return FutexEmulation : : WaitWasm32 ( isolate , array_buffer , address , <nl> + expected_value , timeout_ns - > AsInt64 ( ) ) ; <nl> } <nl> <nl> RUNTIME_FUNCTION ( Runtime_WasmI64AtomicWait ) { <nl> ClearThreadInWasmScope clear_wasm_flag ; <nl> HandleScope scope ( isolate ) ; <nl> - DCHECK_EQ ( 5 , args . length ( ) ) ; <nl> + DCHECK_EQ ( 4 , args . length ( ) ) ; <nl> CONVERT_ARG_HANDLE_CHECKED ( WasmInstanceObject , instance , 0 ) ; <nl> CONVERT_NUMBER_CHECKED ( uint32_t , address , Uint32 , args [ 1 ] ) ; <nl> - CONVERT_NUMBER_CHECKED ( uint32_t , expected_value_high , Uint32 , args [ 2 ] ) ; <nl> - CONVERT_NUMBER_CHECKED ( uint32_t , expected_value_low , Uint32 , args [ 3 ] ) ; <nl> - CONVERT_DOUBLE_ARG_CHECKED ( timeout_ns , 4 ) ; <nl> - int64_t expected_value = ( static_cast < uint64_t > ( expected_value_high ) < < 32 ) | <nl> - static_cast < uint64_t > ( expected_value_low ) ; <nl> - double timeout_ms = WaitTimeoutInMs ( timeout_ns ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( BigInt , expected_value , 2 ) ; <nl> + CONVERT_ARG_HANDLE_CHECKED ( BigInt , timeout_ns , 3 ) ; <nl> + <nl> Handle < JSArrayBuffer > array_buffer = <nl> getSharedArrayBuffer ( instance , isolate , address ) ; <nl> - return FutexEmulation : : Wait64 ( isolate , array_buffer , address , expected_value , <nl> - timeout_ms ) ; <nl> + return FutexEmulation : : WaitWasm64 ( isolate , array_buffer , address , <nl> + expected_value - > AsInt64 ( ) , <nl> + timeout_ns - > AsInt64 ( ) ) ; <nl> } <nl> <nl> namespace { <nl> mmm a / src / wasm / wasm - code - manager . h <nl> ppp b / src / wasm / wasm - code - manager . h <nl> struct WasmModule ; <nl> V ( WasmCompileLazy ) \ <nl> V ( WasmDebugBreak ) \ <nl> V ( WasmAtomicNotify ) \ <nl> - V ( WasmI32AtomicWait ) \ <nl> - V ( WasmI64AtomicWait ) \ <nl> + V ( WasmI32AtomicWait32 ) \ <nl> + V ( WasmI32AtomicWait64 ) \ <nl> + V ( WasmI64AtomicWait32 ) \ <nl> + V ( WasmI64AtomicWait64 ) \ <nl> V ( WasmMemoryGrow ) \ <nl> V ( WasmTableGet ) \ <nl> V ( WasmTableSet ) \ <nl> mmm a / src / wasm / wasm - interpreter . cc <nl> ppp b / src / wasm / wasm - interpreter . cc <nl> class ThreadImpl { <nl> bool ExtractAtomicWaitNotifyParams ( Decoder * decoder , InterpreterCode * code , <nl> pc_t pc , int * const len , <nl> uint32_t * buffer_offset , type * val , <nl> - double * timeout = nullptr ) { <nl> + int64_t * timeout = nullptr ) { <nl> MemoryAccessImmediate < Decoder : : kValidate > imm ( decoder , code - > at ( pc + 1 ) , <nl> sizeof ( type ) ) ; <nl> if ( timeout ) { <nl> - double timeout_ns = Pop ( ) . to < int64_t > ( ) ; <nl> - * timeout = ( timeout_ns < 0 ) <nl> - ? V8_INFINITY <nl> - : timeout_ns / ( base : : Time : : kNanosecondsPerMicrosecond * <nl> - base : : Time : : kMicrosecondsPerMillisecond ) ; <nl> + * timeout = Pop ( ) . to < int64_t > ( ) ; <nl> } <nl> * val = Pop ( ) . to < type > ( ) ; <nl> auto index = Pop ( ) . to < uint32_t > ( ) ; <nl> class ThreadImpl { <nl> break ; <nl> case kExprI32AtomicWait : { <nl> int32_t val ; <nl> - double timeout ; <nl> + int64_t timeout ; <nl> uint32_t buffer_offset ; <nl> if ( ! ExtractAtomicWaitNotifyParams < int32_t > ( <nl> decoder , code , pc , len , & buffer_offset , & val , & timeout ) ) { <nl> class ThreadImpl { <nl> HandleScope handle_scope ( isolate_ ) ; <nl> Handle < JSArrayBuffer > array_buffer ( <nl> instance_object_ - > memory_object ( ) . array_buffer ( ) , isolate_ ) ; <nl> - auto result = FutexEmulation : : Wait32 ( isolate_ , array_buffer , <nl> - buffer_offset , val , timeout ) ; <nl> + auto result = FutexEmulation : : WaitWasm32 ( isolate_ , array_buffer , <nl> + buffer_offset , val , timeout ) ; <nl> Push ( WasmValue ( result . ToSmi ( ) . value ( ) ) ) ; <nl> break ; <nl> } <nl> case kExprI64AtomicWait : { <nl> int64_t val ; <nl> - double timeout ; <nl> + int64_t timeout ; <nl> uint32_t buffer_offset ; <nl> if ( ! ExtractAtomicWaitNotifyParams < int64_t > ( <nl> decoder , code , pc , len , & buffer_offset , & val , & timeout ) ) { <nl> class ThreadImpl { <nl> HandleScope handle_scope ( isolate_ ) ; <nl> Handle < JSArrayBuffer > array_buffer ( <nl> instance_object_ - > memory_object ( ) . array_buffer ( ) , isolate_ ) ; <nl> - auto result = FutexEmulation : : Wait64 ( isolate_ , array_buffer , <nl> - buffer_offset , val , timeout ) ; <nl> + auto result = FutexEmulation : : WaitWasm64 ( isolate_ , array_buffer , <nl> + buffer_offset , val , timeout ) ; <nl> Push ( WasmValue ( result . ToSmi ( ) . value ( ) ) ) ; <nl> break ; <nl> } <nl> | Reland " [ wasm ] Refactor AtomicWait implementation " | v8/v8 | 7ad6b04edbf0edf07a5afeae0902f4f5bc01fd0b | 2020-03-02T14:49:55Z |
mmm a / src / Common / ThreadProfileEvents . cpp <nl> ppp b / src / Common / ThreadProfileEvents . cpp <nl> <nl> # include < syscall . h > <nl> # include < sys / ioctl . h > <nl> # include < cerrno > <nl> + # include < sys / types . h > <nl> + # include < dirent . h > <nl> <nl> <nl> namespace DB <nl> bool PerfEventsCounters : : initializeThreadLocalEvents ( PerfEventsCounters & counte <nl> return false ; <nl> } <nl> <nl> + rlimit64 limits { } ; <nl> + if ( getrlimit64 ( RLIMIT_NOFILE , & limits ) ) <nl> + { <nl> + LOG_WARNING ( getLogger ( ) , " Unable to get rlimit : errno = " < < errno < < " , message = " < < strerror ( errno ) ) ; <nl> + return false ; <nl> + } <nl> + UInt64 maximum_open_descriptors = limits . rlim_cur ; <nl> + <nl> + std : : string dir_path ( " / proc / " ) ; <nl> + dir_path + = std : : to_string ( getpid ( ) ) ; <nl> + dir_path + = " / fd " ; <nl> + DIR * fd_dir = opendir ( dir_path . c_str ( ) ) ; <nl> + if ( fd_dir = = nullptr ) <nl> + { <nl> + LOG_WARNING ( getLogger ( ) , " Unable to get file descriptors used by the current process errno = " < < errno <nl> + < < " , message = " < < strerror ( errno ) ) ; <nl> + return false ; <nl> + } <nl> + UInt64 opened_descriptors = 0 ; <nl> + while ( readdir ( fd_dir ) ! = nullptr ) <nl> + + + opened_descriptors ; <nl> + closedir ( fd_dir ) ; <nl> + <nl> + UInt64 fd_count_afterwards = opened_descriptors + NUMBER_OF_RAW_EVENTS ; <nl> + UInt64 threshold = static_cast < UInt64 > ( maximum_open_descriptors * FILE_DESCRIPTORS_THRESHOLD ) ; <nl> + if ( fd_count_afterwards > threshold ) <nl> + { <nl> + LOG_WARNING ( getLogger ( ) , " Can ' t measure perf events as the result number of file descriptors ( " <nl> + < < fd_count_afterwards < < " ) is more than the current threshold ( " < < threshold < < " = " <nl> + < < maximum_open_descriptors < < " * " < < FILE_DESCRIPTORS_THRESHOLD < < " ) " ) ; <nl> + return false ; <nl> + } <nl> + <nl> bool expected = false ; <nl> bool log_unsupported_event = particular_events_unavailability_logged . compare_exchange_strong ( expected , true ) ; <nl> for ( size_t i = 0 ; i < NUMBER_OF_RAW_EVENTS ; + + i ) <nl> mmm a / src / Common / ThreadProfileEvents . h <nl> ppp b / src / Common / ThreadProfileEvents . h <nl> struct PerfEventsCounters <nl> typedef UInt64 Id ; <nl> <nl> static constexpr size_t NUMBER_OF_RAW_EVENTS = 18 ; <nl> + static constexpr Float64 FILE_DESCRIPTORS_THRESHOLD = 0 . 7 ; <nl> <nl> static const PerfEventInfo raw_events_info [ PerfEventsCounters : : NUMBER_OF_RAW_EVENTS ] ; <nl> <nl> | Added file descriptors threshold | ClickHouse/ClickHouse | b6d6427748cfa93b2cd242cea893f9c8eae4926a | 2020-05-19T18:22:30Z |
mmm a / osquery / tables / system / windows / logical_drives . cpp <nl> ppp b / osquery / tables / system / windows / logical_drives . cpp <nl> <nl> * This source code is licensed in accordance with the terms specified in <nl> * the LICENSE file found in the root directory of this source tree . <nl> * / <nl> - # include < osquery / tables . h > <nl> + <nl> + # include < unordered_set > <nl> <nl> # include " osquery / core / windows / wmi . h " <nl> + # include < osquery / tables . h > <nl> <nl> namespace osquery { <nl> namespace tables { <nl> QueryData genLogicalDrives ( QueryContext & context ) { <nl> " select DeviceID , Description , FreeSpace , Size , FileSystem from " <nl> " Win32_LogicalDisk " ) ; <nl> auto const & logicalDisks = wmiLogicalDiskReq . results ( ) ; <nl> + <nl> + const WmiRequest wmiBootConfigurationReq ( <nl> + " select BootDirectory from Win32_BootConfiguration " ) ; <nl> + auto const & bootConfigurations = wmiBootConfigurationReq . results ( ) ; <nl> + std : : unordered_set < char > bootDeviceIds ; <nl> + <nl> + for ( const auto & bootConfiguration : bootConfigurations ) { <nl> + std : : string bootDirectory ; <nl> + bootConfiguration . GetString ( " BootDirectory " , bootDirectory ) ; <nl> + bootDeviceIds . insert ( bootDirectory . at ( 0 ) ) ; <nl> + } <nl> + <nl> for ( const auto & logicalDisk : logicalDisks ) { <nl> Row r ; <nl> std : : string deviceId ; <nl> QueryData genLogicalDrives ( QueryContext & context ) { <nl> / / return " Unknown " . That behavior is preserved here . <nl> r [ " type " ] = " Unknown " ; <nl> r [ " device_id " ] = deviceId ; <nl> - r [ " boot_partition " ] = INTEGER ( 0 ) ; <nl> + r [ " boot_partition " ] = INTEGER ( bootDeviceIds . count ( deviceId . at ( 0 ) ) ) ; <nl> <nl> - std : : string assocQuery = <nl> - std : : string ( " Associators of { Win32_LogicalDisk . DeviceID = ' " ) + deviceId + <nl> - " ' } where AssocClass = Win32_LogicalDiskToPartition " ; <nl> - <nl> - const WmiRequest wmiLogicalDiskToPartitionReq ( assocQuery ) ; <nl> - auto const & wmiLogicalDiskToPartitionResults = <nl> - wmiLogicalDiskToPartitionReq . results ( ) ; <nl> - <nl> - if ( wmiLogicalDiskToPartitionResults . empty ( ) ) { <nl> - results . push_back ( r ) ; <nl> - continue ; <nl> - } <nl> - std : : string partitionDeviceId ; <nl> - wmiLogicalDiskToPartitionResults [ 0 ] . GetString ( " DeviceID " , <nl> - partitionDeviceId ) ; <nl> - <nl> - std : : string partitionQuery = <nl> - std : : string ( <nl> - " SELECT BootPartition FROM Win32_DiskPartition WHERE DeviceID = ' " ) + <nl> - partitionDeviceId + ' \ ' ' ; <nl> - const WmiRequest wmiPartitionReq ( partitionQuery ) ; <nl> - auto const & wmiPartitionResults = wmiPartitionReq . results ( ) ; <nl> - <nl> - if ( wmiPartitionResults . empty ( ) ) { <nl> - results . push_back ( r ) ; <nl> - continue ; <nl> - } <nl> - bool bootPartition = false ; <nl> - wmiPartitionResults [ 0 ] . GetBool ( " BootPartition " , bootPartition ) ; <nl> - r [ " boot_partition " ] = bootPartition ? INTEGER ( 1 ) : INTEGER ( 0 ) ; <nl> - results . push_back ( r ) ; <nl> + results . push_back ( std : : move ( r ) ) ; <nl> } <nl> return results ; <nl> } <nl> | windows / logical_drives : Fix boot partition detection ( ) | osquery/osquery | a8df05dfcd83bb0051d151b0734f2dc4eb2e9aed | 2019-03-11T11:57:28Z |
mmm a / include / fmt / format . h <nl> ppp b / include / fmt / format . h <nl> join ( const Range & range , wstring_view sep ) { <nl> * / <nl> template < typename T , FMT_ENABLE_IF ( ! std : : is_integral < T > : : value ) > <nl> inline std : : string to_string ( const T & value ) { <nl> - return format ( " { } " , value ) ; <nl> + std : : string result ; <nl> + detail : : write < char > ( std : : back_inserter ( result ) , value ) ; <nl> + return result ; <nl> } <nl> <nl> template < typename T , FMT_ENABLE_IF ( std : : is_integral < T > : : value ) > <nl> | Make to_string bypass format | fmtlib/fmt | 7431165f38bc608c8367f5511ad670e1afa9aefa | 2020-06-16T00:55:16Z |
deleted file mode 100755 <nl> index db3398a92a3 . . 00000000000 <nl> mmm a / misc / dist / appimage / AppRun <nl> ppp / dev / null <nl> <nl> - # ! / bin / sh <nl> - HERE = " $ ( dirname " $ ( readlink - f " $ { 0 } " ) " ) " <nl> - " $ { HERE } " / godot $ @ <nl> deleted file mode 100644 <nl> index 545c491256f . . 00000000000 <nl> mmm a / misc / dist / appimage / godot . desktop <nl> ppp / dev / null <nl> <nl> - [ Desktop Entry ] <nl> - Name = Godot Engine <nl> - GenericName = Libre game engine <nl> - Comment = Multi - platform 2D and 3D game engine with a feature rich editor <nl> - Exec = godot - pm <nl> - Icon = godot <nl> - Terminal = false <nl> - Type = Application <nl> - Categories = Development ; IDE ; <nl> deleted file mode 100644 <nl> index e334f5fa78b . . 00000000000 <nl> Binary files a / misc / dist / appimage / godot . png and / dev / null differ <nl> | Merge pull request from Calinou / remove - appimage - structure | godotengine/godot | 682c2f249369e18724ffbe1c2c7ba617c05fb379 | 2018-06-25T13:27:32Z |
mmm a / ios / playground / WeexDemo / AppDelegate . m <nl> ppp b / ios / playground / WeexDemo / AppDelegate . m <nl> - ( void ) applicationDidEnterBackground : ( UIApplication * ) application <nl> # endif <nl> } <nl> <nl> + - ( BOOL ) application : ( UIApplication * ) application handleOpenURL : ( NSURL * ) url <nl> + { <nl> + NSString * newUrlStr = url . absoluteString ; <nl> + if ( [ url . scheme isEqualToString : @ " wxpage " ] ) { <nl> + newUrlStr = [ newUrlStr stringByReplacingOccurrencesOfString : @ " wxpage : / / " withString : @ " http : / / " ] ; <nl> + } <nl> + UIViewController * viewController = [ self demoController ] ; <nl> + ( ( WXDemoViewController * ) viewController ) . url = [ NSURL URLWithString : newUrlStr ] ; <nl> + [ ( WXRootViewController * ) self . window . rootViewController pushViewController : viewController animated : YES ] ; <nl> + return YES ; <nl> + } <nl> + <nl> # pragma mark weex <nl> - ( void ) initWeexSDK <nl> { <nl> mmm a / ios / playground / WeexDemo / Info . plist <nl> ppp b / ios / playground / WeexDemo / Info . plist <nl> <nl> < ! DOCTYPE plist PUBLIC " - / / Apple / / DTD PLIST 1 . 0 / / EN " " http : / / www . apple . com / DTDs / PropertyList - 1 . 0 . dtd " > <nl> < plist version = " 1 . 0 " > <nl> < dict > <nl> + < key > CFBundleURLTypes < / key > <nl> + < array > <nl> + < dict > <nl> + < key > CFBundleURLSchemes < / key > <nl> + < array > <nl> + < string > wxpage < / string > <nl> + < / array > <nl> + < / dict > <nl> + < / array > <nl> < key > CFBundleDevelopmentRegion < / key > <nl> < string > en < / string > <nl> < key > CFBundleDisplayName < / key > <nl> | * [ ios ] playground handle wxpage scheme | apache/incubator-weex | 6e664b897e7bdaf9d0439b5e4583c4e83855a2c3 | 2017-01-12T06:19:37Z |
mmm a / lib / Sema / CSApply . cpp <nl> ppp b / lib / Sema / CSApply . cpp <nl> static bool exprNeedsParensAfterAddingAs ( DeclContext * DC , Expr * expr , <nl> getMinPrecedenceForExpr ( DC , expr , rootExpr ) ) ; <nl> } <nl> <nl> + namespace { <nl> + class ExprWalker : public ASTWalker { <nl> + ExprRewriter & Rewriter ; <nl> + SmallVector < ClosureExpr * , 4 > closuresToTypeCheck ; <nl> + unsigned LeftSideOfAssignment = 0 ; <nl> + <nl> + public : <nl> + ExprWalker ( ExprRewriter & Rewriter ) : Rewriter ( Rewriter ) { } <nl> + <nl> + ~ ExprWalker ( ) { <nl> + auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> + auto & tc = cs . getTypeChecker ( ) ; <nl> + for ( auto * closure : closuresToTypeCheck ) <nl> + tc . typeCheckClosureBody ( closure ) ; <nl> + } <nl> + <nl> + std : : pair < bool , Expr * > walkToExprPre ( Expr * expr ) override { <nl> + / / For a default - value expression , do nothing . <nl> + if ( isa < DefaultValueExpr > ( expr ) ) <nl> + return { false , expr } ; <nl> + <nl> + / / For closures , update the parameter types and check the body . <nl> + if ( auto closure = dyn_cast < ClosureExpr > ( expr ) ) { <nl> + Rewriter . simplifyExprType ( expr ) ; <nl> + auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> + auto & tc = cs . getTypeChecker ( ) ; <nl> + <nl> + / / Coerce the pattern , in case we resolved something . <nl> + auto fnType = closure - > getType ( ) - > castTo < FunctionType > ( ) ; <nl> + Pattern * params = closure - > getParams ( ) ; <nl> + TypeResolutionOptions TROptions ; <nl> + TROptions | = TR_OverrideType ; <nl> + TROptions | = TR_FromNonInferredPattern ; <nl> + TROptions | = TR_InExpression ; <nl> + TROptions | = TR_ImmediateFunctionInput ; <nl> + if ( tc . coercePatternToType ( params , closure , fnType - > getInput ( ) , <nl> + TROptions ) ) <nl> + return { false , nullptr } ; <nl> + closure - > setParams ( params ) ; <nl> + <nl> + / / If this is a single - expression closure , convert the expression <nl> + / / in the body to the result type of the closure . <nl> + if ( closure - > hasSingleExpressionBody ( ) ) { <nl> + / / Enter the context of the closure when type - checking the body . <nl> + llvm : : SaveAndRestore < DeclContext * > savedDC ( Rewriter . dc , closure ) ; <nl> + Expr * body = closure - > getSingleExpressionBody ( ) - > walk ( * this ) ; <nl> + <nl> + if ( body ! = closure - > getSingleExpressionBody ( ) ) <nl> + closure - > setSingleExpressionBody ( body ) ; <nl> + <nl> + if ( body ) { <nl> + <nl> + if ( fnType - > getResult ( ) - > isVoid ( ) & & ! body - > getType ( ) - > isVoid ( ) ) { <nl> + closure = Rewriter . coerceClosureExprToVoid ( closure ) ; <nl> + } else { <nl> + <nl> + body = Rewriter . coerceToType ( body , <nl> + fnType - > getResult ( ) , <nl> + cs . getConstraintLocator ( <nl> + closure , <nl> + ConstraintLocator : : ClosureResult ) ) ; <nl> + if ( ! body ) <nl> + return { false , nullptr } ; <nl> + <nl> + closure - > setSingleExpressionBody ( body ) ; <nl> + } <nl> + } <nl> + } else { <nl> + / / For other closures , type - check the body once we ' ve finished with <nl> + / / the expression . <nl> + closuresToTypeCheck . push_back ( closure ) ; <nl> + } <nl> + <nl> + tc . ClosuresWithUncomputedCaptures . push_back ( closure ) ; <nl> + <nl> + return { false , closure } ; <nl> + } <nl> + <nl> + / / Track whether we ' re in the left - hand side of an assignment . . . <nl> + if ( auto assign = dyn_cast < AssignExpr > ( expr ) ) { <nl> + + + LeftSideOfAssignment ; <nl> + <nl> + if ( auto dest = assign - > getDest ( ) - > walk ( * this ) ) <nl> + assign - > setDest ( dest ) ; <nl> + else <nl> + return { false , nullptr } ; <nl> + <nl> + - - LeftSideOfAssignment ; <nl> + <nl> + auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> + auto srcLocator = cs . getConstraintLocator ( <nl> + assign , <nl> + ConstraintLocator : : AssignSource ) ; <nl> + <nl> + if ( auto src = assign - > getSrc ( ) - > walk ( * this ) ) <nl> + assign - > setSrc ( src ) ; <nl> + else <nl> + return { false , nullptr } ; <nl> + <nl> + expr = Rewriter . visitAssignExpr ( assign , srcLocator ) ; <nl> + return { false , expr } ; <nl> + } <nl> + <nl> + / / . . . so we can verify that ' _ ' only appears there . <nl> + if ( isa < DiscardAssignmentExpr > ( expr ) & & LeftSideOfAssignment = = 0 ) <nl> + Rewriter . getConstraintSystem ( ) . getTypeChecker ( ) <nl> + . diagnose ( expr - > getLoc ( ) , diag : : discard_expr_outside_of_assignment ) ; <nl> + <nl> + return { true , expr } ; <nl> + } <nl> + <nl> + Expr * walkToExprPost ( Expr * expr ) override { <nl> + return Rewriter . visit ( expr ) ; <nl> + } <nl> + <nl> + / / / \ brief Ignore statements . <nl> + std : : pair < bool , Stmt * > walkToStmtPre ( Stmt * stmt ) override { <nl> + return { false , stmt } ; <nl> + } <nl> + <nl> + / / / \ brief Ignore declarations . <nl> + bool walkToDeclPre ( Decl * decl ) override { return false ; } <nl> + } ; <nl> + <nl> + } <nl> + <nl> / / / \ brief Apply a given solution to the expression , producing a fully <nl> / / / type - checked expression . <nl> Expr * ConstraintSystem : : applySolution ( Solution & solution , Expr * expr , <nl> Expr * ConstraintSystem : : applySolution ( Solution & solution , Expr * expr , <nl> return nullptr ; <nl> } <nl> <nl> - class ExprWalker : public ASTWalker { <nl> - ExprRewriter & Rewriter ; <nl> - SmallVector < ClosureExpr * , 4 > closuresToTypeCheck ; <nl> - unsigned LeftSideOfAssignment = 0 ; <nl> - <nl> - public : <nl> - ExprWalker ( ExprRewriter & Rewriter ) : Rewriter ( Rewriter ) { } <nl> - <nl> - ~ ExprWalker ( ) { <nl> - auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> - auto & tc = cs . getTypeChecker ( ) ; <nl> - for ( auto * closure : closuresToTypeCheck ) <nl> - tc . typeCheckClosureBody ( closure ) ; <nl> - } <nl> - <nl> - std : : pair < bool , Expr * > walkToExprPre ( Expr * expr ) override { <nl> - / / For a default - value expression , do nothing . <nl> - if ( isa < DefaultValueExpr > ( expr ) ) <nl> - return { false , expr } ; <nl> - <nl> - / / For closures , update the parameter types and check the body . <nl> - if ( auto closure = dyn_cast < ClosureExpr > ( expr ) ) { <nl> - Rewriter . simplifyExprType ( expr ) ; <nl> - auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> - auto & tc = cs . getTypeChecker ( ) ; <nl> - <nl> - / / Coerce the pattern , in case we resolved something . <nl> - auto fnType = closure - > getType ( ) - > castTo < FunctionType > ( ) ; <nl> - Pattern * params = closure - > getParams ( ) ; <nl> - TypeResolutionOptions TROptions ; <nl> - TROptions | = TR_OverrideType ; <nl> - TROptions | = TR_FromNonInferredPattern ; <nl> - TROptions | = TR_InExpression ; <nl> - TROptions | = TR_ImmediateFunctionInput ; <nl> - if ( tc . coercePatternToType ( params , closure , fnType - > getInput ( ) , <nl> - TROptions ) ) <nl> - return { false , nullptr } ; <nl> - closure - > setParams ( params ) ; <nl> - <nl> - / / If this is a single - expression closure , convert the expression <nl> - / / in the body to the result type of the closure . <nl> - if ( closure - > hasSingleExpressionBody ( ) ) { <nl> - / / Enter the context of the closure when type - checking the body . <nl> - llvm : : SaveAndRestore < DeclContext * > savedDC ( Rewriter . dc , closure ) ; <nl> - Expr * body = closure - > getSingleExpressionBody ( ) - > walk ( * this ) ; <nl> - <nl> - if ( body ! = closure - > getSingleExpressionBody ( ) ) <nl> - closure - > setSingleExpressionBody ( body ) ; <nl> - <nl> - if ( body ) { <nl> - <nl> - if ( fnType - > getResult ( ) - > isVoid ( ) & & ! body - > getType ( ) - > isVoid ( ) ) { <nl> - closure = Rewriter . coerceClosureExprToVoid ( closure ) ; <nl> - } else { <nl> - <nl> - body = Rewriter . coerceToType ( body , <nl> - fnType - > getResult ( ) , <nl> - cs . getConstraintLocator ( <nl> - closure , <nl> - ConstraintLocator : : ClosureResult ) ) ; <nl> - if ( ! body ) <nl> - return { false , nullptr } ; <nl> - <nl> - closure - > setSingleExpressionBody ( body ) ; <nl> - } <nl> - } <nl> - } else { <nl> - / / For other closures , type - check the body once we ' ve finished with <nl> - / / the expression . <nl> - closuresToTypeCheck . push_back ( closure ) ; <nl> - } <nl> - <nl> - tc . ClosuresWithUncomputedCaptures . push_back ( closure ) ; <nl> - <nl> - return { false , closure } ; <nl> - } <nl> - <nl> - / / Track whether we ' re in the left - hand side of an assignment . . . <nl> - if ( auto assign = dyn_cast < AssignExpr > ( expr ) ) { <nl> - + + LeftSideOfAssignment ; <nl> - <nl> - if ( auto dest = assign - > getDest ( ) - > walk ( * this ) ) <nl> - assign - > setDest ( dest ) ; <nl> - else <nl> - return { false , nullptr } ; <nl> - <nl> - - - LeftSideOfAssignment ; <nl> - <nl> - auto & cs = Rewriter . getConstraintSystem ( ) ; <nl> - auto srcLocator = cs . getConstraintLocator ( <nl> - assign , <nl> - ConstraintLocator : : AssignSource ) ; <nl> - <nl> - if ( auto src = assign - > getSrc ( ) - > walk ( * this ) ) <nl> - assign - > setSrc ( src ) ; <nl> - else <nl> - return { false , nullptr } ; <nl> - <nl> - expr = Rewriter . visitAssignExpr ( assign , srcLocator ) ; <nl> - return { false , expr } ; <nl> - } <nl> - <nl> - / / . . . so we can verify that ' _ ' only appears there . <nl> - if ( isa < DiscardAssignmentExpr > ( expr ) & & LeftSideOfAssignment = = 0 ) <nl> - Rewriter . getConstraintSystem ( ) . getTypeChecker ( ) <nl> - . diagnose ( expr - > getLoc ( ) , diag : : discard_expr_outside_of_assignment ) ; <nl> - <nl> - return { true , expr } ; <nl> - } <nl> - <nl> - Expr * walkToExprPost ( Expr * expr ) override { <nl> - return Rewriter . visit ( expr ) ; <nl> - } <nl> - <nl> - / / / \ brief Ignore statements . <nl> - std : : pair < bool , Stmt * > walkToStmtPre ( Stmt * stmt ) override { <nl> - return { false , stmt } ; <nl> - } <nl> - <nl> - / / / \ brief Ignore declarations . <nl> - bool walkToDeclPre ( Decl * decl ) override { return false ; } <nl> - } ; <nl> - <nl> ExprRewriter rewriter ( * this , solution , suppressDiagnostics ) ; <nl> ExprWalker walker ( rewriter ) ; <nl> <nl> | Sema : Moved ExprWalker class out of applySolution ( ) | apple/swift | 6c1ee5537ac6ac3274cf6067f25c2c150d801619 | 2015-06-15T02:00:50Z |
mmm a / xbmc / guilib / GUIKeyboardFactory . cpp <nl> ppp b / xbmc / guilib / GUIKeyboardFactory . cpp <nl> int CGUIKeyboardFactory : : ShowAndVerifyPassword ( std : : string & strPassword , const s <nl> return 0 ; <nl> <nl> std : : string md5pword2 = XBMC : : XBMC_MD5 : : GetMD5 ( strUserInput ) ; <nl> - if ( strPassword = = md5pword2 ) <nl> + if ( StringUtils : : EqualsNoCase ( strPassword , md5pword2 ) ) <nl> return 0 ; / / user entered correct password <nl> else return 1 ; / / user must have entered an incorrect password <nl> } <nl> | Merge pull request from Montellese / fix_profile_password_login | xbmc/xbmc | dd4a6efc939c2c520c4f5be65344baf4b6dc91c4 | 2014-10-05T23:30:20Z |
mmm a / src / regexp / regexp - interpreter . cc <nl> ppp b / src / regexp / regexp - interpreter . cc <nl> bool CheckBitInTable ( const uint32_t current_char , const byte * const table ) { <nl> return ( b & ( 1 < < bit ) ) ! = 0 ; <nl> } <nl> <nl> + / / Returns true iff 0 < = index < length . <nl> + bool IndexIsInBounds ( int index , int length ) { <nl> + DCHECK_GE ( length , 0 ) ; <nl> + return static_cast < uintptr_t > ( index ) < static_cast < uintptr_t > ( length ) ; <nl> + } <nl> + <nl> / / If computed gotos are supported by the compiler , we can get addresses to <nl> / / labels directly in C / C + + . Every bytecode handler has its own label and we <nl> / / store the addresses in a dispatch table indexed by bytecode . To execute the <nl> bool CheckBitInTable ( const uint32_t current_char , const byte * const table ) { <nl> DECODE ( ) <nl> <nl> / / Current position mutations . <nl> - # define SET_CURRENT_POSITION ( value ) \ <nl> - do { \ <nl> - current = ( value ) ; \ <nl> - DCHECK ( base : : IsInBounds ( current , 0 , subject . length ( ) ) ) ; \ <nl> + # define SET_CURRENT_POSITION ( value ) \ <nl> + do { \ <nl> + current = ( value ) ; \ <nl> + DCHECK ( base : : IsInRange ( current , 0 , subject . length ( ) ) ) ; \ <nl> } while ( false ) <nl> # define ADVANCE_CURRENT_POSITION ( by ) SET_CURRENT_POSITION ( current + ( by ) ) <nl> <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_CHAR ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load16AlignedSigned ( pc + 4 ) ; <nl> uint32_t c = Load16Aligned ( pc + 6 ) ; <nl> - while ( static_cast < uintptr_t > ( current + load_offset ) < <nl> - static_cast < uintptr_t > ( subject . length ( ) ) ) { <nl> + while ( IndexIsInBounds ( current + load_offset , subject . length ( ) ) ) { <nl> current_char = subject [ current + load_offset ] ; <nl> if ( c = = current_char ) { <nl> SET_PC_FROM_OFFSET ( Load32Aligned ( pc + 8 ) ) ; <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_CHAR_AND ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load16AlignedSigned ( pc + 4 ) ; <nl> uint16_t c = Load16Aligned ( pc + 6 ) ; <nl> uint32_t mask = Load32Aligned ( pc + 8 ) ; <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_CHAR_POS_CHECKED ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load16AlignedSigned ( pc + 4 ) ; <nl> uint16_t c = Load16Aligned ( pc + 6 ) ; <nl> int32_t maximum_offset = Load32Aligned ( pc + 8 ) ; <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_BIT_IN_TABLE ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load16AlignedSigned ( pc + 4 ) ; <nl> const byte * table = pc + 8 ; <nl> - while ( static_cast < uintptr_t > ( current + load_offset ) < <nl> - static_cast < uintptr_t > ( subject . length ( ) ) ) { <nl> + while ( IndexIsInBounds ( current + load_offset , subject . length ( ) ) ) { <nl> current_char = subject [ current + load_offset ] ; <nl> if ( CheckBitInTable ( current_char , table ) ) { <nl> SET_PC_FROM_OFFSET ( Load32Aligned ( pc + 24 ) ) ; <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_GT_OR_NOT_BIT_IN_TABLE ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load16AlignedSigned ( pc + 4 ) ; <nl> uint16_t limit = Load16Aligned ( pc + 6 ) ; <nl> const byte * table = pc + 8 ; <nl> - while ( static_cast < uintptr_t > ( current + load_offset ) < <nl> - static_cast < uintptr_t > ( subject . length ( ) ) ) { <nl> + while ( IndexIsInBounds ( current + load_offset , subject . length ( ) ) ) { <nl> current_char = subject [ current + load_offset ] ; <nl> if ( current_char > limit ) { <nl> SET_PC_FROM_OFFSET ( Load32Aligned ( pc + 24 ) ) ; <nl> IrregexpInterpreter : : Result RawMatch ( <nl> DISPATCH ( ) ; <nl> } <nl> BYTECODE ( SKIP_UNTIL_CHAR_OR_CHAR ) { <nl> - uint32_t load_offset = LoadPacked24Unsigned ( insn ) ; <nl> + int32_t load_offset = LoadPacked24Signed ( insn ) ; <nl> int32_t advance = Load32Aligned ( pc + 4 ) ; <nl> uint16_t c = Load16Aligned ( pc + 8 ) ; <nl> uint16_t c2 = Load16Aligned ( pc + 10 ) ; <nl> - while ( static_cast < uintptr_t > ( current + load_offset ) < <nl> - static_cast < uintptr_t > ( subject . length ( ) ) ) { <nl> + while ( IndexIsInBounds ( current + load_offset , subject . length ( ) ) ) { <nl> current_char = subject [ current + load_offset ] ; <nl> / / The two if - statements below are split up intentionally , as combining <nl> / / them seems to result in register allocation behaving quite <nl> new file mode 100644 <nl> index 00000000000 . . 61392086104 <nl> mmm / dev / null <nl> ppp b / test / mjsunit / regress / regress - 1084872 . js <nl> <nl> + / / Copyright 2020 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + const re = new RegExp ( " ( ? < = ( . ) \ \ 2 . * ( T ) ) " ) ; <nl> + re . exec ( undefined ) ; <nl> + assertEquals ( re . exec ( " bTaLTT " ) [ 1 ] , " b " ) ; <nl> | [ regexp ] Fix signed / unsigned confusion in regexp interpreter | v8/v8 | 1372e3591e6bc91b2a204ef6371b72b0e701c7af | 2020-05-20T13:44:21Z |
mmm a / src / library_sdl . js <nl> ppp b / src / library_sdl . js <nl> var LibrarySDL = { <nl> return ret ; <nl> } , <nl> <nl> + rotozoomSurface : function ( src , angle , zoom , smooth ) { <nl> + var srcData = SDL . surfaces [ src ] ; <nl> + var w = srcData . width * zoom ; <nl> + var h = srcData . height * zoom ; <nl> + var diagonal = Math . ceil ( Math . sqrt ( Math . pow ( w , 2 ) + Math . pow ( h , 2 ) ) ) ; <nl> + var ret = SDL . makeSurface ( diagonal , diagonal , srcData . flags , false , ' rotozoomSurface ' ) ; <nl> + var dstData = SDL . surfaces [ ret ] ; <nl> + dstData . ctx . translate ( diagonal / 2 , diagonal / 2 ) ; <nl> + dstData . ctx . rotate ( angle * Math . PI / 180 ) ; <nl> + dstData . ctx . drawImage ( srcData . canvas , - w / 2 , - h / 2 , w , h ) ; <nl> + return ret ; <nl> + } , <nl> + <nl> SDL_SetAlpha : function ( surf , flag , alpha ) { <nl> SDL . surfaces [ surf ] . alpha = alpha ; <nl> } , <nl> mmm a / tests / sdl_rotozoom . c <nl> ppp b / tests / sdl_rotozoom . c <nl> int main ( int argc , char * * argv ) { <nl> sprite [ 1 ] = SDL_CreateRGBSurface ( SDL_SWSURFACE , 100 , 100 , 32 , 0xFF000000 , 0xFF0000 , 0xFF00 , 0xFF ) ; <nl> SDL_FillRect ( sprite [ 1 ] , 0 , 0xA0A0A0A0 ) ; <nl> sprite [ 2 ] = zoomSurface ( sprite [ 0 ] , 0 . 5 , 0 . 5 , SMOOTHING_ON ) ; <nl> - sprite [ 3 ] = zoomSurface ( sprite [ 1 ] , 0 . 5 , 0 . 5 , SMOOTHING_ON ) ; <nl> + sprite [ 3 ] = rotozoomSurface ( sprite [ 1 ] , 45 , 0 . 5 , SMOOTHING_ON ) ; <nl> <nl> mainloop ( ) ; <nl> <nl> Binary files a / tests / sdl_rotozoom . png and b / tests / sdl_rotozoom . png differ <nl> | Support rotozoomSurface | emscripten-core/emscripten | 703422829c0b8de54016ed32e4905a4d51b9f7dc | 2013-03-30T21:24:15Z |
mmm a / Box2D / proj . bada / . cproject <nl> ppp b / Box2D / proj . bada / . cproject <nl> <nl> < / toolChain > <nl> < / folderInfo > <nl> < sourceEntries > <nl> - < entry excluding = " Collision | Common | Dynamics " flags = " VALUE_WORKSPACE_PATH | RESOLVED " kind = " sourcePath " name = " " / > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Collision " / > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Common " / > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Dynamics " / > <nl> <nl> < externalSetting > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " includePath " name = " / Box2D " / > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " libraryPath " name = " / Box2D / . Target - Debug " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " libraryPath " name = " / Box2D " / > <nl> < / externalSetting > <nl> < / externalSettings > <nl> < extensions > <nl> <nl> < / toolChain > <nl> < / folderInfo > <nl> < sourceEntries > <nl> - < entry flags = " VALUE_WORKSPACE_PATH | RESOLVED " kind = " sourcePath " name = " " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Collision " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Common " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Dynamics " / > <nl> < / sourceEntries > <nl> < / configuration > <nl> < / storageModule > <nl> <nl> < externalSetting > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " includePath " name = " / Box2D " / > <nl> < entry flags = " VALUE_WORKSPACE_PATH " kind = " libraryPath " name = " / Box2D / . Target - Release " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " libraryPath " name = " / Box2D " / > <nl> < / externalSetting > <nl> < / externalSettings > <nl> < extensions > <nl> <nl> < / toolChain > <nl> < / folderInfo > <nl> < sourceEntries > <nl> - < entry flags = " VALUE_WORKSPACE_PATH | RESOLVED " kind = " sourcePath " name = " " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Collision " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Common " / > <nl> + < entry flags = " VALUE_WORKSPACE_PATH " kind = " sourcePath " name = " Dynamics " / > <nl> < / sourceEntries > <nl> < / configuration > <nl> < / storageModule > <nl> | modify setting of box2d in bada project | cocos2d/cocos2d-x | d96e00668b6a3b83758ee87977850a48b752f496 | 2011-09-19T15:19:39Z |
mmm a / src / app / ui / timeline / timeline . cpp <nl> ppp b / src / app / ui / timeline / timeline . cpp <nl> namespace { <nl> <nl> } / / anonymous namespace <nl> <nl> + Timeline : : Hit : : Hit ( int part , <nl> + layer_t layer , <nl> + frame_t frame , <nl> + ObjectId frameTag , <nl> + int band ) <nl> + : part ( part ) , <nl> + layer ( layer ) , <nl> + frame ( frame ) , <nl> + frameTag ( frameTag ) , <nl> + veryBottom ( false ) , <nl> + band ( band ) <nl> + { <nl> + } <nl> + <nl> + bool Timeline : : Hit : : operator ! = ( const Hit & other ) const <nl> + { <nl> + return <nl> + part ! = other . part | | <nl> + layer ! = other . layer | | <nl> + frame ! = other . frame | | <nl> + frameTag ! = other . frameTag | | <nl> + band ! = other . band ; <nl> + } <nl> + <nl> + FrameTag * Timeline : : Hit : : getFrameTag ( ) const <nl> + { <nl> + return get < FrameTag > ( frameTag ) ; <nl> + } <nl> + <nl> + Timeline : : DropTarget : : DropTarget ( ) <nl> + { <nl> + hhit = HNone ; <nl> + vhit = VNone ; <nl> + } <nl> + <nl> + Timeline : : LayerInfo : : LayerInfo ( ) <nl> + : layer ( nullptr ) , <nl> + level ( 0 ) , <nl> + inheritedFlags ( LayerFlags : : None ) <nl> + { <nl> + } <nl> + <nl> + Timeline : : LayerInfo : : LayerInfo ( Layer * layer , int level , LayerFlags inheritedFlags ) <nl> + : layer ( layer ) , <nl> + level ( level ) , <nl> + inheritedFlags ( inheritedFlags ) <nl> + { <nl> + } <nl> + <nl> + bool Timeline : : LayerInfo : : parentVisible ( ) const <nl> + { <nl> + return ( ( int ( inheritedFlags ) & int ( LayerFlags : : Visible ) ) ! = 0 ) ; <nl> + } <nl> + <nl> + bool Timeline : : LayerInfo : : parentEditable ( ) const <nl> + { <nl> + return ( ( int ( inheritedFlags ) & int ( LayerFlags : : Editable ) ) ! = 0 ) ; <nl> + } <nl> + <nl> Timeline : : Timeline ( ) <nl> : Widget ( kGenericWidget ) <nl> , m_hbar ( HORIZONTAL , this ) <nl> int Timeline : : topHeight ( ) const <nl> return h ; <nl> } <nl> <nl> - FrameTag * Timeline : : Hit : : getFrameTag ( ) const <nl> - { <nl> - return get < FrameTag > ( frameTag ) ; <nl> - } <nl> - <nl> void Timeline : : onNewInputPriority ( InputChainElement * element ) <nl> { <nl> / / It looks like the user wants to execute commands targetting the <nl> mmm a / src / app / ui / timeline / timeline . h <nl> ppp b / src / app / ui / timeline / timeline . h <nl> namespace app { <nl> layer_t layer = - 1 , <nl> frame_t frame = 0 , <nl> ObjectId frameTag = NullId , <nl> - int band = - 1 ) <nl> - : part ( part ) , <nl> - layer ( layer ) , <nl> - frame ( frame ) , <nl> - frameTag ( frameTag ) , <nl> - veryBottom ( false ) , <nl> - band ( band ) { <nl> - } <nl> - <nl> - bool operator ! = ( const Hit & other ) const { <nl> - return <nl> - part ! = other . part | | <nl> - layer ! = other . layer | | <nl> - frame ! = other . frame | | <nl> - frameTag ! = other . frameTag | | <nl> - band ! = other . band ; <nl> - } <nl> - <nl> + int band = - 1 ) ; <nl> + bool operator ! = ( const Hit & other ) const ; <nl> FrameTag * getFrameTag ( ) const ; <nl> } ; <nl> <nl> struct DropTarget { <nl> - <nl> enum HHit { <nl> HNone , <nl> Before , <nl> After <nl> } ; <nl> - <nl> enum VHit { <nl> VNone , <nl> Bottom , <nl> namespace app { <nl> VeryBottom <nl> } ; <nl> <nl> - DropTarget ( ) { <nl> - hhit = HNone ; <nl> - vhit = VNone ; <nl> - } <nl> + DropTarget ( ) ; <nl> <nl> HHit hhit ; <nl> VHit vhit ; <nl> namespace app { <nl> int level ; <nl> LayerFlags inheritedFlags ; <nl> <nl> - LayerInfo ( ) <nl> - : layer ( nullptr ) , <nl> - level ( 0 ) , <nl> - inheritedFlags ( LayerFlags : : None ) { <nl> - } <nl> - <nl> - LayerInfo ( Layer * layer , int level , LayerFlags inheritedFlags ) <nl> - : layer ( layer ) , <nl> - level ( level ) , <nl> - inheritedFlags ( inheritedFlags ) { <nl> - } <nl> - <nl> - bool parentVisible ( ) const { <nl> - return ( ( int ( inheritedFlags ) & int ( LayerFlags : : Visible ) ) ! = 0 ) ; <nl> - } <nl> - <nl> - bool parentEditable ( ) const { <nl> - return ( ( int ( inheritedFlags ) & int ( LayerFlags : : Editable ) ) ! = 0 ) ; <nl> - } <nl> + LayerInfo ( ) ; <nl> + LayerInfo ( Layer * layer , int level , LayerFlags inheritedFlags ) ; <nl> + <nl> + bool parentVisible ( ) const ; <nl> + bool parentEditable ( ) const ; <nl> } ; <nl> <nl> bool selectedLayersBounds ( const SelectedLayers & layers , <nl> | Move internal Timeline structs from timeline . h to timeline . cpp | aseprite/aseprite | fa49673c460f622d58cb046450ce952df65ea4b8 | 2017-04-12T18:53:54Z |
mmm a / Examples / SequenceToSequence / CMUDict / Python / Sequence2Sequence . py <nl> ppp b / Examples / SequenceToSequence / CMUDict / Python / Sequence2Sequence . py <nl> def LSTM_stack ( input , num_layers , output_dim , recurrence_hook_h = past_value , recu <nl> <nl> return ( output_h , output_c ) <nl> <nl> - def create_model ( inputs ) : <nl> + def create_model ( inputs ) : # ( input_sequence , decoder_history_sequence ) - - > ( word_sequence ) <nl> <nl> # get inputs to the model ( has to include labels for input to the decoder ) <nl> raw_input , raw_labels = inputs <nl> mmm a / Examples / SequenceToSequence / CMUDict / Python / attention . py <nl> ppp b / Examples / SequenceToSequence / CMUDict / Python / attention . py <nl> <nl> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> <nl> from cntk . ops import times , constant , past_value , splice , softmax , reshape , \ <nl> - parameter , element_times , tanh , log , alias <nl> + parameter , element_times , tanh , alias <nl> from cntk . ops . sequence import last , broadcast_as <nl> from cntk . initializer import glorot_uniform <nl> from cntk . blocks import Stabilizer , _INFERRED <nl> def augment_input_hook ( prev_state ) : <nl> v = parameter ( shape = ( attention_dim , 1 ) ) <nl> <nl> u = times ( Stabilizer ( ) ( element_times ( tanh_out , valid ) ) , v ) # ( attention_span , 1 ) <nl> - u_valid = u + ( valid - 1 ) * 50 <nl> - <nl> + u_valid = u + ( valid - 1 ) * 50 # zero - out the unused elements <nl> + <nl> # we do two reshapes ( 20 , 1 ) - > ( 20 ) and then ( 20 ) - > ( 20 , 1 ) so that we can use the built - in softmax ( ) <nl> + # TODO : we have to do the above because softmax ( ) does not support " axis = " - - > make sure this gets added <nl> attention_weights = alias ( softmax ( reshape ( u_valid , shape = ( attention_span ) ) ) , name = ' attention_weights ' ) <nl> <nl> # the window should be shape = ( attention_span , output_dim ) <nl> def augment_input_hook ( prev_state ) : <nl> <nl> return weighted_attention_avg <nl> <nl> - return augment_input_hook <nl> + return augment_input_hook <nl> \ No newline at end of file <nl> mmm a / Source / CNTKv2LibraryDll / API / CNTKLibrary . h <nl> ppp b / Source / CNTKv2LibraryDll / API / CNTKLibrary . h <nl> namespace CNTK <nl> <nl> / / / <nl> / / / Create an instance of the CNTK built - in softmax operation on specified tensor input operand <nl> + / / / TODO : this Softmax ( ) needs to support specifying the axis <nl> / / / <nl> CNTK_API FunctionPtr Softmax ( const Variable & operand , const std : : wstring & name = L " " ) ; <nl> <nl> | added TODO for adding axis to softmax | microsoft/CNTK | cb39afc4516b129b29d04bcef8589894d6d8f4fd | 2016-12-06T11:04:31Z |
mmm a / tensorflow / contrib / tensorrt / log / trt_logger . cc <nl> ppp b / tensorflow / contrib / tensorrt / log / trt_logger . cc <nl> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> See the License for the specific language governing permissions and <nl> limitations under the License . <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> # if GOOGLE_CUDA <nl> # if GOOGLE_TENSORRT <nl> <nl> void Logger : : log ( Severity severity , const char * msg ) { <nl> } / / namespace tensorrt <nl> } / / namespace tensorflow <nl> <nl> - # endif <nl> - # endif <nl> + # endif / / GOOGLE_CUDA <nl> + # endif / / GOOGLE_TENSORRT <nl> mmm a / tensorflow / contrib / tensorrt / log / trt_logger . h <nl> ppp b / tensorflow / contrib / tensorrt / log / trt_logger . h <nl> class Logger : public nvinfer1 : : ILogger { <nl> <nl> # endif / / GOOGLE_TENSORRT <nl> # endif / / GOOGLE_CUDA <nl> + <nl> # endif / / TENSORFLOW_CONTRIB_TENSORRT_LOG_TRT_LOGGER_H_ <nl> mmm a / tensorflow / contrib / tensorrt / segment / segment_test . cc <nl> ppp b / tensorflow / contrib / tensorrt / segment / segment_test . cc <nl> See the License for the specific language governing permissions and <nl> limitations under the License . <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> <nl> - # if GOOGLE_CUDA <nl> - # if GOOGLE_TENSORRT <nl> - <nl> # include " tensorflow / contrib / tensorrt / segment / segment . h " <nl> # include " tensorflow / c / c_api . h " <nl> # include " tensorflow / core / framework / graph . pb . h " <nl> limitations under the License . <nl> # include " tensorflow / core / lib / core / status . h " <nl> # include " tensorflow / core / platform / test . h " <nl> <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> namespace tensorflow { <nl> - <nl> namespace tensorrt { <nl> namespace segment { <nl> namespace test { <nl> TEST_F ( SegmentTest , BigIfElse ) { <nl> } / / namespace test <nl> } / / namespace segment <nl> } / / namespace tensorrt <nl> - <nl> } / / namespace tensorflow <nl> - <nl> - # endif / / GOOGLE_TENSORRT <nl> - # endif / / GOOGLE_CUDA <nl> | Fix GOOGLE_TENSORRT | tensorflow/tensorflow | f47e05b65bb15d595d24b4b7f0da0f2648c5b30e | 2018-01-30T16:36:09Z |
mmm a / xbmc / cores / AudioEngine / Sinks / AESinkALSA . cpp <nl> ppp b / xbmc / cores / AudioEngine / Sinks / AESinkALSA . cpp <nl> bool CAESinkALSA : : InitializeHW ( const ALSAConfig & inconfig , ALSAConfig & outconfig <nl> int bits = snd_pcm_hw_params_get_sbits ( hw_params ) ; <nl> if ( bits ! = fmtBits ) <nl> { <nl> - / * if we opened in 32bit and only have 24bits , pack into 24 * / <nl> + / * if we opened in 32bit and only have 24bits , signal it accordingly * / <nl> if ( fmtBits = = 32 & & bits = = 24 ) <nl> - i = AE_FMT_S24NE4 ; <nl> + i = AE_FMT_S24NE4MSB ; <nl> else <nl> continue ; <nl> } <nl> | AESinkALSA : Fix S24NE4MSB incorrectly reported as S24NE4 | xbmc/xbmc | bcd591a97e5a6e8ac9550dca3adcf157bb11a248 | 2014-08-28T17:48:25Z |
mmm a / docs / en / operations / utilities / clickhouse - benchmark . md <nl> ppp b / docs / en / operations / utilities / clickhouse - benchmark . md <nl> clickhouse - benchmark [ keys ] < queries_file <nl> <nl> # # Keys { # clickhouse - benchmark - keys } <nl> <nl> - - ` - - query = WORD ` - Query to execute . If this parameter is not passed , ` clickhouse - benchmark ` will read queries from standard input . <nl> + - ` - - query = WORD ` — Query to execute . If this parameter is not passed , ` clickhouse - benchmark ` will read queries from standard input . <nl> - ` - c N ` , ` - - concurrency = N ` — Number of queries that ` clickhouse - benchmark ` sends simultaneously . Default value : ` 1 ` . <nl> - ` - d N ` , ` - - delay = N ` — Interval in seconds between intermediate reports ( to disable reports set ` 0 ` ) . Default value : ` 1 ` . <nl> - ` - h WORD ` , ` - - host = WORD ` — Server host . Default value : ` localhost ` . For the [ comparison mode ] ( # clickhouse - benchmark - comparison - mode ) you can use multiple ` - h ` keys . <nl> mmm a / docs / ru / operations / utilities / clickhouse - benchmark . md <nl> ppp b / docs / ru / operations / utilities / clickhouse - benchmark . md <nl> clickhouse - benchmark [ keys ] < queries_file <nl> <nl> # # Ключи { # clickhouse - benchmark - keys } <nl> <nl> - - ` - - query = WORD ` - запрос для исполнения . Если параметр не передан , ` clickhouse - benchmark ` будет считывать считывать запросы из стандартного ввода . <nl> + - ` - - query = WORD ` — запрос для исполнения . Если параметр не передан , ` clickhouse - benchmark ` будет считывать считывать запросы из стандартного ввода . <nl> - ` - c N ` , ` - - concurrency = N ` — количество запросов , которые ` clickhouse - benchmark ` отправляет одновременно . Значение по умолчанию : ` 1 ` . <nl> - ` - d N ` , ` - - delay = N ` — интервал в секундах между промежуточными сообщениями . ( чтобы отлючить сообщения , установите ` 0 ` ) . Значение по умолчанию : ` 1 ` . <nl> - ` - h WORD ` , ` - - host = WORD ` — хост сервера . Значение по умолчанию : ` localhost ` . Для [ сравнительного режима ] ( # clickhouse - benchmark - comparison - mode ) можно использовать несколько ` - h ` ключей . <nl> | Minor fixes | ClickHouse/ClickHouse | c7b9cf73488da560dbd9e878ab6473f72edc8625 | 2020-12-30T14:12:10Z |
mmm a / jstests / libs / geo_near_random . js <nl> ppp b / jstests / libs / geo_near_random . js <nl> GeoNearRandomTest = function ( name ) { <nl> <nl> GeoNearRandomTest . prototype . mkPt = function mkPt ( scale ) { <nl> scale = scale | | 1 ; / / scale is good for staying away from edges <nl> - return [ ( ( Random . rand ( ) * 360 ) - 180 ) * scale , ( ( Random . rand ( ) * 180 ) - 90 ) * scale ] ; <nl> + return [ ( ( Random . rand ( ) * 359 . 8 ) - 179 . 9 ) * scale , ( ( Random . rand ( ) * 180 ) - 90 ) * scale ] ; <nl> } <nl> <nl> GeoNearRandomTest . prototype . insertPts = function ( nPts ) { <nl> | Limit generated points to [ - 179 . 9 , 179 . 9 ] due to SERVER - 1720 | mongodb/mongo | b5e57bae310b4f097fcb4c7230cbe3de42477dab | 2010-09-03T17:28:10Z |
mmm a / . github / ISSUE_TEMPLATE / Bug_report . md <nl> ppp b / . github / ISSUE_TEMPLATE / Bug_report . md <nl> The info below often helps , please fill it out if you ' re able to . : ) <nl> <nl> - [ ] Windows : ( _version : _ ___ ) <nl> - [ ] Linux : ( _distro : _ ___ ) <nl> - - [ ] Mac OS : ( _version : _ ___ ) <nl> + - [ ] macOS : ( _version : _ ___ ) <nl> - [ ] Other : ___ <nl> <nl> # # # # What is your DB4S version ? <nl> | Update macOS casing in bug report template | sqlitebrowser/sqlitebrowser | e0b276c391d30ae312a2a03f5564f22f0cc1fb57 | 2020-01-17T22:31:09Z |
mmm a / src / openalpr / alpr_impl . cpp <nl> ppp b / src / openalpr / alpr_impl . cpp <nl> AlprFullDetails AlprImpl : : recognizeFullDetails ( cv : : Mat img , std : : vector < cv : : Rect <nl> displayImage ( config , " Main Image " , img ) ; <nl> <nl> / / Sleep 1ms <nl> - sleep_ms ( 1000 ) ; <nl> + sleep_ms ( 1 ) ; <nl> <nl> } <nl> <nl> | Sleep for 1ms , rather than 1 second | openalpr/openalpr | 7a3cb53aa67483cd1e2015c8c4bb8cbd06848ab8 | 2014-08-28T12:57:54Z |
mmm a / src / core / CMakeLists . txt <nl> ppp b / src / core / CMakeLists . txt <nl> set ( SRCS <nl> hle / service / apt_u . cpp <nl> hle / service / cfg_u . cpp <nl> hle / service / dsp_dsp . cpp <nl> + hle / service / err_f . cpp <nl> hle / service / fs_user . cpp <nl> hle / service / gsp_gpu . cpp <nl> hle / service / hid_user . cpp <nl> set ( HEADERS <nl> hle / service / apt_u . h <nl> hle / service / cfg_u . h <nl> hle / service / dsp_dsp . h <nl> + hle / service / err_f . h <nl> hle / service / fs_user . h <nl> hle / service / gsp_gpu . h <nl> hle / service / hid_user . h <nl> new file mode 100644 <nl> index 00000000000 . . 917b2f8ca4c <nl> mmm / dev / null <nl> ppp b / src / core / hle / service / err_f . cpp <nl> <nl> + / / Copyright 2014 Citra Emulator Project <nl> + / / Licensed under GPLv2 <nl> + / / Refer to the license . txt file included . <nl> + <nl> + # include " common / log . h " <nl> + # include " core / hle / hle . h " <nl> + # include " core / hle / service / err_f . h " <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Namespace ERR_F <nl> + <nl> + namespace ERR_F { <nl> + <nl> + const Interface : : FunctionInfo FunctionTable [ ] = { <nl> + { 0x00010800 , nullptr , " ThrowFatalError " } <nl> + } ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Interface class <nl> + <nl> + Interface : : Interface ( ) { <nl> + Register ( FunctionTable , ARRAY_SIZE ( FunctionTable ) ) ; <nl> + } <nl> + <nl> + Interface : : ~ Interface ( ) { <nl> + } <nl> + <nl> + } / / namespace <nl> new file mode 100644 <nl> index 00000000000 . . 5da6632672d <nl> mmm / dev / null <nl> ppp b / src / core / hle / service / err_f . h <nl> <nl> + / / Copyright 2014 Citra Emulator Project <nl> + / / Licensed under GPLv2 <nl> + / / Refer to the license . txt file included . <nl> + <nl> + # pragma once <nl> + <nl> + # include " core / hle / service / service . h " <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Namespace ERR_F <nl> + <nl> + namespace ERR_F { <nl> + <nl> + class Interface : public Service : : Interface { <nl> + public : <nl> + Interface ( ) ; <nl> + ~ Interface ( ) ; <nl> + / * * <nl> + * Gets the string port name used by CTROS for the service <nl> + * @ return Port name of service <nl> + * / <nl> + std : : string GetPortName ( ) const { <nl> + return " err : f " ; <nl> + } <nl> + } ; <nl> + <nl> + } / / namespace <nl> mmm a / src / core / hle / service / service . cpp <nl> ppp b / src / core / hle / service / service . cpp <nl> <nl> # include " core / hle / service / apt_u . h " <nl> # include " core / hle / service / cfg_u . h " <nl> # include " core / hle / service / dsp_dsp . h " <nl> + # include " core / hle / service / err_f . h " <nl> # include " core / hle / service / fs_user . h " <nl> # include " core / hle / service / gsp_gpu . h " <nl> # include " core / hle / service / hid_user . h " <nl> void Init ( ) { <nl> g_manager - > AddService ( new APT_U : : Interface ) ; <nl> g_manager - > AddService ( new CFG_U : : Interface ) ; <nl> g_manager - > AddService ( new DSP_DSP : : Interface ) ; <nl> + g_manager - > AddService ( new ERR_F : : Interface ) ; <nl> g_manager - > AddService ( new FS_User : : Interface ) ; <nl> g_manager - > AddService ( new GSP_GPU : : Interface ) ; <nl> g_manager - > AddService ( new HID_User : : Interface ) ; <nl> | Merge pull request from archshift / errf | yuzu-emu/yuzu | 2ca12e7f3899a58e112ee8bb4e46d11ca61f7152 | 2014-11-02T03:43:52Z |
deleted file mode 100644 <nl> index b54cb52278e . . 00000000000 <nl> mmm a / src / third_party / fdlibm / LICENSE <nl> ppp / dev / null <nl> <nl> - Copyright ( C ) 1993 - 2004 by Sun Microsystems , Inc . All rights reserved . <nl> - <nl> - Developed at SunSoft , a Sun Microsystems , Inc . business . <nl> - Permission to use , copy , modify , and distribute this <nl> - software is freely granted , provided that this notice <nl> - is preserved . <nl> deleted file mode 100644 <nl> index ea8fdb6ce10 . . 00000000000 <nl> mmm a / src / third_party / fdlibm / README . v8 <nl> ppp / dev / null <nl> <nl> - Name : Freely Distributable LIBM <nl> - Short Name : fdlibm <nl> - URL : http : / / www . netlib . org / fdlibm / <nl> - Version : 5 . 3 <nl> - License : Freely Distributable . <nl> - License File : LICENSE . <nl> - Security Critical : yes . <nl> - License Android Compatible : yes . <nl> - <nl> - Description : <nl> - This is used to provide a accurate implementation for trigonometric functions <nl> - used in V8 . <nl> - <nl> - Local Modifications : <nl> - For the use in V8 , fdlibm has been reduced to include only sine , cosine and <nl> - tangent . To make inlining into generated code possible , a large portion of <nl> - that has been translated to Javascript . The rest remains in C , but has been <nl> - refactored and reformatted to interoperate with the rest of V8 . <nl> deleted file mode 100644 <nl> index ffb67de7f1b . . 00000000000 <nl> mmm a / src / third_party / fdlibm / fdlibm . js <nl> ppp / dev / null <nl> <nl> - / / The following is adapted from fdlibm ( http : / / www . netlib . org / fdlibm ) , <nl> - / / <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - / / Copyright ( C ) 1993 - 2004 by Sun Microsystems , Inc . All rights reserved . <nl> - / / <nl> - / / Developed at SunSoft , a Sun Microsystems , Inc . business . <nl> - / / Permission to use , copy , modify , and distribute this <nl> - / / software is freely granted , provided that this notice <nl> - / / is preserved . <nl> - / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - / / <nl> - / / The original source code covered by the above license above has been <nl> - / / modified significantly by Google Inc . <nl> - / / Copyright 2014 the V8 project authors . All rights reserved . <nl> - / / <nl> - / / The following is a straightforward translation of fdlibm routines <nl> - / / by Raymond Toy ( rtoy @ google . com ) . <nl> - <nl> - ( function ( global , utils ) { <nl> - <nl> - " use strict " ; <nl> - <nl> - % CheckIsBootstrapping ( ) ; <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - / / Imports <nl> - <nl> - var GlobalMath = global . Math ; <nl> - <nl> - utils . Import ( function ( from ) { } ) ; <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - <nl> - utils . InstallFunctions ( GlobalMath , DONT_ENUM , [ ] ) ; <nl> - <nl> - } ) <nl> | Removed fdlibm . js , as it is now an empty shell . | v8/v8 | 47f543305e396c8e10cfbff4a510f55ea2fedcfa | 2016-07-05T03:57:17Z |
mmm a / docs / en / introduction / adopters . md <nl> ppp b / docs / en / introduction / adopters . md <nl> <nl> # ClickHouse Adopters <nl> <nl> - ! ! ! note " Disclaimer " <nl> + ! ! ! warning " Disclaimer " <nl> The following list of companies using ClickHouse and their success stories is assembled from public sources , thus might differ from current reality . We ' d really appreciate if you share the story of adopting ClickHouse in your company and [ add it to the list ] ( https : / / github . com / ClickHouse / ClickHouse / edit / master / docs / en / introduction / adopters . md ) , but please make sure you won ' t have any NDA issues by doing so . Providing updates with publications by other companies is also useful . <nl> <nl> | Company | Industry | Usecase | Cluster Size | ( Un ) Compressed Data Size < abbr title = " of single replica " > < sup > * < / sup > < / abbr > | Reference | <nl> | Update adopters . md | ClickHouse/ClickHouse | e8b54cd6a343d44673a0528b686df627d5d5e792 | 2020-02-18T13:53:39Z |
mmm a / . gitignore <nl> ppp b / . gitignore <nl> dbms / src / Core / tests / field <nl> dbms / src / Core / tests / rvo_test <nl> dbms / src / Core / tests / string_pool <nl> dbms / src / DataStreams / tests / aggregating_stream <nl> - dbms / src / DataStreams / tests / block_row_transforms <nl> dbms / src / DataStreams / tests / block_tab_separated_streams <nl> dbms / src / DataStreams / tests / collapsing_sorted_stream <nl> dbms / src / DataStreams / tests / expression_stream <nl> mmm a / . gitmodules <nl> ppp b / . gitmodules <nl> <nl> [ submodule " contrib / rapidjson " ] <nl> path = contrib / rapidjson <nl> url = https : / / github . com / Tencent / rapidjson <nl> - [ submodule " contrib / mimalloc " ] <nl> - path = contrib / mimalloc <nl> - url = https : / / github . com / ClickHouse - Extras / mimalloc <nl> [ submodule " contrib / fastops " ] <nl> path = contrib / fastops <nl> url = https : / / github . com / ClickHouse - Extras / fastops <nl> mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> include ( cmake / find_consistent - hashing . cmake ) <nl> include ( cmake / find_base64 . cmake ) <nl> include ( cmake / find_parquet . cmake ) <nl> include ( cmake / find_hyperscan . cmake ) <nl> - include ( cmake / find_mimalloc . cmake ) <nl> include ( cmake / find_simdjson . cmake ) <nl> include ( cmake / find_rapidjson . cmake ) <nl> include ( cmake / find_fastops . cmake ) <nl> mmm a / cmake / find_ccache . cmake <nl> ppp b / cmake / find_ccache . cmake <nl> <nl> find_program ( CCACHE_FOUND ccache ) <nl> + <nl> if ( CCACHE_FOUND AND NOT CMAKE_CXX_COMPILER_LAUNCHER MATCHES " ccache " AND NOT CMAKE_CXX_COMPILER MATCHES " ccache " ) <nl> - execute_process ( COMMAND $ { CCACHE_FOUND } " - V " OUTPUT_VARIABLE CCACHE_VERSION ) <nl> - string ( REGEX REPLACE " ccache version ( [ 0 - 9 \ \ . ] + ) . * " " \ \ 1 " CCACHE_VERSION $ { CCACHE_VERSION } ) <nl> + execute_process ( COMMAND $ { CCACHE_FOUND } " - V " OUTPUT_VARIABLE CCACHE_VERSION ) <nl> + string ( REGEX REPLACE " ccache version ( [ 0 - 9 \ \ . ] + ) . * " " \ \ 1 " CCACHE_VERSION $ { CCACHE_VERSION } ) <nl> <nl> - if ( CCACHE_VERSION VERSION_GREATER " 3 . 2 . 0 " OR NOT CMAKE_CXX_COMPILER_ID STREQUAL " Clang " ) <nl> - # message ( STATUS " Using $ { CCACHE_FOUND } $ { CCACHE_VERSION } " ) <nl> - set_property ( GLOBAL PROPERTY RULE_LAUNCH_COMPILE $ { CCACHE_FOUND } ) <nl> - set_property ( GLOBAL PROPERTY RULE_LAUNCH_LINK $ { CCACHE_FOUND } ) <nl> - else ( ) <nl> - message ( STATUS " Not using $ { CCACHE_FOUND } $ { CCACHE_VERSION } bug : https : / / bugzilla . samba . org / show_bug . cgi ? id = 8118 " ) <nl> - endif ( ) <nl> + if ( CCACHE_VERSION VERSION_GREATER " 3 . 2 . 0 " OR NOT CMAKE_CXX_COMPILER_ID STREQUAL " Clang " ) <nl> + # message ( STATUS " Using $ { CCACHE_FOUND } $ { CCACHE_VERSION } " ) <nl> + set_property ( GLOBAL PROPERTY RULE_LAUNCH_COMPILE $ { CCACHE_FOUND } ) <nl> + set_property ( GLOBAL PROPERTY RULE_LAUNCH_LINK $ { CCACHE_FOUND } ) <nl> + else ( ) <nl> + message ( STATUS " Not using $ { CCACHE_FOUND } $ { CCACHE_VERSION } bug : https : / / bugzilla . samba . org / show_bug . cgi ? id = 8118 " ) <nl> + endif ( ) <nl> endif ( ) <nl> mmm a / cmake / find_cxx . cmake <nl> ppp b / cmake / find_cxx . cmake <nl> if ( USE_LIBCXX ) <nl> find_library ( LIBCXXFS_LIBRARY c + + fs ) <nl> find_library ( LIBCXXABI_LIBRARY c + + abi ) <nl> <nl> + set ( CMAKE_CXX_FLAGS " $ { CMAKE_CXX_FLAGS } - stdlib = libc + + " ) <nl> + <nl> target_link_libraries ( global - libs INTERFACE $ { EXCEPTION_HANDLING_LIBRARY } ) <nl> else ( ) <nl> set ( LIBCXX_LIBRARY cxx ) <nl> if ( USE_LIBCXX ) <nl> target_link_libraries ( global - libs INTERFACE $ { LIBCXX_LIBRARY } $ { LIBCXXABI_LIBRARY } $ { LIBCXXFS_LIBRARY } ) <nl> <nl> set ( HAVE_LIBCXX 1 ) <nl> - set ( CMAKE_CXX_FLAGS " $ { CMAKE_CXX_FLAGS } - stdlib = libc + + " ) <nl> <nl> message ( STATUS " Using libcxx : $ { LIBCXX_LIBRARY } " ) <nl> message ( STATUS " Using libcxxfs : $ { LIBCXXFS_LIBRARY } " ) <nl> deleted file mode 100644 <nl> index 1820421379f . . 00000000000 <nl> mmm a / cmake / find_mimalloc . cmake <nl> ppp / dev / null <nl> <nl> - if ( OS_LINUX AND NOT SANITIZE AND NOT ARCH_ARM AND NOT ARCH_32 AND NOT ARCH_PPC64LE ) <nl> - option ( ENABLE_MIMALLOC " Set to FALSE to disable usage of mimalloc for internal ClickHouse caches " FALSE ) <nl> - endif ( ) <nl> - <nl> - if ( NOT EXISTS " $ { ClickHouse_SOURCE_DIR } / contrib / mimalloc / include / mimalloc . h " ) <nl> - message ( WARNING " submodule contrib / mimalloc is missing . to fix try run : \ n git submodule update - - init - - recursive " ) <nl> - return ( ) <nl> - endif ( ) <nl> - <nl> - if ( ENABLE_MIMALLOC ) <nl> - message ( FATAL_ERROR " Mimalloc is not production ready . ( Disable with cmake - D ENABLE_MIMALLOC = 0 ) . If you want to use mimalloc , you must manually remove this message . " ) <nl> - <nl> - set ( MIMALLOC_INCLUDE_DIR $ { ClickHouse_SOURCE_DIR } / contrib / mimalloc / include ) <nl> - set ( USE_MIMALLOC 1 ) <nl> - set ( MIMALLOC_LIBRARY mimalloc - static ) <nl> - message ( STATUS " Using mimalloc : $ { MIMALLOC_INCLUDE_DIR } : $ { MIMALLOC_LIBRARY } " ) <nl> - endif ( ) <nl> mmm a / contrib / libcxx - cmake / CMakeLists . txt <nl> ppp b / contrib / libcxx - cmake / CMakeLists . txt <nl> $ { LIBCXX_SOURCE_DIR } / src / random . cpp <nl> <nl> add_library ( cxx $ { SRCS } ) <nl> <nl> - target_include_directories ( cxx BEFORE PUBLIC $ < BUILD_INTERFACE : $ { LIBCXX_SOURCE_DIR } / include > ) <nl> + target_include_directories ( cxx SYSTEM BEFORE PUBLIC $ < BUILD_INTERFACE : $ { LIBCXX_SOURCE_DIR } / include > ) <nl> target_compile_definitions ( cxx PRIVATE - D_LIBCPP_BUILDING_LIBRARY - DLIBCXX_BUILDING_LIBCXXABI ) <nl> target_compile_options ( cxx PUBLIC - nostdinc + + - Wno - reserved - id - macro ) <nl> target_link_libraries ( cxx PUBLIC cxxabi ) <nl> mmm a / contrib / libcxxabi - cmake / CMakeLists . txt <nl> ppp b / contrib / libcxxabi - cmake / CMakeLists . txt <nl> target_include_directories ( cxxabi SYSTEM BEFORE <nl> ) <nl> target_compile_definitions ( cxxabi PRIVATE - D_LIBCPP_BUILDING_LIBRARY ) <nl> target_compile_options ( cxxabi PRIVATE - nostdinc + + - fno - sanitize = undefined - Wno - macro - redefined ) # If we don ' t disable UBSan , infinite recursion happens in dynamic_cast . <nl> - <nl> - if ( USE_UNWIND ) <nl> - target_link_libraries ( cxxabi PRIVATE $ { UNWIND_LIBRARIES } ) <nl> - else ( ) <nl> - target_link_libraries ( cxxabi PRIVATE gcc_eh ) <nl> - endif ( ) <nl> + target_link_libraries ( cxxabi PUBLIC $ { EXCEPTION_HANDLING_LIBRARY } ) <nl> <nl> install ( <nl> TARGETS cxxabi <nl> deleted file mode 160000 <nl> index a787bdebce9 . . 00000000000 <nl> mmm a / contrib / mimalloc <nl> ppp / dev / null <nl> @ @ - 1 + 0 , 0 @ @ <nl> - Subproject commit a787bdebce94bf3776dc0d1ad597917f479ab8d5 <nl> mmm a / dbms / CMakeLists . txt <nl> ppp b / dbms / CMakeLists . txt <nl> if ( RE2_INCLUDE_DIR ) <nl> target_include_directories ( clickhouse_common_io SYSTEM BEFORE PUBLIC $ { RE2_INCLUDE_DIR } ) <nl> endif ( ) <nl> <nl> - if ( USE_MIMALLOC ) <nl> - target_include_directories ( clickhouse_common_io SYSTEM BEFORE PUBLIC $ { MIMALLOC_INCLUDE_DIR } ) <nl> - target_link_libraries ( clickhouse_common_io PRIVATE $ { MIMALLOC_LIBRARY } ) <nl> - endif ( ) <nl> - <nl> if ( CPUID_LIBRARY ) <nl> target_link_libraries ( clickhouse_common_io PRIVATE $ { CPUID_LIBRARY } ) <nl> endif ( ) <nl> mmm a / dbms / programs / performance - test / PerformanceTestInfo . cpp <nl> ppp b / dbms / programs / performance - test / PerformanceTestInfo . cpp <nl> void PerformanceTestInfo : : applySettings ( XMLConfigurationPtr config ) <nl> } <nl> <nl> extractSettings ( config , " settings " , config_settings , settings_to_apply ) ; <nl> - settings . loadFromChanges ( settings_to_apply ) ; <nl> + settings . applyChanges ( settings_to_apply ) ; <nl> <nl> if ( settings_contain ( " average_rows_speed_precision " ) ) <nl> TestStats : : avg_rows_speed_precision = <nl> mmm a / dbms / programs / server / Server . cpp <nl> ppp b / dbms / programs / server / Server . cpp <nl> int Server : : main ( const std : : vector < std : : string > & / * args * / ) <nl> <nl> / / / Init trace collector only after trace_log system table was created <nl> / / / Disable it if we collect test coverage information , because it will work extremely slow . <nl> - # if USE_UNWIND & & ! WITH_COVERAGE <nl> + / / / <nl> + / / / It also cannot work with sanitizers . <nl> + / / / Sanitizers are using quick " frame walking " stack unwinding ( this implies - fno - omit - frame - pointer ) <nl> + / / / And they do unwiding frequently ( on every malloc / free , thread / mutex operations , etc ) . <nl> + / / / They change % rbp during unwinding and it confuses libunwind if signal comes during sanitizer unwiding <nl> + / / / and query profiler decide to unwind stack with libunwind at this moment . <nl> + / / / <nl> + / / / Symptoms : you ' ll get silent Segmentation Fault - without sanitizer message and without usual ClickHouse diagnostics . <nl> + / / / <nl> + / / / Look at compiler - rt / lib / sanitizer_common / sanitizer_stacktrace . h <nl> + / / / <nl> + # if USE_UNWIND & & ! WITH_COVERAGE & & ! defined ( SANITIZER ) <nl> / / / QueryProfiler cannot work reliably with any other libunwind or without PHDR cache . <nl> if ( hasPHDRCache ( ) ) <nl> global_context - > initializeTraceCollector ( ) ; <nl> mmm a / dbms / src / Common / ErrorCodes . cpp <nl> ppp b / dbms / src / Common / ErrorCodes . cpp <nl> namespace ErrorCodes <nl> extern const int VIOLATED_CONSTRAINT = 469 ; <nl> extern const int QUERY_IS_NOT_SUPPORTED_IN_LIVE_VIEW = 470 ; <nl> extern const int SETTINGS_ARE_NOT_SUPPORTED = 471 ; <nl> - extern const int IMMUTABLE_SETTING = 472 ; <nl> + extern const int READONLY_SETTING = 472 ; <nl> + extern const int DEADLOCK_AVOIDED = 473 ; <nl> + extern const int INVALID_TEMPLATE_FORMAT = 474 ; <nl> <nl> extern const int KEEPER_EXCEPTION = 999 ; <nl> extern const int POCO_EXCEPTION = 1000 ; <nl> deleted file mode 100644 <nl> index 04e61a5de16 . . 00000000000 <nl> mmm a / dbms / src / Common / MiAllocator . cpp <nl> ppp / dev / null <nl> <nl> - # include " MiAllocator . h " <nl> - <nl> - # if USE_MIMALLOC <nl> - # include < mimalloc . h > <nl> - <nl> - # include < Common / Exception . h > <nl> - # include < Common / formatReadable . h > <nl> - # include < IO / WriteHelpers . h > <nl> - <nl> - namespace DB <nl> - { <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int CANNOT_ALLOCATE_MEMORY ; <nl> - } <nl> - <nl> - void * MiAllocator : : alloc ( size_t size , size_t alignment ) <nl> - { <nl> - void * ptr ; <nl> - if ( alignment = = 0 ) <nl> - { <nl> - ptr = mi_malloc ( size ) ; <nl> - if ( ! ptr ) <nl> - DB : : throwFromErrno ( " MiAllocator : Cannot allocate in mimalloc " + formatReadableSizeWithBinarySuffix ( size ) + " . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - } <nl> - else <nl> - { <nl> - ptr = mi_malloc_aligned ( size , alignment ) ; <nl> - if ( ! ptr ) <nl> - DB : : throwFromErrno ( " MiAllocator : Cannot allocate in mimalloc ( mi_malloc_aligned ) " + formatReadableSizeWithBinarySuffix ( size ) + " with alignment " + toString ( alignment ) + " . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - } <nl> - return ptr ; <nl> - } <nl> - <nl> - void MiAllocator : : free ( void * buf , size_t ) <nl> - { <nl> - mi_free ( buf ) ; <nl> - } <nl> - <nl> - void * MiAllocator : : realloc ( void * old_ptr , size_t , size_t new_size , size_t alignment ) <nl> - { <nl> - if ( old_ptr = = nullptr ) <nl> - return alloc ( new_size , alignment ) ; <nl> - <nl> - if ( new_size = = 0 ) <nl> - { <nl> - mi_free ( old_ptr ) ; <nl> - return nullptr ; <nl> - } <nl> - <nl> - void * ptr ; <nl> - <nl> - if ( alignment = = 0 ) <nl> - { <nl> - ptr = mi_realloc ( old_ptr , alignment ) ; <nl> - if ( ! ptr ) <nl> - DB : : throwFromErrno ( " MiAllocator : Cannot reallocate in mimalloc " + formatReadableSizeWithBinarySuffix ( size ) + " . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - } <nl> - else <nl> - { <nl> - ptr = mi_realloc_aligned ( old_ptr , new_size , alignment ) ; <nl> - if ( ! ptr ) <nl> - DB : : throwFromErrno ( " MiAllocator : Cannot reallocate in mimalloc ( mi_realloc_aligned ) " + formatReadableSizeWithBinarySuffix ( size ) + " with alignment " + toString ( alignment ) + " . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - } <nl> - return ptr ; <nl> - } <nl> - <nl> - } <nl> - <nl> - # endif <nl> deleted file mode 100644 <nl> index 127be82434b . . 00000000000 <nl> mmm a / dbms / src / Common / MiAllocator . h <nl> ppp / dev / null <nl> <nl> - # pragma once <nl> - <nl> - # include < Common / config . h > <nl> - <nl> - # if USE_MIMALLOC <nl> - # include < cstddef > <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - / * <nl> - * This is a different allocator that is based on mimalloc ( Microsoft malloc ) . <nl> - * It can be used separately from main allocator to catch heap corruptions and vulnerabilities ( for example , for caches ) . <nl> - * We use MI_SECURE mode in mimalloc to achieve such behaviour . <nl> - * / <nl> - struct MiAllocator <nl> - { <nl> - static void * alloc ( size_t size , size_t alignment = 0 ) ; <nl> - <nl> - static void free ( void * buf , size_t ) ; <nl> - <nl> - static void * realloc ( void * old_ptr , size_t , size_t new_size , size_t alignment = 0 ) ; <nl> - } ; <nl> - <nl> - } <nl> - <nl> - # endif <nl> mmm a / dbms / src / Common / ProfileEvents . cpp <nl> ppp b / dbms / src / Common / ProfileEvents . cpp <nl> <nl> M ( MarkCacheMisses , " " ) \ <nl> M ( CreatedReadBufferOrdinary , " " ) \ <nl> M ( CreatedReadBufferAIO , " " ) \ <nl> + M ( CreatedReadBufferAIOFailed , " " ) \ <nl> M ( CreatedWriteBufferOrdinary , " " ) \ <nl> M ( CreatedWriteBufferAIO , " " ) \ <nl> + M ( CreatedWriteBufferAIOFailed , " " ) \ <nl> M ( DiskReadElapsedMicroseconds , " Total time spent waiting for read syscall . This include reads from page cache . " ) \ <nl> M ( DiskWriteElapsedMicroseconds , " Total time spent waiting for write syscall . This include writes to page cache . " ) \ <nl> M ( NetworkReceiveElapsedMicroseconds , " " ) \ <nl> mmm a / dbms / src / Common / RWLock . cpp <nl> ppp b / dbms / src / Common / RWLock . cpp <nl> <nl> # include < Common / CurrentMetrics . h > <nl> # include < Common / ProfileEvents . h > <nl> <nl> + # include < cassert > <nl> + <nl> <nl> namespace ProfileEvents <nl> { <nl> namespace DB <nl> namespace ErrorCodes <nl> { <nl> extern const int LOGICAL_ERROR ; <nl> + extern const int DEADLOCK_AVOIDED ; <nl> } <nl> <nl> <nl> class RWLockImpl : : LockHolderImpl <nl> RWLock parent ; <nl> GroupsContainer : : iterator it_group ; <nl> ClientsContainer : : iterator it_client ; <nl> - ThreadToHolder : : key_type thread_id ; <nl> QueryIdToHolder : : key_type query_id ; <nl> CurrentMetrics : : Increment active_client_increment ; <nl> <nl> class RWLockImpl : : LockHolderImpl <nl> } ; <nl> <nl> <nl> + namespace <nl> + { <nl> + / / / Global information about all read locks that query has . It is needed to avoid some type of deadlocks . <nl> + <nl> + class QueryLockInfo <nl> + { <nl> + private : <nl> + std : : mutex mutex ; <nl> + std : : map < std : : string , size_t > queries ; <nl> + <nl> + public : <nl> + void add ( const String & query_id ) <nl> + { <nl> + std : : lock_guard lock ( mutex ) ; <nl> + + + queries [ query_id ] ; <nl> + } <nl> + <nl> + void remove ( const String & query_id ) <nl> + { <nl> + std : : lock_guard lock ( mutex ) ; <nl> + auto it = queries . find ( query_id ) ; <nl> + assert ( it ! = queries . end ( ) ) ; <nl> + if ( - - it - > second = = 0 ) <nl> + queries . erase ( it ) ; <nl> + } <nl> + <nl> + void check ( const String & query_id ) <nl> + { <nl> + std : : lock_guard lock ( mutex ) ; <nl> + if ( queries . count ( query_id ) ) <nl> + throw Exception ( " Possible deadlock avoided . Client should retry . " , ErrorCodes : : DEADLOCK_AVOIDED ) ; <nl> + } <nl> + } ; <nl> + <nl> + QueryLockInfo all_read_locks ; <nl> + } <nl> + <nl> + <nl> RWLockImpl : : LockHolder RWLockImpl : : getLock ( RWLockImpl : : Type type , const String & query_id ) <nl> { <nl> Stopwatch watch ( CLOCK_MONOTONIC_COARSE ) ; <nl> RWLockImpl : : LockHolder RWLockImpl : : getLock ( RWLockImpl : : Type type , const String & <nl> GroupsContainer : : iterator it_group ; <nl> ClientsContainer : : iterator it_client ; <nl> <nl> + / / / This object is placed above unique_lock , because it may lock in destructor . <nl> + LockHolder res ; <nl> + <nl> std : : unique_lock lock ( mutex ) ; <nl> <nl> / / / Check if the same query is acquiring previously acquired lock <nl> - LockHolder existing_holder_ptr ; <nl> - <nl> - auto this_thread_id = std : : this_thread : : get_id ( ) ; <nl> - auto it_thread = thread_to_holder . find ( this_thread_id ) ; <nl> - <nl> - auto it_query = query_id_to_holder . end ( ) ; <nl> if ( query_id ! = RWLockImpl : : NO_QUERY ) <nl> - it_query = query_id_to_holder . find ( query_id ) ; <nl> - <nl> - if ( it_thread ! = thread_to_holder . end ( ) ) <nl> - existing_holder_ptr = it_thread - > second . lock ( ) ; <nl> - else if ( it_query ! = query_id_to_holder . end ( ) ) <nl> - existing_holder_ptr = it_query - > second . lock ( ) ; <nl> + { <nl> + auto it_query = query_id_to_holder . find ( query_id ) ; <nl> + if ( it_query ! = query_id_to_holder . end ( ) ) <nl> + res = it_query - > second . lock ( ) ; <nl> + } <nl> <nl> - if ( existing_holder_ptr ) <nl> + if ( res ) <nl> { <nl> / / / XXX : it means we can ' t upgrade lock from read to write - with proper waiting ! <nl> - if ( type ! = Read | | existing_holder_ptr - > it_group - > type ! = Read ) <nl> + if ( type ! = Read | | res - > it_group - > type ! = Read ) <nl> throw Exception ( " Attempt to acquire exclusive lock recursively " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - return existing_holder_ptr ; <nl> + else <nl> + return res ; <nl> } <nl> <nl> + / * * If the query already has any active read lock and tries to acquire another read lock <nl> + * but it is not in front of the queue and has to wait , deadlock is possible : <nl> + * <nl> + * Example ( four queries , two RWLocks - ' a ' and ' b ' ) : <nl> + * <nl> + * - - > time - - > <nl> + * <nl> + * q1 : ra rb <nl> + * q2 : wa <nl> + * q3 : rb ra <nl> + * q4 : wb <nl> + * <nl> + * We will throw an exception instead . <nl> + * / <nl> + <nl> if ( type = = Type : : Write | | queue . empty ( ) | | queue . back ( ) . type = = Type : : Write ) <nl> { <nl> + if ( type = = Type : : Read & & ! queue . empty ( ) & & queue . back ( ) . type = = Type : : Write & & query_id ! = RWLockImpl : : NO_QUERY ) <nl> + all_read_locks . check ( query_id ) ; <nl> + <nl> / / / Create new group of clients <nl> it_group = queue . emplace ( queue . end ( ) , type ) ; <nl> } <nl> RWLockImpl : : LockHolder RWLockImpl : : getLock ( RWLockImpl : : Type type , const String & <nl> { <nl> / / / Will append myself to last group <nl> it_group = std : : prev ( queue . end ( ) ) ; <nl> + <nl> + if ( it_group ! = queue . begin ( ) & & query_id ! = RWLockImpl : : NO_QUERY ) <nl> + all_read_locks . check ( query_id ) ; <nl> } <nl> <nl> / / / Append myself to the end of chosen group <nl> RWLockImpl : : LockHolder RWLockImpl : : getLock ( RWLockImpl : : Type type , const String & <nl> throw ; <nl> } <nl> <nl> - LockHolder res ( new LockHolderImpl ( shared_from_this ( ) , it_group , it_client ) ) ; <nl> + res . reset ( new LockHolderImpl ( shared_from_this ( ) , it_group , it_client ) ) ; <nl> <nl> / / / Wait a notification until we will be the only in the group . <nl> it_group - > cv . wait ( lock , [ & ] ( ) { return it_group = = queue . begin ( ) ; } ) ; <nl> <nl> - / / / Insert myself ( weak_ptr to the holder ) to threads set to implement recursive lock <nl> - thread_to_holder . emplace ( this_thread_id , res ) ; <nl> - res - > thread_id = this_thread_id ; <nl> - <nl> + / / / Insert myself ( weak_ptr to the holder ) to queries set to implement recursive lock <nl> if ( query_id ! = RWLockImpl : : NO_QUERY ) <nl> + { <nl> query_id_to_holder . emplace ( query_id , res ) ; <nl> + <nl> + if ( type = = Type : : Read ) <nl> + all_read_locks . add ( query_id ) ; <nl> + } <nl> res - > query_id = query_id ; <nl> <nl> finalize_metrics ( ) ; <nl> RWLockImpl : : LockHolder RWLockImpl : : getLock ( RWLockImpl : : Type type , const String & <nl> <nl> RWLockImpl : : LockHolderImpl : : ~ LockHolderImpl ( ) <nl> { <nl> - std : : unique_lock lock ( parent - > mutex ) ; <nl> + std : : lock_guard lock ( parent - > mutex ) ; <nl> <nl> / / / Remove weak_ptrs to the holder , since there are no owners of the current lock <nl> - parent - > thread_to_holder . erase ( thread_id ) ; <nl> parent - > query_id_to_holder . erase ( query_id ) ; <nl> <nl> + if ( * it_client = = RWLockImpl : : Read & & query_id ! = RWLockImpl : : NO_QUERY ) <nl> + all_read_locks . remove ( query_id ) ; <nl> + <nl> / / / Removes myself from client list of our group <nl> it_group - > clients . erase ( it_client ) ; <nl> <nl> RWLockImpl : : LockHolderImpl : : LockHolderImpl ( RWLock & & parent_ , RWLockImpl : : Groups <nl> : parent { std : : move ( parent_ ) } , it_group { it_group_ } , it_client { it_client_ } , <nl> active_client_increment { ( * it_client = = RWLockImpl : : Read ) ? CurrentMetrics : : RWLockActiveReaders <nl> : CurrentMetrics : : RWLockActiveWriters } <nl> - { } <nl> + { <nl> + } <nl> <nl> } <nl> mmm a / dbms / src / Common / RWLock . h <nl> ppp b / dbms / src / Common / RWLock . h <nl> <nl> # include < vector > <nl> # include < mutex > <nl> # include < condition_variable > <nl> - # include < thread > <nl> # include < map > <nl> # include < string > <nl> <nl> using RWLock = std : : shared_ptr < RWLockImpl > ; <nl> <nl> <nl> / / / Implements shared lock with FIFO service <nl> - / / / Can be acquired recursively ( several calls for the same query or the same OS thread ) in Read mode <nl> + / / / Can be acquired recursively ( several calls for the same query ) in Read mode <nl> / / / <nl> / / / NOTE : it is important to allow acquiring the same lock in Read mode without waiting if it is already <nl> / / / acquired by another thread of the same query . Otherwise the following deadlock is possible : <nl> class RWLockImpl : public std : : enable_shared_from_this < RWLockImpl > <nl> struct Group ; <nl> using GroupsContainer = std : : list < Group > ; <nl> using ClientsContainer = std : : list < Type > ; <nl> - using ThreadToHolder = std : : map < std : : thread : : id , std : : weak_ptr < LockHolderImpl > > ; <nl> using QueryIdToHolder = std : : map < String , std : : weak_ptr < LockHolderImpl > > ; <nl> <nl> / / / Group of clients that should be executed concurrently <nl> class RWLockImpl : public std : : enable_shared_from_this < RWLockImpl > <nl> <nl> mutable std : : mutex mutex ; <nl> GroupsContainer queue ; <nl> - ThreadToHolder thread_to_holder ; <nl> QueryIdToHolder query_id_to_holder ; <nl> } ; <nl> <nl> mmm a / dbms / src / Common / ThreadStatus . h <nl> ppp b / dbms / src / Common / ThreadStatus . h <nl> class ThreadGroupStatus <nl> InternalTextLogsQueueWeakPtr logs_queue_ptr ; <nl> <nl> std : : vector < UInt32 > thread_numbers ; <nl> + std : : vector < UInt32 > os_thread_ids ; <nl> <nl> / / / The first thread created this thread group <nl> UInt32 master_thread_number = 0 ; <nl> mmm a / dbms / src / Common / config . h . in <nl> ppp b / dbms / src / Common / config . h . in <nl> <nl> # cmakedefine01 USE_CPUID <nl> # cmakedefine01 USE_CPUINFO <nl> # cmakedefine01 USE_BROTLI <nl> - # cmakedefine01 USE_MIMALLOC <nl> # cmakedefine01 USE_UNWIND <nl> # cmakedefine01 CLICKHOUSE_SPLIT_BINARY <nl> mmm a / dbms / src / Common / tests / CMakeLists . txt <nl> ppp b / dbms / src / Common / tests / CMakeLists . txt <nl> target_link_libraries ( cow_compositions PRIVATE clickhouse_common_io ) <nl> add_executable ( stopwatch stopwatch . cpp ) <nl> target_link_libraries ( stopwatch PRIVATE clickhouse_common_io ) <nl> <nl> - add_executable ( mi_malloc_test mi_malloc_test . cpp ) <nl> - target_link_libraries ( mi_malloc_test PRIVATE clickhouse_common_io ) <nl> - <nl> add_executable ( symbol_index symbol_index . cpp ) <nl> target_link_libraries ( symbol_index PRIVATE clickhouse_common_io ) <nl> mmm a / dbms / src / Common / tests / gtest_rw_lock . cpp <nl> ppp b / dbms / src / Common / tests / gtest_rw_lock . cpp <nl> <nl> <nl> using namespace DB ; <nl> <nl> + namespace DB <nl> + { <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int DEADLOCK_AVOIDED ; <nl> + } <nl> + } <nl> + <nl> <nl> TEST ( Common , RWLock_1 ) <nl> { <nl> TEST ( Common , RWLock_Recursive ) <nl> { <nl> for ( int i = 0 ; i < 2 * cycles ; + + i ) <nl> { <nl> - auto lock = fifo_lock - > getLock ( RWLockImpl : : Write , RWLockImpl : : NO_QUERY ) ; <nl> + auto lock = fifo_lock - > getLock ( RWLockImpl : : Write , " q1 " ) ; <nl> <nl> auto sleep_for = std : : chrono : : duration < int , std : : micro > ( std : : uniform_int_distribution < > ( 1 , 100 ) ( gen ) ) ; <nl> std : : this_thread : : sleep_for ( sleep_for ) ; <nl> TEST ( Common , RWLock_Recursive ) <nl> { <nl> for ( int i = 0 ; i < cycles ; + + i ) <nl> { <nl> - auto lock1 = fifo_lock - > getLock ( RWLockImpl : : Read , RWLockImpl : : NO_QUERY ) ; <nl> + auto lock1 = fifo_lock - > getLock ( RWLockImpl : : Read , " q2 " ) ; <nl> <nl> auto sleep_for = std : : chrono : : duration < int , std : : micro > ( std : : uniform_int_distribution < > ( 1 , 100 ) ( gen ) ) ; <nl> std : : this_thread : : sleep_for ( sleep_for ) ; <nl> <nl> - auto lock2 = fifo_lock - > getLock ( RWLockImpl : : Read , RWLockImpl : : NO_QUERY ) ; <nl> + auto lock2 = fifo_lock - > getLock ( RWLockImpl : : Read , " q2 " ) ; <nl> <nl> - EXPECT_ANY_THROW ( { fifo_lock - > getLock ( RWLockImpl : : Write , RWLockImpl : : NO_QUERY ) ; } ) ; <nl> + EXPECT_ANY_THROW ( { fifo_lock - > getLock ( RWLockImpl : : Write , " q2 " ) ; } ) ; <nl> } <nl> <nl> - fifo_lock - > getLock ( RWLockImpl : : Write , RWLockImpl : : NO_QUERY ) ; <nl> + fifo_lock - > getLock ( RWLockImpl : : Write , " q2 " ) ; <nl> + } ) ; <nl> + <nl> + t1 . join ( ) ; <nl> + t2 . join ( ) ; <nl> + } <nl> + <nl> + <nl> + TEST ( Common , RWLock_Deadlock ) <nl> + { <nl> + static auto lock1 = RWLockImpl : : create ( ) ; <nl> + static auto lock2 = RWLockImpl : : create ( ) ; <nl> + <nl> + / * * <nl> + * q1 : r1 r2 <nl> + * q2 : w1 <nl> + * q3 : r2 r1 <nl> + * q4 : w2 <nl> + * / <nl> + <nl> + std : : thread t1 ( [ & ] ( ) <nl> + { <nl> + auto holder1 = lock1 - > getLock ( RWLockImpl : : Read , " q1 " ) ; <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + try <nl> + { <nl> + auto holder2 = lock2 - > getLock ( RWLockImpl : : Read , " q1 " ) ; <nl> + } <nl> + catch ( const Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = ErrorCodes : : DEADLOCK_AVOIDED ) <nl> + throw ; <nl> + } <nl> + } ) ; <nl> + <nl> + std : : thread t2 ( [ & ] ( ) <nl> + { <nl> + usleep ( 100000 ) ; <nl> + auto holder1 = lock1 - > getLock ( RWLockImpl : : Write , " q2 " ) ; <nl> + } ) ; <nl> + <nl> + std : : thread t3 ( [ & ] ( ) <nl> + { <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + auto holder2 = lock2 - > getLock ( RWLockImpl : : Read , " q3 " ) ; <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + try <nl> + { <nl> + auto holder1 = lock1 - > getLock ( RWLockImpl : : Read , " q3 " ) ; <nl> + } <nl> + catch ( const Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = ErrorCodes : : DEADLOCK_AVOIDED ) <nl> + throw ; <nl> + } <nl> + } ) ; <nl> + <nl> + std : : thread t4 ( [ & ] ( ) <nl> + { <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + usleep ( 100000 ) ; <nl> + auto holder2 = lock2 - > getLock ( RWLockImpl : : Write , " q4 " ) ; <nl> } ) ; <nl> <nl> t1 . join ( ) ; <nl> t2 . join ( ) ; <nl> + t3 . join ( ) ; <nl> + t4 . join ( ) ; <nl> } <nl> <nl> <nl> deleted file mode 100644 <nl> index ce1e4a3a770 . . 00000000000 <nl> mmm a / dbms / src / Common / tests / mi_malloc_test . cpp <nl> ppp / dev / null <nl> <nl> - / * * In addition to ClickHouse ( Apache 2 ) license , this file can be also used under MIT license : <nl> - <nl> - MIT License <nl> - <nl> - Copyright ( c ) 2019 Yandex LLC , Alexey Milovidov <nl> - <nl> - Permission is hereby granted , free of charge , to any person obtaining a copy <nl> - of this software and associated documentation files ( the " Software " ) , to deal <nl> - in the Software without restriction , including without limitation the rights <nl> - to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> - copies of the Software , and to permit persons to whom the Software is <nl> - furnished to do so , subject to the following conditions : <nl> - <nl> - The above copyright notice and this permission notice shall be included in all <nl> - copies or substantial portions of the Software . <nl> - <nl> - THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> - IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> - LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE <nl> - SOFTWARE . <nl> - <nl> - * / <nl> - <nl> - # include < map > <nl> - # include < vector > <nl> - # include < cstdint > <nl> - # include < random > <nl> - # include < stdexcept > <nl> - # include < iostream > <nl> - <nl> - # include < Common / config . h > <nl> - <nl> - / / # undef USE_MIMALLOC <nl> - / / # define USE_MIMALLOC 0 <nl> - <nl> - # if USE_MIMALLOC <nl> - <nl> - # include < mimalloc . h > <nl> - # define malloc mi_malloc <nl> - # define free mi_free <nl> - <nl> - # else <nl> - <nl> - # include < stdlib . h > <nl> - <nl> - # endif <nl> - <nl> - <nl> - size_t total_size { 0 } ; <nl> - <nl> - struct Allocation <nl> - { <nl> - void * ptr = nullptr ; <nl> - size_t size = 0 ; <nl> - <nl> - Allocation ( ) { } <nl> - <nl> - Allocation ( size_t size_ ) <nl> - : size ( size_ ) <nl> - { <nl> - ptr = malloc ( size ) ; <nl> - if ( ! ptr ) <nl> - throw std : : runtime_error ( " Cannot allocate memory " ) ; <nl> - total_size + = size ; <nl> - } <nl> - <nl> - ~ Allocation ( ) <nl> - { <nl> - if ( ptr ) <nl> - { <nl> - free ( ptr ) ; <nl> - total_size - = size ; <nl> - } <nl> - ptr = nullptr ; <nl> - } <nl> - <nl> - Allocation ( const Allocation & ) = delete ; <nl> - <nl> - Allocation ( Allocation & & rhs ) <nl> - { <nl> - ptr = rhs . ptr ; <nl> - size = rhs . size ; <nl> - rhs . ptr = nullptr ; <nl> - rhs . size = 0 ; <nl> - } <nl> - } ; <nl> - <nl> - <nl> - int main ( int , char * * ) <nl> - { <nl> - std : : vector < Allocation > allocations ; <nl> - <nl> - constexpr size_t limit = 100000000 ; <nl> - constexpr size_t min_alloc_size = 65536 ; <nl> - constexpr size_t max_alloc_size = 10000000 ; <nl> - <nl> - std : : mt19937 rng ; <nl> - auto distribution = std : : uniform_int_distribution ( min_alloc_size , max_alloc_size ) ; <nl> - <nl> - size_t total_allocations = 0 ; <nl> - <nl> - while ( true ) <nl> - { <nl> - size_t size = distribution ( rng ) ; <nl> - <nl> - while ( total_size + size > limit ) <nl> - allocations . pop_back ( ) ; <nl> - <nl> - allocations . emplace_back ( size ) ; <nl> - <nl> - + + total_allocations ; <nl> - if ( total_allocations % ( 1ULL < < 20 ) = = 0 ) <nl> - std : : cerr < < " Total allocations : " < < total_allocations < < " \ n " ; <nl> - } <nl> - } <nl> mmm a / dbms / src / Core / Defines . h <nl> ppp b / dbms / src / Core / Defines . h <nl> <nl> # endif <nl> # endif <nl> <nl> + / / / TODO Strange enough , there is no way to detect UB sanitizer . <nl> + <nl> / / / Explicitly allow undefined behaviour for certain functions . Use it as a function attribute . <nl> / / / It is useful in case when compiler cannot see ( and exploit ) it , but UBSan can . <nl> / / / Example : multiplication of signed integers with possibility of overflow when both sides are from user input . <nl> mmm a / dbms / src / Core / Settings . h <nl> ppp b / dbms / src / Core / Settings . h <nl> struct Settings : public SettingsCollection < Settings > <nl> * but we are not going to do it , because settings is used everywhere as static struct fields . <nl> * / <nl> <nl> - / / / M ( mutable ) for normal settings , IM ( immutable ) for not updateable settings . <nl> - # define LIST_OF_SETTINGS ( M , IM ) \ <nl> + # define LIST_OF_SETTINGS ( M ) \ <nl> M ( SettingUInt64 , min_compress_block_size , 65536 , " The actual size of the block to compress , if the uncompressed data less than max_compress_block_size is no less than this value and no less than the volume of data for one mark . " ) \ <nl> M ( SettingUInt64 , max_compress_block_size , 1048576 , " The maximum size of blocks of uncompressed data before compressing for writing to a table . " ) \ <nl> M ( SettingUInt64 , max_block_size , DEFAULT_BLOCK_SIZE , " Maximum block size for reading " ) \ <nl> struct Settings : public SettingsCollection < Settings > <nl> M ( SettingMilliseconds , stream_flush_interval_ms , 7500 , " Timeout for flushing data from streaming storages . " ) \ <nl> M ( SettingMilliseconds , stream_poll_timeout_ms , 500 , " Timeout for polling data from / to streaming storages . " ) \ <nl> M ( SettingString , format_schema , " " , " Schema identifier ( used by schema - based formats ) " ) \ <nl> + M ( SettingString , format_schema_rows , " " , " Row format string for Template format " ) \ <nl> + M ( SettingString , format_schema_rows_between_delimiter , " \ n " , " Delimiter between rows for Template format " ) \ <nl> M ( SettingBool , insert_allow_materialized_columns , 0 , " If setting is enabled , Allow materialized columns in INSERT . " ) \ <nl> M ( SettingSeconds , http_connection_timeout , DEFAULT_HTTP_READ_BUFFER_CONNECTION_TIMEOUT , " HTTP connection timeout . " ) \ <nl> M ( SettingSeconds , http_send_timeout , DEFAULT_HTTP_READ_BUFFER_TIMEOUT , " HTTP send timeout " ) \ <nl> mmm a / dbms / src / Core / SettingsCommon . h <nl> ppp b / dbms / src / Core / SettingsCommon . h <nl> class Field ; <nl> class ReadBuffer ; <nl> class WriteBuffer ; <nl> <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int IMMUTABLE_SETTING ; <nl> - } <nl> - <nl> / * * One setting for any type . <nl> * Stores a value within itself , as well as a flag - whether the value was changed . <nl> * This is done so that you can send to the remote servers only changed settings ( or explicitly specified in the config ) values . <nl> class SettingsCollection <nl> using DeserializeFunction = void ( * ) ( Derived & , ReadBuffer & buf ) ; <nl> using CastValueWithoutApplyingFunction = Field ( * ) ( const Field & ) ; <nl> <nl> + <nl> struct MemberInfo <nl> { <nl> IsChangedFunction is_changed ; <nl> StringRef name ; <nl> StringRef description ; <nl> - / / / Can be updated after first load for config / definition . <nl> - / / / Non updatable settings can be ` changed ` , <nl> - / / / if they were overwritten in config / definition . <nl> - const bool updateable ; <nl> GetStringFunction get_string ; <nl> GetFieldFunction get_field ; <nl> SetStringFunction set_string ; <nl> class SettingsCollection <nl> const_reference ( const const_reference & src ) = default ; <nl> const StringRef & getName ( ) const { return member - > name ; } <nl> const StringRef & getDescription ( ) const { return member - > description ; } <nl> - bool isUpdateable ( ) const { return member - > updateable ; } <nl> bool isChanged ( ) const { return member - > isChanged ( * collection ) ; } <nl> Field getValue ( ) const { return member - > get_field ( * collection ) ; } <nl> String getValueAsString ( ) const { return member - > get_string ( * collection ) ; } <nl> class SettingsCollection <nl> reference ( const const_reference & src ) : const_reference ( src ) { } <nl> void setValue ( const Field & value ) { this - > member - > set_field ( * const_cast < Derived * > ( this - > collection ) , value ) ; } <nl> void setValue ( const String & value ) { this - > member - > set_string ( * const_cast < Derived * > ( this - > collection ) , value ) ; } <nl> - void updateValue ( const Field & value ) <nl> - { <nl> - if ( ! this - > member - > updateable ) <nl> - throw Exception ( " Setting ' " + this - > member - > name . toString ( ) + " ' is restricted for updates . " , ErrorCodes : : IMMUTABLE_SETTING ) ; <nl> - setValue ( value ) ; <nl> - } <nl> - void updateValue ( const String & value ) <nl> - { <nl> - if ( ! this - > member - > updateable ) <nl> - throw Exception ( " Setting ' " + this - > member - > name . toString ( ) + " ' is restricted for updates . " , ErrorCodes : : IMMUTABLE_SETTING ) ; <nl> - setValue ( value ) ; <nl> - } <nl> } ; <nl> <nl> / / / Iterator to iterating through all the settings . <nl> class SettingsCollection <nl> void set ( size_t index , const String & value ) { ( * this ) [ index ] . setValue ( value ) ; } <nl> void set ( const String & name , const String & value ) { ( * this ) [ name ] . setValue ( value ) ; } <nl> <nl> - / / / Updates setting ' s value . Checks it ' mutability . <nl> - void update ( size_t index , const Field & value ) { ( * this ) [ index ] . updateValue ( value ) ; } <nl> - <nl> - void update ( const String & name , const Field & value ) { ( * this ) [ name ] . updateValue ( value ) ; } <nl> - <nl> - void update ( size_t index , const String & value ) { ( * this ) [ index ] . updateValue ( value ) ; } <nl> - <nl> - void update ( const String & name , const String & value ) { ( * this ) [ name ] . updateValue ( value ) ; } <nl> - <nl> / / / Returns value of a setting . <nl> Field get ( size_t index ) const { return ( * this ) [ index ] . getValue ( ) ; } <nl> Field get ( const String & name ) const { return ( * this ) [ name ] . getValue ( ) ; } <nl> class SettingsCollection <nl> return found_changes ; <nl> } <nl> <nl> - / / / Applies change to the settings . Doesn ' t check settings mutability . <nl> - void loadFromChange ( const SettingChange & change ) <nl> + / / / Applies change to concrete setting . <nl> + void applyChange ( const SettingChange & change ) <nl> { <nl> set ( change . name , change . value ) ; <nl> } <nl> <nl> - / / / Applies changes to the settings . Should be used in initial settings loading . <nl> - / / / ( on table creation or loading from config ) <nl> - void loadFromChanges ( const SettingsChanges & changes ) <nl> - { <nl> - for ( const SettingChange & change : changes ) <nl> - loadFromChange ( change ) ; <nl> - } <nl> - <nl> - / / / Applies change to the settings , checks settings mutability . <nl> - void updateFromChange ( const SettingChange & change ) <nl> - { <nl> - update ( change . name , change . value ) ; <nl> - } <nl> - <nl> - / / / Applies changes to the settings . Should be used for settigns update . <nl> - / / / ( ALTER MODIFY SETTINGS ) <nl> - void updateFromChanges ( const SettingsChanges & changes ) <nl> + / / / Applies changes to the settings . <nl> + void applyChanges ( const SettingsChanges & changes ) <nl> { <nl> for ( const SettingChange & change : changes ) <nl> - updateFromChange ( change ) ; <nl> + applyChange ( change ) ; <nl> } <nl> <nl> - <nl> void copyChangesFrom ( const Derived & src ) <nl> { <nl> for ( const auto & member : members ( ) ) <nl> class SettingsCollection <nl> } ; <nl> <nl> # define DECLARE_SETTINGS_COLLECTION ( LIST_OF_SETTINGS_MACRO ) \ <nl> - LIST_OF_SETTINGS_MACRO ( DECLARE_SETTINGS_COLLECTION_DECLARE_VARIABLES_HELPER_ , DECLARE_SETTINGS_COLLECTION_DECLARE_VARIABLES_HELPER_ ) <nl> + LIST_OF_SETTINGS_MACRO ( DECLARE_SETTINGS_COLLECTION_DECLARE_VARIABLES_HELPER_ ) <nl> <nl> <nl> # define IMPLEMENT_SETTINGS_COLLECTION ( DERIVED_CLASS_NAME , LIST_OF_SETTINGS_MACRO ) \ <nl> class SettingsCollection <nl> using Derived = DERIVED_CLASS_NAME ; \ <nl> struct Functions \ <nl> { \ <nl> - LIST_OF_SETTINGS_MACRO ( IMPLEMENT_SETTINGS_COLLECTION_DEFINE_FUNCTIONS_HELPER_ , IMPLEMENT_SETTINGS_COLLECTION_DEFINE_FUNCTIONS_HELPER_ ) \ <nl> + LIST_OF_SETTINGS_MACRO ( IMPLEMENT_SETTINGS_COLLECTION_DEFINE_FUNCTIONS_HELPER_ ) \ <nl> } ; \ <nl> - LIST_OF_SETTINGS_MACRO ( IMPLEMENT_SETTINGS_COLLECTION_ADD_MUTABLE_MEMBER_INFO_HELPER_ , IMPLEMENT_SETTINGS_COLLECTION_ADD_IMMUTABLE_MEMBER_INFO_HELPER_ ) \ <nl> + LIST_OF_SETTINGS_MACRO ( IMPLEMENT_SETTINGS_COLLECTION_ADD_MEMBER_INFO_HELPER_ ) \ <nl> } <nl> <nl> <nl> class SettingsCollection <nl> static void NAME # # _setField ( Derived & collection , const Field & value ) { collection . NAME . set ( value ) ; } \ <nl> static void NAME # # _serialize ( const Derived & collection , WriteBuffer & buf ) { collection . NAME . serialize ( buf ) ; } \ <nl> static void NAME # # _deserialize ( Derived & collection , ReadBuffer & buf ) { collection . NAME . deserialize ( buf ) ; } \ <nl> - static Field NAME # # _castValueWithoutApplying ( const Field & value ) { TYPE temp { DEFAULT } ; temp . set ( value ) ; return temp . toField ( ) ; } <nl> + static Field NAME # # _castValueWithoutApplying ( const Field & value ) { TYPE temp { DEFAULT } ; temp . set ( value ) ; return temp . toField ( ) ; } \ <nl> <nl> <nl> - # define IMPLEMENT_SETTINGS_COLLECTION_ADD_MUTABLE_MEMBER_INFO_HELPER_ ( TYPE , NAME , DEFAULT , DESCRIPTION ) \ <nl> + # define IMPLEMENT_SETTINGS_COLLECTION_ADD_MEMBER_INFO_HELPER_ ( TYPE , NAME , DEFAULT , DESCRIPTION ) \ <nl> add ( { [ ] ( const Derived & d ) { return d . NAME . changed ; } , \ <nl> - StringRef ( # NAME , strlen ( # NAME ) ) , StringRef ( DESCRIPTION , strlen ( DESCRIPTION ) ) , true , \ <nl> + StringRef ( # NAME , strlen ( # NAME ) ) , StringRef ( DESCRIPTION , strlen ( DESCRIPTION ) ) , \ <nl> & Functions : : NAME # # _getString , & Functions : : NAME # # _getField , \ <nl> & Functions : : NAME # # _setString , & Functions : : NAME # # _setField , \ <nl> & Functions : : NAME # # _serialize , & Functions : : NAME # # _deserialize , \ <nl> & Functions : : NAME # # _castValueWithoutApplying } ) ; <nl> - <nl> - # define IMPLEMENT_SETTINGS_COLLECTION_ADD_IMMUTABLE_MEMBER_INFO_HELPER_ ( TYPE , NAME , DEFAULT , DESCRIPTION ) \ <nl> - add ( { [ ] ( const Derived & d ) { return d . NAME . changed ; } , \ <nl> - StringRef ( # NAME , strlen ( # NAME ) ) , StringRef ( DESCRIPTION , strlen ( DESCRIPTION ) ) , false , \ <nl> - & Functions : : NAME # # _getString , & Functions : : NAME # # _getField , \ <nl> - & Functions : : NAME # # _setString , & Functions : : NAME # # _setField , \ <nl> - & Functions : : NAME # # _serialize , & Functions : : NAME # # _deserialize , \ <nl> - & Functions : : NAME # # _castValueWithoutApplying } ) ; <nl> } <nl> mmm a / dbms / src / DataStreams / IBlockInputStream . h <nl> ppp b / dbms / src / DataStreams / IBlockInputStream . h <nl> class IBlockInputStream <nl> / / / NOTE : Acquire a read lock , therefore f ( ) should be thread safe <nl> std : : shared_lock lock ( children_mutex ) ; <nl> <nl> - for ( auto & child : children ) <nl> + / / Reduce lock scope and avoid recursive locking since that is undefined for shared_mutex . <nl> + const auto children_copy = children ; <nl> + lock . unlock ( ) ; <nl> + <nl> + for ( auto & child : children_copy ) <nl> if ( f ( * child ) ) <nl> return ; <nl> } <nl> mmm a / dbms / src / DataStreams / MarkInCompressedFile . h <nl> ppp b / dbms / src / DataStreams / MarkInCompressedFile . h <nl> <nl> # include < IO / WriteHelpers . h > <nl> # include < Common / PODArray . h > <nl> <nl> - # include < Common / config . h > <nl> - # if USE_MIMALLOC <nl> - # include < Common / MiAllocator . h > <nl> - # endif <nl> <nl> namespace DB <nl> { <nl> struct MarkInCompressedFile <nl> } <nl> <nl> } ; <nl> - # if USE_MIMALLOC <nl> - using MarksInCompressedFile = PODArray < MarkInCompressedFile , 4096 , MiAllocator > ; <nl> - # else <nl> + <nl> using MarksInCompressedFile = PODArray < MarkInCompressedFile > ; <nl> - # endif <nl> + <nl> } <nl> mmm a / dbms / src / DataStreams / PushingToViewsBlockOutputStream . cpp <nl> ppp b / dbms / src / DataStreams / PushingToViewsBlockOutputStream . cpp <nl> PushingToViewsBlockOutputStream : : PushingToViewsBlockOutputStream ( <nl> * Although now any insertion into the table is done via PushingToViewsBlockOutputStream , <nl> * but it ' s clear that here is not the best place for this functionality . <nl> * / <nl> - addTableLock ( storage - > lockStructureForShare ( true , context . getCurrentQueryId ( ) ) ) ; <nl> + addTableLock ( storage - > lockStructureForShare ( true , context . getInitialQueryId ( ) ) ) ; <nl> <nl> / / / If the " root " table deduplactes blocks , there are no need to make deduplication for children <nl> / / / Moreover , deduplication for AggregatingMergeTree children could produce false positives due to low size of inserting blocks <nl> mmm a / dbms / src / Dictionaries / CacheDictionary . cpp <nl> ppp b / dbms / src / Dictionaries / CacheDictionary . cpp <nl> CacheDictionary : : CacheDictionary ( <nl> , dict_struct ( dict_struct_ ) <nl> , source_ptr { std : : move ( source_ptr_ ) } <nl> , dict_lifetime ( dict_lifetime_ ) <nl> + , log ( & Logger : : get ( " ExternalDictionaries " ) ) <nl> , size { roundUpToPowerOfTwoOrZero ( std : : max ( size_ , size_t ( max_collision_length ) ) ) } <nl> , size_overlap_mask { this - > size - 1 } <nl> , cells { this - > size } <nl> BlockInputStreamPtr CacheDictionary : : getBlockInputStream ( const Names & column_na <nl> return std : : make_shared < BlockInputStreamType > ( shared_from_this ( ) , max_block_size , getCachedIds ( ) , column_names ) ; <nl> } <nl> <nl> + std : : exception_ptr CacheDictionary : : getLastException ( ) const <nl> + { <nl> + const ProfilingScopedReadRWLock read_lock { rw_lock , ProfileEvents : : DictCacheLockReadNs } ; <nl> + return last_exception ; <nl> + } <nl> + <nl> void registerDictionaryCache ( DictionaryFactory & factory ) <nl> { <nl> auto create_layout = [ = ] ( const std : : string & name , <nl> mmm a / dbms / src / Dictionaries / CacheDictionary . h <nl> ppp b / dbms / src / Dictionaries / CacheDictionary . h <nl> <nl> # include < shared_mutex > <nl> # include < variant > <nl> # include < vector > <nl> + # include < common / logger_useful . h > <nl> # include < Columns / ColumnDecimal . h > <nl> # include < Columns / ColumnString . h > <nl> # include < pcg_random . hpp > <nl> class CacheDictionary final : public IDictionary <nl> void isInVectorConstant ( const PaddedPODArray < Key > & child_ids , const Key ancestor_id , PaddedPODArray < UInt8 > & out ) const override ; <nl> void isInConstantVector ( const Key child_id , const PaddedPODArray < Key > & ancestor_ids , PaddedPODArray < UInt8 > & out ) const override ; <nl> <nl> + std : : exception_ptr getLastException ( ) const override ; <nl> + <nl> template < typename T > <nl> using ResultArrayType = std : : conditional_t < IsDecimalNumber < T > , DecimalPaddedPODArray < T > , PaddedPODArray < T > > ; <nl> <nl> class CacheDictionary final : public IDictionary <nl> <nl> const std : : string name ; <nl> const DictionaryStructure dict_struct ; <nl> - const DictionarySourcePtr source_ptr ; <nl> + mutable DictionarySourcePtr source_ptr ; <nl> const DictionaryLifetime dict_lifetime ; <nl> + Logger * const log ; <nl> <nl> mutable std : : shared_mutex rw_lock ; <nl> <nl> class CacheDictionary final : public IDictionary <nl> Attribute * hierarchical_attribute = nullptr ; <nl> std : : unique_ptr < ArenaWithFreeLists > string_arena ; <nl> <nl> + mutable std : : exception_ptr last_exception ; <nl> + mutable size_t error_count = 0 ; <nl> + mutable std : : chrono : : system_clock : : time_point backoff_end_time ; <nl> + <nl> mutable pcg64 rnd_engine ; <nl> <nl> mutable size_t bytes_allocated = 0 ; <nl> mmm a / dbms / src / Dictionaries / CacheDictionary . inc . h <nl> ppp b / dbms / src / Dictionaries / CacheDictionary . inc . h <nl> <nl> # include < Columns / ColumnsNumber . h > <nl> # include < Common / ProfilingScopedRWLock . h > <nl> # include < Common / typeid_cast . h > <nl> + # include < common / DateLUT . h > <nl> # include < DataStreams / IBlockInputStream . h > <nl> # include < ext / map . h > <nl> # include < ext / range . h > <nl> template < typename PresentIdHandler , typename AbsentIdHandler > <nl> void CacheDictionary : : update ( <nl> const std : : vector < Key > & requested_ids , PresentIdHandler & & on_cell_updated , AbsentIdHandler & & on_id_not_found ) const <nl> { <nl> + CurrentMetrics : : Increment metric_increment { CurrentMetrics : : DictCacheRequests } ; <nl> + ProfileEvents : : increment ( ProfileEvents : : DictCacheKeysRequested , requested_ids . size ( ) ) ; <nl> + <nl> std : : unordered_map < Key , UInt8 > remaining_ids { requested_ids . size ( ) } ; <nl> for ( const auto id : requested_ids ) <nl> remaining_ids . insert ( { id , 0 } ) ; <nl> <nl> - std : : uniform_int_distribution < UInt64 > distribution { dict_lifetime . min_sec , dict_lifetime . max_sec } ; <nl> + const auto now = std : : chrono : : system_clock : : now ( ) ; <nl> <nl> const ProfilingScopedWriteRWLock write_lock { rw_lock , ProfileEvents : : DictCacheLockWriteNs } ; <nl> <nl> + if ( now > backoff_end_time ) <nl> { <nl> - CurrentMetrics : : Increment metric_increment { CurrentMetrics : : DictCacheRequests } ; <nl> - Stopwatch watch ; <nl> - auto stream = source_ptr - > loadIds ( requested_ids ) ; <nl> - stream - > readPrefix ( ) ; <nl> - <nl> - const auto now = std : : chrono : : system_clock : : now ( ) ; <nl> - <nl> - while ( const auto block = stream - > read ( ) ) <nl> + try <nl> { <nl> - const auto id_column = typeid_cast < const ColumnUInt64 * > ( block . safeGetByPosition ( 0 ) . column . get ( ) ) ; <nl> - if ( ! id_column ) <nl> - throw Exception { name + " : id column has type different from UInt64 . " , ErrorCodes : : TYPE_MISMATCH } ; <nl> - <nl> - const auto & ids = id_column - > getData ( ) ; <nl> + if ( error_count ) <nl> + { <nl> + / / / Recover after error : we have to clone the source here because <nl> + / / / it could keep connections which should be reset after error . <nl> + source_ptr = source_ptr - > clone ( ) ; <nl> + } <nl> <nl> - / / / cache column pointers <nl> - const auto column_ptrs = ext : : map < std : : vector > ( <nl> - ext : : range ( 0 , attributes . size ( ) ) , [ & block ] ( size_t i ) { return block . safeGetByPosition ( i + 1 ) . column . get ( ) ; } ) ; <nl> + Stopwatch watch ; <nl> + auto stream = source_ptr - > loadIds ( requested_ids ) ; <nl> + stream - > readPrefix ( ) ; <nl> <nl> - for ( const auto i : ext : : range ( 0 , ids . size ( ) ) ) <nl> + while ( const auto block = stream - > read ( ) ) <nl> { <nl> - const auto id = ids [ i ] ; <nl> + const auto id_column = typeid_cast < const ColumnUInt64 * > ( block . safeGetByPosition ( 0 ) . column . get ( ) ) ; <nl> + if ( ! id_column ) <nl> + throw Exception { name + " : id column has type different from UInt64 . " , ErrorCodes : : TYPE_MISMATCH } ; <nl> <nl> - const auto find_result = findCellIdx ( id , now ) ; <nl> - const auto & cell_idx = find_result . cell_idx ; <nl> + const auto & ids = id_column - > getData ( ) ; <nl> <nl> - auto & cell = cells [ cell_idx ] ; <nl> + / / / cache column pointers <nl> + const auto column_ptrs = ext : : map < std : : vector > ( <nl> + ext : : range ( 0 , attributes . size ( ) ) , [ & block ] ( size_t i ) { return block . safeGetByPosition ( i + 1 ) . column . get ( ) ; } ) ; <nl> <nl> - for ( const auto attribute_idx : ext : : range ( 0 , attributes . size ( ) ) ) <nl> + for ( const auto i : ext : : range ( 0 , ids . size ( ) ) ) <nl> { <nl> - const auto & attribute_column = * column_ptrs [ attribute_idx ] ; <nl> - auto & attribute = attributes [ attribute_idx ] ; <nl> - <nl> - setAttributeValue ( attribute , cell_idx , attribute_column [ i ] ) ; <nl> + const auto id = ids [ i ] ; <nl> + <nl> + const auto find_result = findCellIdx ( id , now ) ; <nl> + const auto & cell_idx = find_result . cell_idx ; <nl> + <nl> + auto & cell = cells [ cell_idx ] ; <nl> + <nl> + for ( const auto attribute_idx : ext : : range ( 0 , attributes . size ( ) ) ) <nl> + { <nl> + const auto & attribute_column = * column_ptrs [ attribute_idx ] ; <nl> + auto & attribute = attributes [ attribute_idx ] ; <nl> + <nl> + setAttributeValue ( attribute , cell_idx , attribute_column [ i ] ) ; <nl> + } <nl> + <nl> + / / / if cell id is zero and zero does not map to this cell , then the cell is unused <nl> + if ( cell . id = = 0 & & cell_idx ! = zero_cell_idx ) <nl> + element_count . fetch_add ( 1 , std : : memory_order_relaxed ) ; <nl> + <nl> + cell . id = id ; <nl> + if ( dict_lifetime . min_sec ! = 0 & & dict_lifetime . max_sec ! = 0 ) <nl> + { <nl> + std : : uniform_int_distribution < UInt64 > distribution { dict_lifetime . min_sec , dict_lifetime . max_sec } ; <nl> + cell . setExpiresAt ( now + std : : chrono : : seconds { distribution ( rnd_engine ) } ) ; <nl> + } <nl> + else <nl> + cell . setExpiresAt ( std : : chrono : : time_point < std : : chrono : : system_clock > : : max ( ) ) ; <nl> + <nl> + / / / inform caller <nl> + on_cell_updated ( id , cell_idx ) ; <nl> + / / / mark corresponding id as found <nl> + remaining_ids [ id ] = 1 ; <nl> } <nl> + } <nl> <nl> - / / / if cell id is zero and zero does not map to this cell , then the cell is unused <nl> - if ( cell . id = = 0 & & cell_idx ! = zero_cell_idx ) <nl> - element_count . fetch_add ( 1 , std : : memory_order_relaxed ) ; <nl> + stream - > readSuffix ( ) ; <nl> <nl> - cell . id = id ; <nl> - if ( dict_lifetime . min_sec ! = 0 & & dict_lifetime . max_sec ! = 0 ) <nl> - cell . setExpiresAt ( std : : chrono : : system_clock : : now ( ) + std : : chrono : : seconds { distribution ( rnd_engine ) } ) ; <nl> - else <nl> - cell . setExpiresAt ( std : : chrono : : time_point < std : : chrono : : system_clock > : : max ( ) ) ; <nl> + error_count = 0 ; <nl> + last_exception = std : : exception_ptr { } ; <nl> + backoff_end_time = std : : chrono : : system_clock : : time_point { } ; <nl> <nl> - / / / inform caller <nl> - on_cell_updated ( id , cell_idx ) ; <nl> - / / / mark corresponding id as found <nl> - remaining_ids [ id ] = 1 ; <nl> - } <nl> + ProfileEvents : : increment ( ProfileEvents : : DictCacheRequestTimeNs , watch . elapsed ( ) ) ; <nl> } <nl> + catch ( . . . ) <nl> + { <nl> + + + error_count ; <nl> + last_exception = std : : current_exception ( ) ; <nl> + backoff_end_time = now + std : : chrono : : seconds ( ExternalLoadableBackoff { } . calculateDuration ( rnd_engine , error_count ) ) ; <nl> <nl> - stream - > readSuffix ( ) ; <nl> - <nl> - ProfileEvents : : increment ( ProfileEvents : : DictCacheKeysRequested , requested_ids . size ( ) ) ; <nl> - ProfileEvents : : increment ( ProfileEvents : : DictCacheRequestTimeNs , watch . elapsed ( ) ) ; <nl> + tryLogException ( last_exception , log , " Could not update cache dictionary ' " + getName ( ) + <nl> + " ' , next update is scheduled at " + DateLUT : : instance ( ) . timeToString ( std : : chrono : : system_clock : : to_time_t ( backoff_end_time ) ) ) ; <nl> + } <nl> } <nl> <nl> size_t not_found_num = 0 , found_num = 0 ; <nl> <nl> - const auto now = std : : chrono : : system_clock : : now ( ) ; <nl> / / / Check which ids have not been found and require setting null_value <nl> for ( const auto & id_found_pair : remaining_ids ) <nl> { <nl> void CacheDictionary : : update ( <nl> <nl> const auto find_result = findCellIdx ( id , now ) ; <nl> const auto & cell_idx = find_result . cell_idx ; <nl> - <nl> auto & cell = cells [ cell_idx ] ; <nl> <nl> - / / / Set null_value for each attribute <nl> - for ( auto & attribute : attributes ) <nl> - setDefaultAttributeValue ( attribute , cell_idx ) ; <nl> + if ( error_count ) <nl> + { <nl> + if ( find_result . outdated ) <nl> + { <nl> + / / / We have expired data for that ` id ` so we can continue using it . <nl> + bool was_default = cell . isDefault ( ) ; <nl> + cell . setExpiresAt ( backoff_end_time ) ; <nl> + if ( was_default ) <nl> + cell . setDefault ( ) ; <nl> + if ( was_default ) <nl> + on_id_not_found ( id , cell_idx ) ; <nl> + else <nl> + on_cell_updated ( id , cell_idx ) ; <nl> + continue ; <nl> + } <nl> + / / / We don ' t have expired data for that ` id ` so all we can do is to rethrow ` last_exception ` . <nl> + std : : rethrow_exception ( last_exception ) ; <nl> + } <nl> <nl> / / / Check if cell had not been occupied before and increment element counter if it hadn ' t <nl> if ( cell . id = = 0 & & cell_idx ! = zero_cell_idx ) <nl> element_count . fetch_add ( 1 , std : : memory_order_relaxed ) ; <nl> <nl> cell . id = id ; <nl> + <nl> if ( dict_lifetime . min_sec ! = 0 & & dict_lifetime . max_sec ! = 0 ) <nl> - cell . setExpiresAt ( std : : chrono : : system_clock : : now ( ) + std : : chrono : : seconds { distribution ( rnd_engine ) } ) ; <nl> + { <nl> + std : : uniform_int_distribution < UInt64 > distribution { dict_lifetime . min_sec , dict_lifetime . max_sec } ; <nl> + cell . setExpiresAt ( now + std : : chrono : : seconds { distribution ( rnd_engine ) } ) ; <nl> + } <nl> else <nl> cell . setExpiresAt ( std : : chrono : : time_point < std : : chrono : : system_clock > : : max ( ) ) ; <nl> <nl> + / / / Set null_value for each attribute <nl> cell . setDefault ( ) ; <nl> + for ( auto & attribute : attributes ) <nl> + setDefaultAttributeValue ( attribute , cell_idx ) ; <nl> <nl> / / / inform caller that the cell has not been found <nl> on_id_not_found ( id , cell_idx ) ; <nl> mmm a / dbms / src / Dictionaries / IDictionary . h <nl> ppp b / dbms / src / Dictionaries / IDictionary . h <nl> struct IDictionaryBase : public IExternalLoadable <nl> return source & & source - > isModified ( ) ; <nl> } <nl> <nl> + virtual std : : exception_ptr getLastException ( ) const { return { } ; } <nl> + <nl> std : : shared_ptr < IDictionaryBase > shared_from_this ( ) <nl> { <nl> return std : : static_pointer_cast < IDictionaryBase > ( IExternalLoadable : : shared_from_this ( ) ) ; <nl> deleted file mode 100644 <nl> index fc38b476e0b . . 00000000000 <nl> mmm a / dbms / src / Formats / BlockInputStreamFromRowInputStream . cpp <nl> ppp / dev / null <nl> <nl> - # include < Common / Exception . h > <nl> - # include < IO / WriteHelpers . h > <nl> - # include < Formats / BlockInputStreamFromRowInputStream . h > <nl> - # include < common / logger_useful . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int CANNOT_PARSE_INPUT_ASSERTION_FAILED ; <nl> - extern const int CANNOT_PARSE_QUOTED_STRING ; <nl> - extern const int CANNOT_PARSE_DATE ; <nl> - extern const int CANNOT_PARSE_DATETIME ; <nl> - extern const int CANNOT_READ_ARRAY_FROM_TEXT ; <nl> - extern const int CANNOT_PARSE_NUMBER ; <nl> - extern const int CANNOT_PARSE_UUID ; <nl> - extern const int TOO_LARGE_STRING_SIZE ; <nl> - extern const int CANNOT_READ_ALL_DATA ; <nl> - extern const int INCORRECT_DATA ; <nl> - extern const int INCORRECT_NUMBER_OF_COLUMNS ; <nl> - } <nl> - <nl> - <nl> - BlockInputStreamFromRowInputStream : : BlockInputStreamFromRowInputStream ( <nl> - const RowInputStreamPtr & row_input_ , <nl> - const Block & sample_ , <nl> - UInt64 max_block_size_ , <nl> - UInt64 rows_portion_size_ , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) <nl> - : row_input ( row_input_ ) <nl> - , sample ( sample_ ) <nl> - , max_block_size ( max_block_size_ ) <nl> - , rows_portion_size ( rows_portion_size_ ) <nl> - , read_virtual_columns_callback ( callback ) <nl> - , allow_errors_num ( settings . input_allow_errors_num ) <nl> - , allow_errors_ratio ( settings . input_allow_errors_ratio ) <nl> - { <nl> - } <nl> - <nl> - <nl> - static bool isParseError ( int code ) <nl> - { <nl> - return code = = ErrorCodes : : CANNOT_PARSE_INPUT_ASSERTION_FAILED <nl> - | | code = = ErrorCodes : : CANNOT_PARSE_QUOTED_STRING <nl> - | | code = = ErrorCodes : : CANNOT_PARSE_DATE <nl> - | | code = = ErrorCodes : : CANNOT_PARSE_DATETIME <nl> - | | code = = ErrorCodes : : CANNOT_READ_ARRAY_FROM_TEXT <nl> - | | code = = ErrorCodes : : CANNOT_PARSE_NUMBER <nl> - | | code = = ErrorCodes : : CANNOT_PARSE_UUID <nl> - | | code = = ErrorCodes : : TOO_LARGE_STRING_SIZE <nl> - | | code = = ErrorCodes : : CANNOT_READ_ALL_DATA <nl> - | | code = = ErrorCodes : : INCORRECT_DATA ; <nl> - } <nl> - <nl> - <nl> - Block BlockInputStreamFromRowInputStream : : readImpl ( ) <nl> - { <nl> - size_t num_columns = sample . columns ( ) ; <nl> - MutableColumns columns = sample . cloneEmptyColumns ( ) ; <nl> - block_missing_values . clear ( ) ; <nl> - <nl> - try <nl> - { <nl> - for ( size_t rows = 0 , batch = 0 ; rows < max_block_size ; + + rows , + + batch ) <nl> - { <nl> - if ( rows_portion_size & & batch = = rows_portion_size ) <nl> - { <nl> - batch = 0 ; <nl> - if ( ! checkTimeLimit ( ) | | isCancelled ( ) ) <nl> - break ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - + + total_rows ; <nl> - RowReadExtension info_ ; <nl> - if ( ! row_input - > read ( columns , info_ ) ) <nl> - break ; <nl> - if ( read_virtual_columns_callback ) <nl> - read_virtual_columns_callback ( ) ; <nl> - <nl> - for ( size_t column_idx = 0 ; column_idx < info_ . read_columns . size ( ) ; + + column_idx ) <nl> - { <nl> - if ( ! info_ . read_columns [ column_idx ] ) <nl> - { <nl> - size_t column_size = columns [ column_idx ] - > size ( ) ; <nl> - if ( column_size = = 0 ) <nl> - throw Exception ( " Unexpected empty column " , ErrorCodes : : INCORRECT_NUMBER_OF_COLUMNS ) ; <nl> - block_missing_values . setBit ( column_idx , column_size - 1 ) ; <nl> - } <nl> - } <nl> - } <nl> - catch ( Exception & e ) <nl> - { <nl> - / / / Logic for possible skipping of errors . <nl> - <nl> - if ( ! isParseError ( e . code ( ) ) ) <nl> - throw ; <nl> - <nl> - if ( allow_errors_num = = 0 & & allow_errors_ratio = = 0 ) <nl> - throw ; <nl> - <nl> - + + num_errors ; <nl> - Float32 current_error_ratio = static_cast < Float32 > ( num_errors ) / total_rows ; <nl> - <nl> - if ( num_errors > allow_errors_num <nl> - & & current_error_ratio > allow_errors_ratio ) <nl> - { <nl> - e . addMessage ( " ( Already have " + toString ( num_errors ) + " errors " <nl> - " out of " + toString ( total_rows ) + " rows " <nl> - " , which is " + toString ( current_error_ratio ) + " of all rows ) " ) ; <nl> - throw ; <nl> - } <nl> - <nl> - if ( ! row_input - > allowSyncAfterError ( ) ) <nl> - { <nl> - e . addMessage ( " ( Input format doesn ' t allow to skip errors ) " ) ; <nl> - throw ; <nl> - } <nl> - <nl> - row_input - > syncAfterError ( ) ; <nl> - <nl> - / / / Truncate all columns in block to minimal size ( remove values , that was appended to only part of columns ) . <nl> - <nl> - size_t min_size = std : : numeric_limits < size_t > : : max ( ) ; <nl> - for ( size_t column_idx = 0 ; column_idx < num_columns ; + + column_idx ) <nl> - min_size = std : : min ( min_size , columns [ column_idx ] - > size ( ) ) ; <nl> - <nl> - for ( size_t column_idx = 0 ; column_idx < num_columns ; + + column_idx ) <nl> - { <nl> - auto & column = columns [ column_idx ] ; <nl> - if ( column - > size ( ) > min_size ) <nl> - column - > popBack ( column - > size ( ) - min_size ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - catch ( Exception & e ) <nl> - { <nl> - if ( ! isParseError ( e . code ( ) ) ) <nl> - throw ; <nl> - <nl> - String verbose_diagnostic ; <nl> - try <nl> - { <nl> - verbose_diagnostic = row_input - > getDiagnosticInfo ( ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - / / / Error while trying to obtain verbose diagnostic . Ok to ignore . <nl> - } <nl> - <nl> - e . addMessage ( " ( at row " + toString ( total_rows ) + " ) \ n " + verbose_diagnostic ) ; <nl> - throw ; <nl> - } <nl> - <nl> - if ( columns . empty ( ) | | columns [ 0 ] - > empty ( ) ) <nl> - return { } ; <nl> - <nl> - return sample . cloneWithColumns ( std : : move ( columns ) ) ; <nl> - } <nl> - <nl> - <nl> - void BlockInputStreamFromRowInputStream : : readSuffix ( ) <nl> - { <nl> - if ( allow_errors_num > 0 | | allow_errors_ratio > 0 ) <nl> - { <nl> - Logger * log = & Logger : : get ( " BlockInputStreamFromRowInputStream " ) ; <nl> - LOG_TRACE ( log , " Skipped " < < num_errors < < " rows with errors while reading the input stream " ) ; <nl> - } <nl> - <nl> - row_input - > readSuffix ( ) ; <nl> - } <nl> - <nl> - } <nl> deleted file mode 100644 <nl> index 2338af3bf38 . . 00000000000 <nl> mmm a / dbms / src / Formats / BlockInputStreamFromRowInputStream . h <nl> ppp / dev / null <nl> <nl> - # pragma once <nl> - <nl> - # include < Core / Defines . h > <nl> - # include < DataStreams / IBlockInputStream . h > <nl> - # include < Formats / FormatFactory . h > <nl> - # include < Formats / FormatSettings . h > <nl> - # include < Formats / IRowInputStream . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - / * * Makes block - oriented stream on top of row - oriented stream . <nl> - * It is used to read data from text formats . <nl> - * <nl> - * Also controls over parsing errors and prints diagnostic information about them . <nl> - * / <nl> - class BlockInputStreamFromRowInputStream : public IBlockInputStream <nl> - { <nl> - public : <nl> - / / / | sample | is a block with zero rows , that structure describes how to interpret values <nl> - / / / | rows_portion_size | is a number of rows to read before break and check limits <nl> - BlockInputStreamFromRowInputStream ( <nl> - const RowInputStreamPtr & row_input_ , <nl> - const Block & sample_ , <nl> - UInt64 max_block_size_ , <nl> - UInt64 rows_portion_size_ , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) ; <nl> - <nl> - void readPrefix ( ) override { row_input - > readPrefix ( ) ; } <nl> - void readSuffix ( ) override ; <nl> - <nl> - String getName ( ) const override { return " BlockInputStreamFromRowInputStream " ; } <nl> - <nl> - RowInputStreamPtr & getRowInput ( ) { return row_input ; } <nl> - <nl> - Block getHeader ( ) const override { return sample ; } <nl> - <nl> - const BlockMissingValues & getMissingValues ( ) const override { return block_missing_values ; } <nl> - <nl> - protected : <nl> - Block readImpl ( ) override ; <nl> - <nl> - private : <nl> - RowInputStreamPtr row_input ; <nl> - Block sample ; <nl> - UInt64 max_block_size ; <nl> - UInt64 rows_portion_size ; <nl> - <nl> - / / / Callback used to setup virtual columns after reading each row . <nl> - FormatFactory : : ReadCallback read_virtual_columns_callback ; <nl> - <nl> - BlockMissingValues block_missing_values ; <nl> - <nl> - UInt64 allow_errors_num ; <nl> - Float32 allow_errors_ratio ; <nl> - <nl> - size_t total_rows = 0 ; <nl> - size_t num_errors = 0 ; <nl> - } ; <nl> - } <nl> deleted file mode 100644 <nl> index 4b1b6198486 . . 00000000000 <nl> mmm a / dbms / src / Formats / CSVRowInputStream . cpp <nl> ppp / dev / null <nl> <nl> - # include < Core / Defines . h > <nl> - <nl> - # include < IO / ConcatReadBuffer . h > <nl> - # include < IO / ReadHelpers . h > <nl> - # include < IO / Operators . h > <nl> - <nl> - # include < Formats / verbosePrintString . h > <nl> - # include < Formats / CSVRowInputStream . h > <nl> - # include < Formats / FormatFactory . h > <nl> - # include < Formats / BlockInputStreamFromRowInputStream . h > <nl> - <nl> - # include < DataTypes / DataTypeNullable . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int INCORRECT_DATA ; <nl> - extern const int LOGICAL_ERROR ; <nl> - } <nl> - <nl> - <nl> - static inline void skipEndOfLine ( ReadBuffer & istr ) <nl> - { <nl> - / / / \ n ( Unix ) or \ r \ n ( DOS / Windows ) or \ n \ r ( Mac OS Classic ) <nl> - <nl> - if ( * istr . position ( ) = = ' \ n ' ) <nl> - { <nl> - + + istr . position ( ) ; <nl> - if ( ! istr . eof ( ) & & * istr . position ( ) = = ' \ r ' ) <nl> - + + istr . position ( ) ; <nl> - } <nl> - else if ( * istr . position ( ) = = ' \ r ' ) <nl> - { <nl> - + + istr . position ( ) ; <nl> - if ( ! istr . eof ( ) & & * istr . position ( ) = = ' \ n ' ) <nl> - + + istr . position ( ) ; <nl> - else <nl> - throw Exception ( " Cannot parse CSV format : found \ \ r ( CR ) not followed by \ \ n ( LF ) . " <nl> - " Line must end by \ \ n ( LF ) or \ \ r \ \ n ( CR LF ) or \ \ n \ \ r . " , ErrorCodes : : INCORRECT_DATA ) ; <nl> - } <nl> - else if ( ! istr . eof ( ) ) <nl> - throw Exception ( " Expected end of line " , ErrorCodes : : INCORRECT_DATA ) ; <nl> - } <nl> - <nl> - <nl> - static inline void skipDelimiter ( ReadBuffer & istr , const char delimiter , bool is_last_column ) <nl> - { <nl> - if ( is_last_column ) <nl> - { <nl> - if ( istr . eof ( ) ) <nl> - return ; <nl> - <nl> - / / / we support the extra delimiter at the end of the line <nl> - if ( * istr . position ( ) = = delimiter ) <nl> - { <nl> - + + istr . position ( ) ; <nl> - if ( istr . eof ( ) ) <nl> - return ; <nl> - } <nl> - <nl> - skipEndOfLine ( istr ) ; <nl> - } <nl> - else <nl> - assertChar ( delimiter , istr ) ; <nl> - } <nl> - <nl> - <nl> - / / / Skip ` whitespace ` symbols allowed in CSV . <nl> - static inline void skipWhitespacesAndTabs ( ReadBuffer & buf ) <nl> - { <nl> - while ( ! buf . eof ( ) <nl> - & & ( * buf . position ( ) = = ' ' <nl> - | | * buf . position ( ) = = ' \ t ' ) ) <nl> - + + buf . position ( ) ; <nl> - } <nl> - <nl> - <nl> - static void skipRow ( ReadBuffer & istr , const FormatSettings : : CSV & settings , size_t num_columns ) <nl> - { <nl> - String tmp ; <nl> - for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> - { <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - readCSVString ( tmp , istr , settings ) ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - <nl> - skipDelimiter ( istr , settings . delimiter , i + 1 = = num_columns ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - CSVRowInputStream : : CSVRowInputStream ( ReadBuffer & istr_ , const Block & header_ , bool with_names_ , const FormatSettings & format_settings_ ) <nl> - : istr ( istr_ ) , header ( header_ ) , with_names ( with_names_ ) , format_settings ( format_settings_ ) <nl> - { <nl> - const auto num_columns = header . columns ( ) ; <nl> - <nl> - data_types . resize ( num_columns ) ; <nl> - column_indexes_by_names . reserve ( num_columns ) ; <nl> - column_idx_to_nullable_column_idx . resize ( num_columns ) ; <nl> - <nl> - for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> - { <nl> - const auto & column_info = header . getByPosition ( i ) ; <nl> - <nl> - data_types [ i ] = column_info . type ; <nl> - column_indexes_by_names . emplace ( column_info . name , i ) ; <nl> - <nl> - / / / If input_format_null_as_default = 1 we need ColumnNullable of type DataTypeNullable ( nested_type ) <nl> - / / / to parse value as nullable before inserting it in corresponding column of not - nullable type . <nl> - / / / Constructing temporary column for each row is slow , so we prepare it here <nl> - if ( format_settings . csv . null_as_default & & ! column_info . type - > isNullable ( ) & & column_info . type - > canBeInsideNullable ( ) ) <nl> - { <nl> - column_idx_to_nullable_column_idx [ i ] = nullable_columns . size ( ) ; <nl> - nullable_types . emplace_back ( std : : make_shared < DataTypeNullable > ( column_info . type ) ) ; <nl> - nullable_columns . emplace_back ( nullable_types . back ( ) - > createColumn ( ) ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / / Map an input file column to a table column , based on its name . <nl> - void CSVRowInputStream : : addInputColumn ( const String & column_name ) <nl> - { <nl> - const auto column_it = column_indexes_by_names . find ( column_name ) ; <nl> - if ( column_it = = column_indexes_by_names . end ( ) ) <nl> - { <nl> - if ( format_settings . skip_unknown_fields ) <nl> - { <nl> - column_indexes_for_input_fields . push_back ( std : : nullopt ) ; <nl> - return ; <nl> - } <nl> - <nl> - throw Exception ( <nl> - " Unknown field found in CSV header : ' " + column_name + " ' " + <nl> - " at position " + std : : to_string ( column_indexes_for_input_fields . size ( ) ) + <nl> - " \ nSet the ' input_format_skip_unknown_fields ' parameter explicitly to ignore and proceed " , <nl> - ErrorCodes : : INCORRECT_DATA <nl> - ) ; <nl> - } <nl> - <nl> - const auto column_index = column_it - > second ; <nl> - <nl> - if ( read_columns [ column_index ] ) <nl> - throw Exception ( " Duplicate field found while parsing CSV header : " + column_name , ErrorCodes : : INCORRECT_DATA ) ; <nl> - <nl> - read_columns [ column_index ] = true ; <nl> - column_indexes_for_input_fields . emplace_back ( column_index ) ; <nl> - } <nl> - <nl> - void CSVRowInputStream : : readPrefix ( ) <nl> - { <nl> - / / / In this format , we assume , that if first string field contain BOM as value , it will be written in quotes , <nl> - / / / so BOM at beginning of stream cannot be confused with BOM in first string value , and it is safe to skip it . <nl> - skipBOMIfExists ( istr ) ; <nl> - <nl> - if ( with_names ) <nl> - { <nl> - / / / This CSV file has a header row with column names . Depending on the <nl> - / / / settings , use it or skip it . <nl> - if ( format_settings . with_names_use_header ) <nl> - { <nl> - / / / Look at the file header to see which columns we have there . <nl> - / / / The missing columns are filled with defaults . <nl> - read_columns . assign ( header . columns ( ) , false ) ; <nl> - do <nl> - { <nl> - String column_name ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - readCSVString ( column_name , istr , format_settings . csv ) ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - <nl> - addInputColumn ( column_name ) ; <nl> - } <nl> - while ( checkChar ( format_settings . csv . delimiter , istr ) ) ; <nl> - <nl> - skipDelimiter ( istr , format_settings . csv . delimiter , true ) ; <nl> - <nl> - for ( size_t column = 0 ; column < read_columns . size ( ) ; column + + ) <nl> - { <nl> - if ( ! read_columns [ column ] ) <nl> - { <nl> - have_always_default_columns = true ; <nl> - break ; <nl> - } <nl> - } <nl> - <nl> - return ; <nl> - } <nl> - else <nl> - { <nl> - skipRow ( istr , format_settings . csv , header . columns ( ) ) ; <nl> - } <nl> - } <nl> - <nl> - / / / The default : map each column of the file to the column of the table with <nl> - / / / the same index . <nl> - read_columns . assign ( header . columns ( ) , true ) ; <nl> - column_indexes_for_input_fields . resize ( header . columns ( ) ) ; <nl> - <nl> - for ( size_t i = 0 ; i < column_indexes_for_input_fields . size ( ) ; + + i ) <nl> - { <nl> - column_indexes_for_input_fields [ i ] = i ; <nl> - } <nl> - } <nl> - <nl> - / * * If you change this function , don ' t forget to change its counterpart <nl> - * with extended error reporting : parseRowAndPrintDiagnosticInfo ( ) . <nl> - * / <nl> - bool CSVRowInputStream : : read ( MutableColumns & columns , RowReadExtension & ext ) <nl> - { <nl> - if ( istr . eof ( ) ) <nl> - return false ; <nl> - <nl> - updateDiagnosticInfo ( ) ; <nl> - <nl> - / / / Track whether we have to fill any columns in this row with default <nl> - / / / values . If not , we return an empty column mask to the caller , so that <nl> - / / / it doesn ' t have to check it . <nl> - bool have_default_columns = have_always_default_columns ; <nl> - <nl> - const auto delimiter = format_settings . csv . delimiter ; <nl> - for ( size_t file_column = 0 ; file_column < column_indexes_for_input_fields . size ( ) ; + + file_column ) <nl> - { <nl> - const auto & table_column = column_indexes_for_input_fields [ file_column ] ; <nl> - const bool is_last_file_column = file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> - <nl> - if ( table_column ) <nl> - { <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - read_columns [ * table_column ] = readField ( * columns [ * table_column ] , data_types [ * table_column ] , <nl> - is_last_file_column , * table_column ) ; <nl> - if ( ! read_columns [ * table_column ] ) <nl> - have_default_columns = true ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - } <nl> - else <nl> - { <nl> - / / / We never read this column from the file , just skip it . <nl> - String tmp ; <nl> - readCSVString ( tmp , istr , format_settings . csv ) ; <nl> - } <nl> - <nl> - skipDelimiter ( istr , delimiter , is_last_file_column ) ; <nl> - } <nl> - <nl> - if ( have_default_columns ) <nl> - { <nl> - for ( size_t i = 0 ; i < read_columns . size ( ) ; i + + ) <nl> - { <nl> - if ( ! read_columns [ i ] ) <nl> - { <nl> - / / / The column value for this row is going to be overwritten <nl> - / / / with default by the caller , but the general assumption is <nl> - / / / that the column size increases for each row , so we have <nl> - / / / to insert something . Since we do not care about the exact <nl> - / / / value , we do not have to use the default value specified by <nl> - / / / the data type , and can just use IColumn : : insertDefault ( ) . <nl> - columns [ i ] - > insertDefault ( ) ; <nl> - } <nl> - } <nl> - ext . read_columns = read_columns ; <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - String CSVRowInputStream : : getDiagnosticInfo ( ) <nl> - { <nl> - if ( istr . eof ( ) ) / / / Buffer has gone , cannot extract information about what has been parsed . <nl> - return { } ; <nl> - <nl> - WriteBufferFromOwnString out ; <nl> - <nl> - MutableColumns columns = header . cloneEmptyColumns ( ) ; <nl> - <nl> - / / / It is possible to display detailed diagnostics only if the last and next to last rows are still in the read buffer . <nl> - size_t bytes_read_at_start_of_buffer = istr . count ( ) - istr . offset ( ) ; <nl> - if ( bytes_read_at_start_of_buffer ! = bytes_read_at_start_of_buffer_on_prev_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because two last rows aren ' t in buffer ( rare case ) \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - size_t max_length_of_column_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . name . size ( ) > max_length_of_column_name ) <nl> - max_length_of_column_name = header . safeGetByPosition ( i ) . name . size ( ) ; <nl> - <nl> - size_t max_length_of_data_type_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) > max_length_of_data_type_name ) <nl> - max_length_of_data_type_name = header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) ; <nl> - <nl> - / / / Roll back the cursor to the beginning of the previous or current row and parse all over again . But now we derive detailed information . <nl> - <nl> - if ( pos_of_prev_row ) <nl> - { <nl> - istr . position ( ) = pos_of_prev_row ; <nl> - <nl> - out < < " \ nRow " < < ( row_num - 1 ) < < " : \ n " ; <nl> - if ( ! parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ) <nl> - return out . str ( ) ; <nl> - } <nl> - else <nl> - { <nl> - if ( ! pos_of_current_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because parsing of data hasn ' t started . \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - istr . position ( ) = pos_of_current_row ; <nl> - } <nl> - <nl> - out < < " \ nRow " < < row_num < < " : \ n " ; <nl> - parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ; <nl> - out < < " \ n " ; <nl> - <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - <nl> - / * * gcc - 7 generates wrong code with optimization level greater than 1 . <nl> - * See tests : dbms / src / IO / tests / write_int . cpp <nl> - * and dbms / tests / queries / 0_stateless / 00898_parsing_bad_diagnostic_message . sh <nl> - * This is compiler bug . The bug does not present in gcc - 8 and clang - 8 . <nl> - * Nevertheless , we don ' t need high optimization of this function . <nl> - * / <nl> - bool OPTIMIZE ( 1 ) CSVRowInputStream : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) <nl> - { <nl> - const char delimiter = format_settings . csv . delimiter ; <nl> - <nl> - for ( size_t file_column = 0 ; file_column < column_indexes_for_input_fields . size ( ) ; + + file_column ) <nl> - { <nl> - if ( file_column = = 0 & & istr . eof ( ) ) <nl> - { <nl> - out < < " < End of stream > \ n " ; <nl> - return false ; <nl> - } <nl> - <nl> - if ( column_indexes_for_input_fields [ file_column ] . has_value ( ) ) <nl> - { <nl> - const auto & table_column = * column_indexes_for_input_fields [ file_column ] ; <nl> - const auto & current_column_type = data_types [ table_column ] ; <nl> - const bool is_last_file_column = <nl> - file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> - const bool at_delimiter = ! istr . eof ( ) & & * istr . position ( ) = = delimiter ; <nl> - const bool at_last_column_line_end = is_last_file_column <nl> - & & ( istr . eof ( ) | | * istr . position ( ) = = ' \ n ' | | * istr . position ( ) = = ' \ r ' ) ; <nl> - <nl> - out < < " Column " < < file_column < < " , " < < std : : string ( ( file_column < 10 ? 2 : file_column < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < header . safeGetByPosition ( table_column ) . name < < " , " < < std : : string ( max_length_of_column_name - header . safeGetByPosition ( table_column ) . name . size ( ) , ' ' ) <nl> - < < " type : " < < current_column_type - > getName ( ) < < " , " < < std : : string ( max_length_of_data_type_name - current_column_type - > getName ( ) . size ( ) , ' ' ) ; <nl> - <nl> - if ( format_settings . csv . empty_as_default <nl> - & & ( at_delimiter | | at_last_column_line_end ) ) <nl> - { <nl> - columns [ table_column ] - > insertDefault ( ) ; <nl> - } <nl> - else <nl> - { <nl> - BufferBase : : Position prev_position = istr . position ( ) ; <nl> - BufferBase : : Position curr_position = istr . position ( ) ; <nl> - std : : exception_ptr exception ; <nl> - <nl> - try <nl> - { <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - prev_position = istr . position ( ) ; <nl> - readField ( * columns [ table_column ] , current_column_type , is_last_file_column , table_column ) ; <nl> - curr_position = istr . position ( ) ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - exception = std : : current_exception ( ) ; <nl> - } <nl> - <nl> - if ( curr_position < prev_position ) <nl> - throw Exception ( " Logical error : parsing is non - deterministic . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - if ( isNativeNumber ( current_column_type ) | | isDateOrDateTime ( current_column_type ) ) <nl> - { <nl> - / / / An empty string instead of a value . <nl> - if ( curr_position = = prev_position ) <nl> - { <nl> - out < < " ERROR : text " ; <nl> - verbosePrintString ( prev_position , std : : min ( prev_position + 10 , istr . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " is not like " < < current_column_type - > getName ( ) < < " \ n " ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - out < < " parsed text : " ; <nl> - verbosePrintString ( prev_position , curr_position , out ) ; <nl> - <nl> - if ( exception ) <nl> - { <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - else <nl> - out < < " ERROR \ n " ; <nl> - return false ; <nl> - } <nl> - <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > haveMaximumSizeOfValue ( ) <nl> - & & * curr_position ! = ' \ n ' & & * curr_position ! = ' \ r ' <nl> - & & * curr_position ! = delimiter ) <nl> - { <nl> - out < < " ERROR : garbage after " < < current_column_type - > getName ( ) < < " : " ; <nl> - verbosePrintString ( curr_position , std : : min ( curr_position + 10 , istr . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - else <nl> - { <nl> - static const String skipped_column_str = " < SKIPPED COLUMN > " ; <nl> - out < < " Column " < < file_column < < " , " < < std : : string ( ( file_column < 10 ? 2 : file_column < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_column_name - skipped_column_str . length ( ) , ' ' ) <nl> - < < " type : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_data_type_name - skipped_column_str . length ( ) , ' ' ) ; <nl> - <nl> - String tmp ; <nl> - readCSVString ( tmp , istr , format_settings . csv ) ; <nl> - } <nl> - <nl> - / / / Delimiters <nl> - if ( file_column + 1 = = column_indexes_for_input_fields . size ( ) ) <nl> - { <nl> - if ( istr . eof ( ) ) <nl> - return false ; <nl> - <nl> - / / / we support the extra delimiter at the end of the line <nl> - if ( * istr . position ( ) = = delimiter ) <nl> - { <nl> - + + istr . position ( ) ; <nl> - if ( istr . eof ( ) ) <nl> - break ; <nl> - } <nl> - <nl> - if ( ! istr . eof ( ) & & * istr . position ( ) ! = ' \ n ' & & * istr . position ( ) ! = ' \ r ' ) <nl> - { <nl> - out < < " ERROR : There is no line feed . " ; <nl> - verbosePrintString ( istr . position ( ) , istr . position ( ) + 1 , out ) ; <nl> - out < < " found instead . \ n " <nl> - " It ' s like your file has more columns than expected . \ n " <nl> - " And if your file have right number of columns , maybe it have unquoted string value with comma . \ n " ; <nl> - <nl> - return false ; <nl> - } <nl> - <nl> - skipEndOfLine ( istr ) ; <nl> - } <nl> - else <nl> - { <nl> - try <nl> - { <nl> - assertChar ( delimiter , istr ) ; <nl> - } <nl> - catch ( const DB : : Exception & ) <nl> - { <nl> - if ( * istr . position ( ) = = ' \ n ' | | * istr . position ( ) = = ' \ r ' ) <nl> - { <nl> - out < < " ERROR : Line feed found where delimiter ( " < < delimiter < < " ) is expected . " <nl> - " It ' s like your file has less columns than expected . \ n " <nl> - " And if your file have right number of columns , maybe it have unescaped quotes in values . \ n " ; <nl> - } <nl> - else <nl> - { <nl> - out < < " ERROR : There is no delimiter ( " < < delimiter < < " ) . " ; <nl> - verbosePrintString ( istr . position ( ) , istr . position ( ) + 1 , out ) ; <nl> - out < < " found instead . \ n " ; <nl> - } <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - void CSVRowInputStream : : syncAfterError ( ) <nl> - { <nl> - skipToNextLineOrEOF ( istr ) ; <nl> - } <nl> - <nl> - void CSVRowInputStream : : updateDiagnosticInfo ( ) <nl> - { <nl> - + + row_num ; <nl> - <nl> - bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row ; <nl> - bytes_read_at_start_of_buffer_on_current_row = istr . count ( ) - istr . offset ( ) ; <nl> - <nl> - pos_of_prev_row = pos_of_current_row ; <nl> - pos_of_current_row = istr . position ( ) ; <nl> - } <nl> - <nl> - bool CSVRowInputStream : : readField ( IColumn & column , const DataTypePtr & type , bool is_last_file_column , size_t column_idx ) <nl> - { <nl> - const bool at_delimiter = ! istr . eof ( ) | | * istr . position ( ) = = format_settings . csv . delimiter ; <nl> - const bool at_last_column_line_end = is_last_file_column <nl> - & & ( istr . eof ( ) | | * istr . position ( ) = = ' \ n ' | | * istr . position ( ) = = ' \ r ' ) ; <nl> - <nl> - if ( format_settings . csv . empty_as_default <nl> - & & ( at_delimiter | | at_last_column_line_end ) ) <nl> - { <nl> - / / / Treat empty unquoted column value as default value , if <nl> - / / / specified in the settings . Tuple columns might seem <nl> - / / / problematic , because they are never quoted but still contain <nl> - / / / commas , which might be also used as delimiters . However , <nl> - / / / they do not contain empty unquoted fields , so this check <nl> - / / / works for tuples as well . <nl> - return false ; <nl> - } <nl> - else if ( column_idx_to_nullable_column_idx [ column_idx ] ) <nl> - { <nl> - / / / If value is null but type is not nullable then use default value instead . <nl> - const size_t nullable_idx = * column_idx_to_nullable_column_idx [ column_idx ] ; <nl> - auto & tmp_col = * nullable_columns [ nullable_idx ] ; <nl> - nullable_types [ nullable_idx ] - > deserializeAsTextCSV ( tmp_col , istr , format_settings ) ; <nl> - Field value = tmp_col [ 0 ] ; <nl> - tmp_col . popBack ( 1 ) ; / / / do not store copy of values in memory <nl> - if ( value . isNull ( ) ) <nl> - return false ; <nl> - column . insert ( value ) ; <nl> - return true ; <nl> - } <nl> - else <nl> - { <nl> - / / / Read the column normally . <nl> - type - > deserializeAsTextCSV ( column , istr , format_settings ) ; <nl> - return true ; <nl> - } <nl> - } <nl> - <nl> - <nl> - void registerInputFormatCSV ( FormatFactory & factory ) <nl> - { <nl> - for ( bool with_names : { false , true } ) <nl> - { <nl> - factory . registerInputFormat ( with_names ? " CSVWithNames " : " CSV " , [ = ] ( <nl> - ReadBuffer & buf , <nl> - const Block & sample , <nl> - const Context & , <nl> - UInt64 max_block_size , <nl> - UInt64 rows_portion_size , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) <nl> - { <nl> - return std : : make_shared < BlockInputStreamFromRowInputStream > ( <nl> - std : : make_shared < CSVRowInputStream > ( buf , sample , with_names , settings ) , <nl> - sample , max_block_size , rows_portion_size , callback , settings ) ; <nl> - } ) ; <nl> - } <nl> - } <nl> - <nl> - } <nl> deleted file mode 100644 <nl> index b398858ee78 . . 00000000000 <nl> mmm a / dbms / src / Formats / CSVRowInputStream . h <nl> ppp / dev / null <nl> <nl> - # pragma once <nl> - <nl> - # include < optional > <nl> - # include < unordered_map > <nl> - <nl> - # include < Core / Block . h > <nl> - # include < Formats / IRowInputStream . h > <nl> - # include < Formats / FormatSettings . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - class ReadBuffer ; <nl> - <nl> - / * * A stream for inputting data in csv format . <nl> - * Does not conform with https : / / tools . ietf . org / html / rfc4180 because it skips spaces and tabs between values . <nl> - * / <nl> - class CSVRowInputStream : public IRowInputStream <nl> - { <nl> - public : <nl> - / * * with_names - in the first line the header with column names <nl> - * / <nl> - CSVRowInputStream ( ReadBuffer & istr_ , const Block & header_ , bool with_names_ , const FormatSettings & format_settings_ ) ; <nl> - <nl> - bool read ( MutableColumns & columns , RowReadExtension & ext ) override ; <nl> - void readPrefix ( ) override ; <nl> - bool allowSyncAfterError ( ) const override { return true ; } <nl> - void syncAfterError ( ) override ; <nl> - <nl> - std : : string getDiagnosticInfo ( ) override ; <nl> - <nl> - private : <nl> - ReadBuffer & istr ; <nl> - Block header ; <nl> - bool with_names ; <nl> - DataTypes data_types ; <nl> - <nl> - const FormatSettings format_settings ; <nl> - <nl> - using IndexesMap = std : : unordered_map < String , size_t > ; <nl> - IndexesMap column_indexes_by_names ; <nl> - <nl> - / / / Maps indexes of columns in the input file to indexes of table columns <nl> - using OptionalIndexes = std : : vector < std : : optional < size_t > > ; <nl> - OptionalIndexes column_indexes_for_input_fields ; <nl> - <nl> - / / / Tracks which colums we have read in a single read ( ) call . <nl> - / / / For columns that are never read , it is initialized to false when we <nl> - / / / read the file header , and never changed afterwards . <nl> - / / / For other columns , it is updated on each read ( ) call . <nl> - std : : vector < UInt8 > read_columns ; <nl> - <nl> - / / / Whether we have any columns that are not read from file at all , <nl> - / / / and must be always initialized with defaults . <nl> - bool have_always_default_columns = false ; <nl> - <nl> - void addInputColumn ( const String & column_name ) ; <nl> - <nl> - / / / For convenient diagnostics in case of an error . <nl> - size_t row_num = 0 ; <nl> - <nl> - / / / How many bytes were read , not counting those that are still in the buffer . <nl> - size_t bytes_read_at_start_of_buffer_on_current_row = 0 ; <nl> - size_t bytes_read_at_start_of_buffer_on_prev_row = 0 ; <nl> - <nl> - char * pos_of_current_row = nullptr ; <nl> - char * pos_of_prev_row = nullptr ; <nl> - <nl> - / / / For setting input_format_null_as_default <nl> - DataTypes nullable_types ; <nl> - MutableColumns nullable_columns ; <nl> - OptionalIndexes column_idx_to_nullable_column_idx ; <nl> - <nl> - void updateDiagnosticInfo ( ) ; <nl> - <nl> - bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) ; <nl> - <nl> - bool readField ( IColumn & column , const DataTypePtr & type , bool is_last_file_column , size_t column_idx ) ; <nl> - } ; <nl> - <nl> - } <nl> mmm a / dbms / src / Formats / FormatFactory . cpp <nl> ppp b / dbms / src / Formats / FormatFactory . cpp <nl> static FormatSettings getInputFormatSetting ( const Settings & settings ) <nl> format_settings . date_time_input_format = settings . date_time_input_format ; <nl> format_settings . input_allow_errors_num = settings . input_format_allow_errors_num ; <nl> format_settings . input_allow_errors_ratio = settings . input_format_allow_errors_ratio ; <nl> + format_settings . template_settings . format = settings . format_schema ; <nl> + format_settings . template_settings . row_format = settings . format_schema_rows ; <nl> + format_settings . template_settings . row_between_delimiter = settings . format_schema_rows_between_delimiter ; <nl> <nl> return format_settings ; <nl> } <nl> static FormatSettings getOutputFormatSetting ( const Settings & settings ) <nl> format_settings . pretty . max_rows = settings . output_format_pretty_max_rows ; <nl> format_settings . pretty . max_column_pad_width = settings . output_format_pretty_max_column_pad_width ; <nl> format_settings . pretty . color = settings . output_format_pretty_color ; <nl> + format_settings . template_settings . format = settings . format_schema ; <nl> + format_settings . template_settings . row_format = settings . format_schema_rows ; <nl> + format_settings . template_settings . row_between_delimiter = settings . format_schema_rows_between_delimiter ; <nl> format_settings . write_statistics = settings . output_format_write_statistics ; <nl> format_settings . parquet . row_group_size = settings . output_format_parquet_row_group_size ; <nl> <nl> void FormatFactory : : registerOutputFormatProcessor ( const String & name , OutputPro <nl> <nl> void registerInputFormatNative ( FormatFactory & factory ) ; <nl> void registerOutputFormatNative ( FormatFactory & factory ) ; <nl> - void registerInputFormatTabSeparated ( FormatFactory & factory ) ; <nl> - void registerInputFormatCSV ( FormatFactory & factory ) ; <nl> <nl> void registerInputFormatProcessorNative ( FormatFactory & factory ) ; <nl> void registerOutputFormatProcessorNative ( FormatFactory & factory ) ; <nl> void registerInputFormatProcessorORC ( FormatFactory & factory ) ; <nl> void registerOutputFormatProcessorParquet ( FormatFactory & factory ) ; <nl> void registerInputFormatProcessorProtobuf ( FormatFactory & factory ) ; <nl> void registerOutputFormatProcessorProtobuf ( FormatFactory & factory ) ; <nl> + void registerInputFormatProcessorTemplate ( FormatFactory & factory ) ; <nl> + void registerOutputFormatProcessorTemplate ( FormatFactory & factory ) ; <nl> <nl> / / / Output only ( presentational ) formats . <nl> <nl> FormatFactory : : FormatFactory ( ) <nl> { <nl> registerInputFormatNative ( * this ) ; <nl> registerOutputFormatNative ( * this ) ; <nl> - registerInputFormatTabSeparated ( * this ) ; <nl> - registerInputFormatCSV ( * this ) ; <nl> <nl> registerOutputFormatProcessorJSONEachRowWithProgress ( * this ) ; <nl> <nl> FormatFactory : : FormatFactory ( ) <nl> registerInputFormatProcessorORC ( * this ) ; <nl> registerInputFormatProcessorParquet ( * this ) ; <nl> registerOutputFormatProcessorParquet ( * this ) ; <nl> + registerInputFormatProcessorTemplate ( * this ) ; <nl> + registerOutputFormatProcessorTemplate ( * this ) ; <nl> <nl> <nl> registerOutputFormatNull ( * this ) ; <nl> mmm a / dbms / src / Formats / FormatSettings . h <nl> ppp b / dbms / src / Formats / FormatSettings . h <nl> struct FormatSettings <nl> <nl> Values values ; <nl> <nl> + struct Template <nl> + { <nl> + String format ; <nl> + String row_format ; <nl> + String row_between_delimiter ; <nl> + } ; <nl> + <nl> + Template template_settings ; <nl> + <nl> bool skip_unknown_fields = false ; <nl> bool with_names_use_header = false ; <nl> bool write_statistics = true ; <nl> new file mode 100644 <nl> index 00000000000 . . f89b1756693 <nl> mmm / dev / null <nl> ppp b / dbms / src / Formats / ParsedTemplateFormatString . cpp <nl> <nl> + # include < Formats / ParsedTemplateFormatString . h > <nl> + # include < Formats / verbosePrintString . h > <nl> + # include < IO / ReadBufferFromMemory . h > <nl> + # include < IO / Operators . h > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int INVALID_TEMPLATE_FORMAT ; <nl> + } <nl> + <nl> + ParsedTemplateFormatString : : ParsedTemplateFormatString ( const String & format_string , const ColumnIdxGetter & idx_by_name ) <nl> + { <nl> + try <nl> + { <nl> + parse ( format_string , idx_by_name ) ; <nl> + } <nl> + catch ( DB : : Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = ErrorCodes : : INVALID_TEMPLATE_FORMAT ) <nl> + throwInvalidFormat ( e . message ( ) , columnsCount ( ) ) ; <nl> + else <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + <nl> + void ParsedTemplateFormatString : : parse ( const String & format_string , const ColumnIdxGetter & idx_by_name ) <nl> + { <nl> + enum ParserState <nl> + { <nl> + Delimiter , <nl> + Column , <nl> + Format <nl> + } ; <nl> + <nl> + const char * pos = format_string . c_str ( ) ; <nl> + const char * end = format_string . c_str ( ) + format_string . size ( ) ; <nl> + const char * token_begin = pos ; <nl> + ParserState state = Delimiter ; <nl> + delimiters . emplace_back ( ) ; <nl> + for ( ; * pos ; + + pos ) <nl> + { <nl> + switch ( state ) <nl> + { <nl> + case Delimiter : <nl> + if ( * pos = = ' $ ' ) <nl> + { <nl> + delimiters . back ( ) . append ( token_begin , pos - token_begin ) ; <nl> + + + pos ; <nl> + if ( * pos = = ' { ' ) <nl> + { <nl> + token_begin = pos + 1 ; <nl> + state = Column ; <nl> + } <nl> + else if ( * pos = = ' $ ' ) <nl> + { <nl> + token_begin = pos ; <nl> + } <nl> + else <nl> + throwInvalidFormat ( " at pos " + std : : to_string ( pos - format_string . c_str ( ) ) + <nl> + " : expected ' { ' or ' $ ' after ' $ ' " , columnsCount ( ) ) ; <nl> + } <nl> + break ; <nl> + <nl> + case Column : <nl> + column_names . emplace_back ( ) ; <nl> + pos = readMayBeQuotedColumnNameInto ( pos , end - pos , column_names . back ( ) ) ; <nl> + <nl> + if ( * pos = = ' : ' ) <nl> + state = Format ; <nl> + else if ( * pos = = ' } ' ) <nl> + { <nl> + formats . push_back ( ColumnFormat : : None ) ; <nl> + delimiters . emplace_back ( ) ; <nl> + state = Delimiter ; <nl> + } <nl> + else <nl> + throwInvalidFormat ( " Expected ' : ' or ' } ' after column name : \ " " + column_names . back ( ) + " \ " " , columnsCount ( ) ) ; <nl> + <nl> + token_begin = pos + 1 ; <nl> + format_idx_to_column_idx . emplace_back ( idx_by_name ( column_names . back ( ) ) ) ; <nl> + break ; <nl> + <nl> + case Format : <nl> + if ( * pos = = ' } ' ) <nl> + { <nl> + formats . push_back ( stringToFormat ( String ( token_begin , pos - token_begin ) ) ) ; <nl> + token_begin = pos + 1 ; <nl> + delimiters . emplace_back ( ) ; <nl> + state = Delimiter ; <nl> + } <nl> + } <nl> + } <nl> + if ( state ! = Delimiter ) <nl> + throwInvalidFormat ( " Unbalanced parentheses " , columnsCount ( ) ) ; <nl> + delimiters . back ( ) . append ( token_begin , pos - token_begin ) ; <nl> + } <nl> + <nl> + <nl> + ParsedTemplateFormatString : : ColumnFormat ParsedTemplateFormatString : : stringToFormat ( const String & col_format ) const <nl> + { <nl> + if ( col_format . empty ( ) ) <nl> + return ColumnFormat : : None ; <nl> + else if ( col_format = = " None " ) <nl> + return ColumnFormat : : None ; <nl> + else if ( col_format = = " Escaped " ) <nl> + return ColumnFormat : : Escaped ; <nl> + else if ( col_format = = " Quoted " ) <nl> + return ColumnFormat : : Quoted ; <nl> + else if ( col_format = = " CSV " ) <nl> + return ColumnFormat : : Csv ; <nl> + else if ( col_format = = " JSON " ) <nl> + return ColumnFormat : : Json ; <nl> + else if ( col_format = = " XML " ) <nl> + return ColumnFormat : : Xml ; <nl> + else if ( col_format = = " Raw " ) <nl> + return ColumnFormat : : Raw ; <nl> + else <nl> + throwInvalidFormat ( " Unknown field format " + col_format , columnsCount ( ) ) ; <nl> + } <nl> + <nl> + size_t ParsedTemplateFormatString : : columnsCount ( ) const <nl> + { <nl> + return format_idx_to_column_idx . size ( ) ; <nl> + } <nl> + <nl> + String ParsedTemplateFormatString : : formatToString ( ParsedTemplateFormatString : : ColumnFormat format ) <nl> + { <nl> + switch ( format ) <nl> + { <nl> + case ColumnFormat : : None : <nl> + return " None " ; <nl> + case ColumnFormat : : Escaped : <nl> + return " Escaped " ; <nl> + case ColumnFormat : : Quoted : <nl> + return " Quoted " ; <nl> + case ColumnFormat : : Csv : <nl> + return " CSV " ; <nl> + case ColumnFormat : : Json : <nl> + return " Json " ; <nl> + case ColumnFormat : : Xml : <nl> + return " Xml " ; <nl> + case ColumnFormat : : Raw : <nl> + return " Raw " ; <nl> + } <nl> + __builtin_unreachable ( ) ; <nl> + } <nl> + <nl> + const char * ParsedTemplateFormatString : : readMayBeQuotedColumnNameInto ( const char * pos , size_t size , String & s ) <nl> + { <nl> + s . clear ( ) ; <nl> + if ( ! size ) <nl> + return pos ; <nl> + ReadBufferFromMemory buf { pos , size } ; <nl> + if ( * pos = = ' " ' ) <nl> + readDoubleQuotedStringWithSQLStyle ( s , buf ) ; <nl> + else if ( * pos = = ' ` ' ) <nl> + readBackQuotedStringWithSQLStyle ( s , buf ) ; <nl> + else if ( isWordCharASCII ( * pos ) ) <nl> + { <nl> + size_t name_size = 1 ; <nl> + while ( name_size < size & & isWordCharASCII ( * ( pos + name_size ) ) ) <nl> + + + name_size ; <nl> + s = String { pos , name_size } ; <nl> + return pos + name_size ; <nl> + } <nl> + return pos + buf . count ( ) ; <nl> + } <nl> + <nl> + String ParsedTemplateFormatString : : dump ( ) const <nl> + { <nl> + WriteBufferFromOwnString res ; <nl> + res < < " Delimiter " < < 0 < < " : " ; <nl> + verbosePrintString ( delimiters . front ( ) . c_str ( ) , delimiters . front ( ) . c_str ( ) + delimiters . front ( ) . size ( ) , res ) ; <nl> + <nl> + size_t num_columns = std : : max ( formats . size ( ) , format_idx_to_column_idx . size ( ) ) ; <nl> + for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> + { <nl> + res < < " \ nColumn " < < i < < " : \ " " ; <nl> + if ( column_names . size ( ) < = i ) <nl> + res < < " < ERROR > " ; <nl> + else if ( column_names [ i ] . empty ( ) ) <nl> + res < < " < SKIPPED > " ; <nl> + else <nl> + res < < column_names [ i ] ; <nl> + <nl> + res < < " \ " ( mapped to table column " ; <nl> + if ( format_idx_to_column_idx . size ( ) < = i ) <nl> + res < < " < ERROR > " ; <nl> + else if ( ! format_idx_to_column_idx [ i ] ) <nl> + res < < " < SKIPPED > " ; <nl> + else <nl> + res < < * format_idx_to_column_idx [ i ] ; <nl> + <nl> + res < < " ) , Format " < < ( i < formats . size ( ) ? formatToString ( formats [ i ] ) : " < ERROR > " ) ; <nl> + <nl> + res < < " \ nDelimiter " < < i + 1 < < " : " ; <nl> + if ( delimiters . size ( ) < = i + 1 ) <nl> + res < < " < ERROR > " ; <nl> + else <nl> + verbosePrintString ( delimiters [ i + 1 ] . c_str ( ) , delimiters [ i + 1 ] . c_str ( ) + delimiters [ i + 1 ] . size ( ) , res ) ; <nl> + } <nl> + <nl> + return res . str ( ) ; <nl> + } <nl> + <nl> + void ParsedTemplateFormatString : : throwInvalidFormat ( const String & message , size_t column ) const <nl> + { <nl> + throw Exception ( " Invalid format string for Template : " + message + " ( near column " + std : : to_string ( column ) + <nl> + " ) " + " . Parsed format string : \ n " + dump ( ) + " \ n " , <nl> + ErrorCodes : : INVALID_TEMPLATE_FORMAT ) ; <nl> + } <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 5353f336f64 <nl> mmm / dev / null <nl> ppp b / dbms / src / Formats / ParsedTemplateFormatString . h <nl> <nl> + # pragma once <nl> + <nl> + # include < Core / Types . h > <nl> + # include < functional > <nl> + # include < optional > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + struct ParsedTemplateFormatString <nl> + { <nl> + enum class ColumnFormat <nl> + { <nl> + None , <nl> + Escaped , <nl> + Quoted , <nl> + Csv , <nl> + Json , <nl> + Xml , <nl> + Raw <nl> + } ; <nl> + <nl> + / / / Format string has syntax : " Delimiter0 $ { ColumnName0 : Format0 } Delimiter1 $ { ColumnName1 : Format1 } Delimiter2 " <nl> + / / / The following vectors is filled with corresponding values , delimiters . size ( ) - 1 = formats . size ( ) = format_idx_to_column_idx . size ( ) <nl> + / / / If format_idx_to_column_idx [ i ] has no value , then TemplateRowInputFormat will skip i - th column . <nl> + <nl> + std : : vector < String > delimiters ; <nl> + std : : vector < ColumnFormat > formats ; <nl> + std : : vector < std : : optional < size_t > > format_idx_to_column_idx ; <nl> + <nl> + / / / For diagnostic info <nl> + Strings column_names ; <nl> + <nl> + typedef std : : function < std : : optional < size_t > ( const String & ) > ColumnIdxGetter ; <nl> + <nl> + ParsedTemplateFormatString ( ) = default ; <nl> + ParsedTemplateFormatString ( const String & format_string , const ColumnIdxGetter & idx_by_name ) ; <nl> + <nl> + void parse ( const String & format_string , const ColumnIdxGetter & idx_by_name ) ; <nl> + <nl> + ColumnFormat stringToFormat ( const String & format ) const ; <nl> + static String formatToString ( ColumnFormat format ) ; <nl> + static const char * readMayBeQuotedColumnNameInto ( const char * pos , size_t size , String & s ) ; <nl> + size_t columnsCount ( ) const ; <nl> + <nl> + String dump ( ) const ; <nl> + [ [ noreturn ] ] void throwInvalidFormat ( const String & message , size_t column ) const ; <nl> + } ; <nl> + <nl> + } <nl> + <nl> deleted file mode 100644 <nl> index 69850dbc455 . . 00000000000 <nl> mmm a / dbms / src / Formats / TabSeparatedRowInputStream . cpp <nl> ppp / dev / null <nl> <nl> - # include < string > <nl> - <nl> - # include < Core / Defines . h > <nl> - <nl> - # include < IO / ReadHelpers . h > <nl> - # include < IO / WriteBufferFromString . h > <nl> - # include < IO / Operators . h > <nl> - <nl> - # include < Formats / TabSeparatedRowInputStream . h > <nl> - # include < Formats / verbosePrintString . h > <nl> - # include < Formats / FormatFactory . h > <nl> - # include < Formats / BlockInputStreamFromRowInputStream . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int INCORRECT_DATA ; <nl> - extern const int LOGICAL_ERROR ; <nl> - } <nl> - <nl> - <nl> - static void skipTSVRow ( ReadBuffer & istr , const size_t num_columns ) <nl> - { <nl> - NullSink null_sink ; <nl> - <nl> - for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> - { <nl> - readEscapedStringInto ( null_sink , istr ) ; <nl> - assertChar ( i = = num_columns - 1 ? ' \ n ' : ' \ t ' , istr ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - / * * Check for a common error case - usage of Windows line feed . <nl> - * / <nl> - static void checkForCarriageReturn ( ReadBuffer & istr ) <nl> - { <nl> - if ( istr . position ( ) [ 0 ] = = ' \ r ' | | ( istr . position ( ) ! = istr . buffer ( ) . begin ( ) & & istr . position ( ) [ - 1 ] = = ' \ r ' ) ) <nl> - throw Exception ( " \ nYou have carriage return ( \ \ r , 0x0D , ASCII 13 ) at end of first row . " <nl> - " \ nIt ' s like your input data has DOS / Windows style line separators , that are illegal in TabSeparated format . " <nl> - " You must transform your file to Unix format . " <nl> - " \ nBut if you really need carriage return at end of string value of last column , you need to escape it as \ \ r . " , <nl> - ErrorCodes : : INCORRECT_DATA ) ; <nl> - } <nl> - <nl> - <nl> - TabSeparatedRowInputStream : : TabSeparatedRowInputStream ( <nl> - ReadBuffer & istr_ , const Block & header_ , bool with_names_ , bool with_types_ , const FormatSettings & format_settings_ ) <nl> - : istr ( istr_ ) , header ( header_ ) , with_names ( with_names_ ) , with_types ( with_types_ ) , format_settings ( format_settings_ ) <nl> - { <nl> - const auto num_columns = header . columns ( ) ; <nl> - <nl> - data_types . resize ( num_columns ) ; <nl> - column_indexes_by_names . reserve ( num_columns ) ; <nl> - <nl> - for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> - { <nl> - const auto & column_info = header . getByPosition ( i ) ; <nl> - <nl> - data_types [ i ] = column_info . type ; <nl> - column_indexes_by_names . emplace ( column_info . name , i ) ; <nl> - } <nl> - <nl> - column_indexes_for_input_fields . reserve ( num_columns ) ; <nl> - read_columns . assign ( num_columns , false ) ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : setupAllColumnsByTableSchema ( ) <nl> - { <nl> - read_columns . assign ( header . columns ( ) , true ) ; <nl> - column_indexes_for_input_fields . resize ( header . columns ( ) ) ; <nl> - <nl> - for ( size_t i = 0 ; i < column_indexes_for_input_fields . size ( ) ; + + i ) <nl> - column_indexes_for_input_fields [ i ] = i ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : addInputColumn ( const String & column_name ) <nl> - { <nl> - const auto column_it = column_indexes_by_names . find ( column_name ) ; <nl> - if ( column_it = = column_indexes_by_names . end ( ) ) <nl> - { <nl> - if ( format_settings . skip_unknown_fields ) <nl> - { <nl> - column_indexes_for_input_fields . push_back ( std : : nullopt ) ; <nl> - return ; <nl> - } <nl> - <nl> - throw Exception ( <nl> - " Unknown field found in TSV header : ' " + column_name + " ' " + <nl> - " at position " + std : : to_string ( column_indexes_for_input_fields . size ( ) ) + <nl> - " \ nSet the ' input_format_skip_unknown_fields ' parameter explicitly to ignore and proceed " , <nl> - ErrorCodes : : INCORRECT_DATA <nl> - ) ; <nl> - } <nl> - <nl> - const auto column_index = column_it - > second ; <nl> - <nl> - if ( read_columns [ column_index ] ) <nl> - throw Exception ( " Duplicate field found while parsing TSV header : " + column_name , ErrorCodes : : INCORRECT_DATA ) ; <nl> - <nl> - read_columns [ column_index ] = true ; <nl> - column_indexes_for_input_fields . emplace_back ( column_index ) ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : fillUnreadColumnsWithDefaults ( MutableColumns & columns , RowReadExtension & row_read_extension ) <nl> - { <nl> - / / / It is safe to memorize this on the first run - the format guarantees this does not change <nl> - if ( unlikely ( row_num = = 1 ) ) <nl> - { <nl> - columns_to_fill_with_default_values . clear ( ) ; <nl> - for ( size_t index = 0 ; index < read_columns . size ( ) ; + + index ) <nl> - if ( read_columns [ index ] = = 0 ) <nl> - columns_to_fill_with_default_values . push_back ( index ) ; <nl> - } <nl> - <nl> - for ( const auto column_index : columns_to_fill_with_default_values ) <nl> - data_types [ column_index ] - > insertDefaultInto ( * columns [ column_index ] ) ; <nl> - <nl> - row_read_extension . read_columns = read_columns ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : readPrefix ( ) <nl> - { <nl> - if ( with_names | | with_types ) <nl> - { <nl> - / / / In this format , we assume that column name or type cannot contain BOM , <nl> - / / / so , if format has header , <nl> - / / / then BOM at beginning of stream cannot be confused with name or type of field , and it is safe to skip it . <nl> - skipBOMIfExists ( istr ) ; <nl> - } <nl> - <nl> - if ( with_names ) <nl> - { <nl> - if ( format_settings . with_names_use_header ) <nl> - { <nl> - String column_name ; <nl> - do <nl> - { <nl> - readEscapedString ( column_name , istr ) ; <nl> - addInputColumn ( column_name ) ; <nl> - } <nl> - while ( checkChar ( ' \ t ' , istr ) ) ; <nl> - <nl> - if ( ! istr . eof ( ) ) <nl> - { <nl> - checkForCarriageReturn ( istr ) ; <nl> - assertChar ( ' \ n ' , istr ) ; <nl> - } <nl> - } <nl> - else <nl> - { <nl> - setupAllColumnsByTableSchema ( ) ; <nl> - skipTSVRow ( istr , column_indexes_for_input_fields . size ( ) ) ; <nl> - } <nl> - } <nl> - else <nl> - setupAllColumnsByTableSchema ( ) ; <nl> - <nl> - if ( with_types ) <nl> - { <nl> - skipTSVRow ( istr , column_indexes_for_input_fields . size ( ) ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - bool TabSeparatedRowInputStream : : read ( MutableColumns & columns , RowReadExtension & ext ) <nl> - { <nl> - if ( istr . eof ( ) ) <nl> - return false ; <nl> - <nl> - updateDiagnosticInfo ( ) ; <nl> - <nl> - for ( size_t input_position = 0 ; input_position < column_indexes_for_input_fields . size ( ) ; + + input_position ) <nl> - { <nl> - const auto & column_index = column_indexes_for_input_fields [ input_position ] ; <nl> - if ( column_index ) <nl> - { <nl> - data_types [ * column_index ] - > deserializeAsTextEscaped ( * columns [ * column_index ] , istr , format_settings ) ; <nl> - } <nl> - else <nl> - { <nl> - NullSink null_sink ; <nl> - readEscapedStringInto ( null_sink , istr ) ; <nl> - } <nl> - <nl> - / / / skip separators <nl> - if ( input_position + 1 < column_indexes_for_input_fields . size ( ) ) <nl> - { <nl> - assertChar ( ' \ t ' , istr ) ; <nl> - } <nl> - else if ( ! istr . eof ( ) ) <nl> - { <nl> - if ( unlikely ( row_num = = 1 ) ) <nl> - checkForCarriageReturn ( istr ) ; <nl> - <nl> - assertChar ( ' \ n ' , istr ) ; <nl> - } <nl> - } <nl> - <nl> - fillUnreadColumnsWithDefaults ( columns , ext ) ; <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - String TabSeparatedRowInputStream : : getDiagnosticInfo ( ) <nl> - { <nl> - if ( istr . eof ( ) ) / / / Buffer has gone , cannot extract information about what has been parsed . <nl> - return { } ; <nl> - <nl> - WriteBufferFromOwnString out ; <nl> - MutableColumns columns = header . cloneEmptyColumns ( ) ; <nl> - <nl> - / / / It is possible to display detailed diagnostics only if the last and next to last lines are still in the read buffer . <nl> - size_t bytes_read_at_start_of_buffer = istr . count ( ) - istr . offset ( ) ; <nl> - if ( bytes_read_at_start_of_buffer ! = bytes_read_at_start_of_buffer_on_prev_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because two last rows aren ' t in buffer ( rare case ) \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - size_t max_length_of_column_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . name . size ( ) > max_length_of_column_name ) <nl> - max_length_of_column_name = header . safeGetByPosition ( i ) . name . size ( ) ; <nl> - <nl> - size_t max_length_of_data_type_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) > max_length_of_data_type_name ) <nl> - max_length_of_data_type_name = header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) ; <nl> - <nl> - / / / Roll back the cursor to the beginning of the previous or current line and parse all over again . But now we derive detailed information . <nl> - <nl> - if ( pos_of_prev_row ) <nl> - { <nl> - istr . position ( ) = pos_of_prev_row ; <nl> - <nl> - out < < " \ nRow " < < ( row_num - 1 ) < < " : \ n " ; <nl> - if ( ! parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ) <nl> - return out . str ( ) ; <nl> - } <nl> - else <nl> - { <nl> - if ( ! pos_of_current_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because parsing of data hasn ' t started . \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - istr . position ( ) = pos_of_current_row ; <nl> - } <nl> - <nl> - out < < " \ nRow " < < row_num < < " : \ n " ; <nl> - parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ; <nl> - out < < " \ n " ; <nl> - <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - <nl> - / * * gcc - 7 generates wrong code with optimization level greater than 1 . <nl> - * See tests : dbms / src / IO / tests / write_int . cpp <nl> - * and dbms / tests / queries / 0_stateless / 00898_parsing_bad_diagnostic_message . sh <nl> - * This is compiler bug . The bug does not present in gcc - 8 and clang - 8 . <nl> - * Nevertheless , we don ' t need high optimization of this function . <nl> - * / <nl> - bool OPTIMIZE ( 1 ) TabSeparatedRowInputStream : : parseRowAndPrintDiagnosticInfo ( <nl> - MutableColumns & columns , WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) <nl> - { <nl> - for ( size_t input_position = 0 ; input_position < column_indexes_for_input_fields . size ( ) ; + + input_position ) <nl> - { <nl> - if ( input_position = = 0 & & istr . eof ( ) ) <nl> - { <nl> - out < < " < End of stream > \ n " ; <nl> - return false ; <nl> - } <nl> - <nl> - if ( column_indexes_for_input_fields [ input_position ] . has_value ( ) ) <nl> - { <nl> - const auto & column_index = * column_indexes_for_input_fields [ input_position ] ; <nl> - const auto & current_column_type = data_types [ column_index ] ; <nl> - <nl> - out < < " Column " < < input_position < < " , " < < std : : string ( ( input_position < 10 ? 2 : input_position < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < header . safeGetByPosition ( column_index ) . name < < " , " < < std : : string ( max_length_of_column_name - header . safeGetByPosition ( column_index ) . name . size ( ) , ' ' ) <nl> - < < " type : " < < current_column_type - > getName ( ) < < " , " < < std : : string ( max_length_of_data_type_name - current_column_type - > getName ( ) . size ( ) , ' ' ) ; <nl> - <nl> - auto prev_position = istr . position ( ) ; <nl> - std : : exception_ptr exception ; <nl> - <nl> - try <nl> - { <nl> - current_column_type - > deserializeAsTextEscaped ( * columns [ column_index ] , istr , format_settings ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - exception = std : : current_exception ( ) ; <nl> - } <nl> - <nl> - auto curr_position = istr . position ( ) ; <nl> - <nl> - if ( curr_position < prev_position ) <nl> - throw Exception ( " Logical error : parsing is non - deterministic . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - if ( isNativeNumber ( current_column_type ) | | isDateOrDateTime ( current_column_type ) ) <nl> - { <nl> - / / / An empty string instead of a value . <nl> - if ( curr_position = = prev_position ) <nl> - { <nl> - out < < " ERROR : text " ; <nl> - verbosePrintString ( prev_position , std : : min ( prev_position + 10 , istr . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " is not like " < < current_column_type - > getName ( ) < < " \ n " ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - out < < " parsed text : " ; <nl> - verbosePrintString ( prev_position , curr_position , out ) ; <nl> - <nl> - if ( exception ) <nl> - { <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - else <nl> - out < < " ERROR \ n " ; <nl> - return false ; <nl> - } <nl> - <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > haveMaximumSizeOfValue ( ) ) <nl> - { <nl> - if ( * curr_position ! = ' \ n ' & & * curr_position ! = ' \ t ' ) <nl> - { <nl> - out < < " ERROR : garbage after " < < current_column_type - > getName ( ) < < " : " ; <nl> - verbosePrintString ( curr_position , std : : min ( curr_position + 10 , istr . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - else <nl> - { <nl> - static const String skipped_column_str = " < SKIPPED COLUMN > " ; <nl> - out < < " Column " < < input_position < < " , " < < std : : string ( ( input_position < 10 ? 2 : input_position < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_column_name - skipped_column_str . length ( ) , ' ' ) <nl> - < < " type : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_data_type_name - skipped_column_str . length ( ) , ' ' ) ; <nl> - <nl> - NullSink null_sink ; <nl> - readEscapedStringInto ( null_sink , istr ) ; <nl> - } <nl> - <nl> - / / / Delimiters <nl> - if ( input_position + 1 = = column_indexes_for_input_fields . size ( ) ) <nl> - { <nl> - if ( ! istr . eof ( ) ) <nl> - { <nl> - try <nl> - { <nl> - assertChar ( ' \ n ' , istr ) ; <nl> - } <nl> - catch ( const DB : : Exception & ) <nl> - { <nl> - if ( * istr . position ( ) = = ' \ t ' ) <nl> - { <nl> - out < < " ERROR : Tab found where line feed is expected . " <nl> - " It ' s like your file has more columns than expected . \ n " <nl> - " And if your file have right number of columns , maybe it have unescaped tab in value . \ n " ; <nl> - } <nl> - else if ( * istr . position ( ) = = ' \ r ' ) <nl> - { <nl> - out < < " ERROR : Carriage return found where line feed is expected . " <nl> - " It ' s like your file has DOS / Windows style line separators , that is illegal in TabSeparated format . \ n " ; <nl> - } <nl> - else <nl> - { <nl> - out < < " ERROR : There is no line feed . " ; <nl> - verbosePrintString ( istr . position ( ) , istr . position ( ) + 1 , out ) ; <nl> - out < < " found instead . \ n " ; <nl> - } <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - else <nl> - { <nl> - try <nl> - { <nl> - assertChar ( ' \ t ' , istr ) ; <nl> - } <nl> - catch ( const DB : : Exception & ) <nl> - { <nl> - if ( * istr . position ( ) = = ' \ n ' ) <nl> - { <nl> - out < < " ERROR : Line feed found where tab is expected . " <nl> - " It ' s like your file has less columns than expected . \ n " <nl> - " And if your file have right number of columns , maybe it have unescaped backslash in value before tab , which cause tab has escaped . \ n " ; <nl> - } <nl> - else if ( * istr . position ( ) = = ' \ r ' ) <nl> - { <nl> - out < < " ERROR : Carriage return found where tab is expected . \ n " ; <nl> - } <nl> - else <nl> - { <nl> - out < < " ERROR : There is no tab . " ; <nl> - verbosePrintString ( istr . position ( ) , istr . position ( ) + 1 , out ) ; <nl> - out < < " found instead . \ n " ; <nl> - } <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : syncAfterError ( ) <nl> - { <nl> - skipToUnescapedNextLineOrEOF ( istr ) ; <nl> - } <nl> - <nl> - <nl> - void TabSeparatedRowInputStream : : updateDiagnosticInfo ( ) <nl> - { <nl> - + + row_num ; <nl> - <nl> - bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row ; <nl> - bytes_read_at_start_of_buffer_on_current_row = istr . count ( ) - istr . offset ( ) ; <nl> - <nl> - pos_of_prev_row = pos_of_current_row ; <nl> - pos_of_current_row = istr . position ( ) ; <nl> - } <nl> - <nl> - <nl> - void registerInputFormatTabSeparated ( FormatFactory & factory ) <nl> - { <nl> - for ( auto name : { " TabSeparated " , " TSV " } ) <nl> - { <nl> - factory . registerInputFormat ( name , [ ] ( <nl> - ReadBuffer & buf , <nl> - const Block & sample , <nl> - const Context & , <nl> - UInt64 max_block_size , <nl> - UInt64 rows_portion_size , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) <nl> - { <nl> - return std : : make_shared < BlockInputStreamFromRowInputStream > ( <nl> - std : : make_shared < TabSeparatedRowInputStream > ( buf , sample , false , false , settings ) , <nl> - sample , max_block_size , rows_portion_size , callback , settings ) ; <nl> - } ) ; <nl> - } <nl> - <nl> - for ( auto name : { " TabSeparatedWithNames " , " TSVWithNames " } ) <nl> - { <nl> - factory . registerInputFormat ( name , [ ] ( <nl> - ReadBuffer & buf , <nl> - const Block & sample , <nl> - const Context & , <nl> - UInt64 max_block_size , <nl> - UInt64 rows_portion_size , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) <nl> - { <nl> - return std : : make_shared < BlockInputStreamFromRowInputStream > ( <nl> - std : : make_shared < TabSeparatedRowInputStream > ( buf , sample , true , false , settings ) , <nl> - sample , max_block_size , rows_portion_size , callback , settings ) ; <nl> - } ) ; <nl> - } <nl> - <nl> - for ( auto name : { " TabSeparatedWithNamesAndTypes " , " TSVWithNamesAndTypes " } ) <nl> - { <nl> - factory . registerInputFormat ( name , [ ] ( <nl> - ReadBuffer & buf , <nl> - const Block & sample , <nl> - const Context & , <nl> - UInt64 max_block_size , <nl> - UInt64 rows_portion_size , <nl> - FormatFactory : : ReadCallback callback , <nl> - const FormatSettings & settings ) <nl> - { <nl> - return std : : make_shared < BlockInputStreamFromRowInputStream > ( <nl> - std : : make_shared < TabSeparatedRowInputStream > ( buf , sample , true , true , settings ) , <nl> - sample , max_block_size , rows_portion_size , callback , settings ) ; <nl> - } ) ; <nl> - } <nl> - } <nl> - <nl> - } <nl> deleted file mode 100644 <nl> index f8ebebbdfe4 . . 00000000000 <nl> mmm a / dbms / src / Formats / TabSeparatedRowInputStream . h <nl> ppp / dev / null <nl> <nl> - # pragma once <nl> - <nl> - # include < optional > <nl> - # include < unordered_map > <nl> - <nl> - # include < Core / Block . h > <nl> - # include < Formats / FormatSettings . h > <nl> - # include < Formats / IRowInputStream . h > <nl> - <nl> - <nl> - namespace DB <nl> - { <nl> - <nl> - class ReadBuffer ; <nl> - <nl> - <nl> - / * * A stream to input data in tsv format . <nl> - * / <nl> - class TabSeparatedRowInputStream : public IRowInputStream <nl> - { <nl> - public : <nl> - / * * with_names - the first line is the header with the names of the columns <nl> - * with_types - on the next line header with type names <nl> - * / <nl> - TabSeparatedRowInputStream ( <nl> - ReadBuffer & istr_ , const Block & header_ , bool with_names_ , bool with_types_ , const FormatSettings & format_settings_ ) ; <nl> - <nl> - bool read ( MutableColumns & columns , RowReadExtension & ext ) override ; <nl> - void readPrefix ( ) override ; <nl> - bool allowSyncAfterError ( ) const override { return true ; } <nl> - void syncAfterError ( ) override ; <nl> - <nl> - std : : string getDiagnosticInfo ( ) override ; <nl> - <nl> - private : <nl> - ReadBuffer & istr ; <nl> - Block header ; <nl> - bool with_names ; <nl> - bool with_types ; <nl> - const FormatSettings format_settings ; <nl> - DataTypes data_types ; <nl> - <nl> - using IndexesMap = std : : unordered_map < String , size_t > ; <nl> - IndexesMap column_indexes_by_names ; <nl> - <nl> - using OptionalIndexes = std : : vector < std : : optional < size_t > > ; <nl> - OptionalIndexes column_indexes_for_input_fields ; <nl> - <nl> - std : : vector < UInt8 > read_columns ; <nl> - std : : vector < size_t > columns_to_fill_with_default_values ; <nl> - <nl> - void addInputColumn ( const String & column_name ) ; <nl> - void setupAllColumnsByTableSchema ( ) ; <nl> - void fillUnreadColumnsWithDefaults ( MutableColumns & columns , RowReadExtension & ext ) ; <nl> - <nl> - / / / For convenient diagnostics in case of an error . <nl> - <nl> - size_t row_num = 0 ; <nl> - <nl> - / / / How many bytes were read , not counting those still in the buffer . <nl> - size_t bytes_read_at_start_of_buffer_on_current_row = 0 ; <nl> - size_t bytes_read_at_start_of_buffer_on_prev_row = 0 ; <nl> - <nl> - char * pos_of_current_row = nullptr ; <nl> - char * pos_of_prev_row = nullptr ; <nl> - <nl> - void updateDiagnosticInfo ( ) ; <nl> - <nl> - bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) ; <nl> - } ; <nl> - <nl> - } <nl> mmm a / dbms / src / Formats / tests / CMakeLists . txt <nl> ppp b / dbms / src / Formats / tests / CMakeLists . txt <nl> set ( SRCS ) <nl> <nl> add_executable ( tab_separated_streams tab_separated_streams . cpp $ { SRCS } ) <nl> target_link_libraries ( tab_separated_streams PRIVATE dbms ) <nl> - <nl> - add_executable ( block_row_transforms block_row_transforms . cpp $ { SRCS } ) <nl> - target_link_libraries ( block_row_transforms PRIVATE dbms ) <nl> deleted file mode 100644 <nl> index 9edc520d85f . . 00000000000 <nl> mmm a / dbms / src / Formats / tests / block_row_transforms . cpp <nl> ppp / dev / null <nl> <nl> - # include < string > <nl> - <nl> - # include < iostream > <nl> - # include < fstream > <nl> - <nl> - # include < Core / Block . h > <nl> - # include < Core / ColumnWithTypeAndName . h > <nl> - <nl> - # include < IO / ReadBufferFromFile . h > <nl> - # include < IO / WriteBufferFromFile . h > <nl> - <nl> - # include < DataTypes / DataTypesNumber . h > <nl> - # include < DataTypes / DataTypeString . h > <nl> - <nl> - # include < Formats / TabSeparatedRowInputStream . h > <nl> - # include < Formats / BlockInputStreamFromRowInputStream . h > <nl> - <nl> - # include < DataStreams / copyData . h > <nl> - # include < Processors / Formats / Impl / TabSeparatedRowOutputFormat . h > <nl> - # include < Processors / Formats / OutputStreamToOutputFormat . h > <nl> - <nl> - <nl> - int main ( int , char * * ) <nl> - try <nl> - { <nl> - using namespace DB ; <nl> - <nl> - Block sample ; <nl> - <nl> - ColumnWithTypeAndName col1 ; <nl> - col1 . name = " col1 " ; <nl> - col1 . type = std : : make_shared < DataTypeUInt64 > ( ) ; <nl> - col1 . column = col1 . type - > createColumn ( ) ; <nl> - sample . insert ( col1 ) ; <nl> - <nl> - ColumnWithTypeAndName col2 ; <nl> - col2 . name = " col2 " ; <nl> - col2 . type = std : : make_shared < DataTypeString > ( ) ; <nl> - col2 . column = col2 . type - > createColumn ( ) ; <nl> - sample . insert ( col2 ) ; <nl> - <nl> - ReadBufferFromFile in_buf ( " test_in " ) ; <nl> - WriteBufferFromFile out_buf ( " test_out " ) ; <nl> - <nl> - FormatSettings format_settings ; <nl> - <nl> - RowInputStreamPtr row_input = std : : make_shared < TabSeparatedRowInputStream > ( in_buf , sample , false , false , format_settings ) ; <nl> - BlockInputStreamFromRowInputStream block_input ( row_input , sample , DEFAULT_INSERT_BLOCK_SIZE , 0 , [ ] { } , format_settings ) ; <nl> - BlockOutputStreamPtr block_output = std : : make_shared < OutputStreamToOutputFormat > ( std : : make_shared < TabSeparatedRowOutputFormat > ( out_buf , sample , false , false , [ ] { } , format_settings ) ) ; <nl> - <nl> - copyData ( block_input , * block_output ) ; <nl> - } <nl> - catch ( const DB : : Exception & e ) <nl> - { <nl> - std : : cerr < < e . what ( ) < < " , " < < e . displayText ( ) < < std : : endl ; <nl> - return 1 ; <nl> - } <nl> mmm a / dbms / src / Formats / tests / tab_separated_streams . cpp <nl> ppp b / dbms / src / Formats / tests / tab_separated_streams . cpp <nl> <nl> # include < DataTypes / DataTypesNumber . h > <nl> # include < DataTypes / DataTypeString . h > <nl> <nl> - # include < Formats / TabSeparatedRowInputStream . h > <nl> - # include < Formats / BlockInputStreamFromRowInputStream . h > <nl> + # include < Processors / Formats / Impl / TabSeparatedRowInputFormat . h > <nl> <nl> # include < DataStreams / copyData . h > <nl> # include < Processors / Formats / OutputStreamToOutputFormat . h > <nl> # include < Processors / Formats / Impl / TabSeparatedRowOutputFormat . h > <nl> + # include < Processors / Formats / InputStreamFromInputFormat . h > <nl> <nl> <nl> using namespace DB ; <nl> try <nl> <nl> FormatSettings format_settings ; <nl> <nl> - RowInputStreamPtr row_input = std : : make_shared < TabSeparatedRowInputStream > ( in_buf , sample , false , false , format_settings ) ; <nl> - BlockInputStreamFromRowInputStream block_input ( row_input , sample , DEFAULT_INSERT_BLOCK_SIZE , 0 , [ ] { } , format_settings ) ; <nl> + RowInputFormatParams params { DEFAULT_INSERT_BLOCK_SIZE , 0 , 0 , 0 , [ ] { } } ; <nl> + <nl> + InputFormatPtr input_format = std : : make_shared < TabSeparatedRowInputFormat > ( sample , in_buf , params , false , false , format_settings ) ; <nl> + BlockInputStreamPtr block_input = std : : make_shared < InputStreamFromInputFormat > ( std : : move ( input_format ) ) ; <nl> <nl> BlockOutputStreamPtr block_output = std : : make_shared < OutputStreamToOutputFormat > ( <nl> std : : make_shared < TabSeparatedRowOutputFormat > ( out_buf , sample , false , false , [ ] { } , format_settings ) ) ; <nl> <nl> - copyData ( block_input , * block_output ) ; <nl> + copyData ( * block_input , * block_output ) ; <nl> return 0 ; <nl> } <nl> catch ( . . . ) <nl> mmm a / dbms / src / Functions / FunctionJoinGet . cpp <nl> ppp b / dbms / src / Functions / FunctionJoinGet . cpp <nl> FunctionBasePtr FunctionBuilderJoinGet : : buildImpl ( const ColumnsWithTypeAndName & <nl> auto join = storage_join - > getJoin ( ) ; <nl> DataTypes data_types ( arguments . size ( ) ) ; <nl> <nl> - auto table_lock = storage_join - > lockStructureForShare ( false , context . getCurrentQueryId ( ) ) ; <nl> + auto table_lock = storage_join - > lockStructureForShare ( false , context . getInitialQueryId ( ) ) ; <nl> for ( size_t i = 0 ; i < arguments . size ( ) ; + + i ) <nl> data_types [ i ] = arguments [ i ] . type ; <nl> <nl> mmm a / dbms / src / Functions / GeoUtils . cpp <nl> ppp b / dbms / src / Functions / GeoUtils . cpp <nl> UInt64 geohashesInBox ( const GeohashesInBoxPreparedArgs & args , char * out ) <nl> } <nl> } <nl> <nl> - if ( items = = 0 & & args . items_count ! = 0 ) <nl> + if ( items = = 0 ) <nl> { <nl> size_t l = geohashEncodeImpl ( args . longitude_min , args . latitude_min , args . precision , out ) ; <nl> out + = l ; <nl> mmm a / dbms / src / Functions / array / arrayEnumerateRanked . h <nl> ppp b / dbms / src / Functions / array / arrayEnumerateRanked . h <nl> void FunctionArrayEnumerateRankedExtended < Derived > : : executeMethodImpl ( <nl> / / / Skipping offsets if no data in this array <nl> if ( prev_off = = off ) <nl> { <nl> - want_clear = true ; <nl> + <nl> + if ( depth_to_look > 2 ) <nl> + want_clear = true ; <nl> <nl> if ( depth_to_look > = 2 ) <nl> { <nl> mmm a / dbms / src / Functions / registerFunctionsIntrospection . cpp <nl> ppp b / dbms / src / Functions / registerFunctionsIntrospection . cpp <nl> class FunctionFactory ; <nl> void registerFunctionAddressToSymbol ( FunctionFactory & factory ) ; <nl> void registerFunctionDemangle ( FunctionFactory & factory ) ; <nl> void registerFunctionAddressToLine ( FunctionFactory & factory ) ; <nl> + void registerFunctionTrap ( FunctionFactory & factory ) ; <nl> <nl> void registerFunctionsIntrospection ( FunctionFactory & factory ) <nl> { <nl> registerFunctionAddressToSymbol ( factory ) ; <nl> registerFunctionDemangle ( factory ) ; <nl> registerFunctionAddressToLine ( factory ) ; <nl> + registerFunctionTrap ( factory ) ; <nl> } <nl> <nl> } <nl> new file mode 100644 <nl> index 00000000000 . . e05d5efa4f7 <nl> mmm / dev / null <nl> ppp b / dbms / src / Functions / trap . cpp <nl> <nl> + # if 0 <nl> + <nl> + # include < Functions / IFunction . h > <nl> + # include < Functions / FunctionFactory . h > <nl> + # include < Functions / FunctionHelpers . h > <nl> + # include < DataTypes / DataTypeString . h > <nl> + # include < DataTypes / DataTypesNumber . h > <nl> + # include < Columns / ColumnString . h > <nl> + <nl> + # include < thread > <nl> + # include < memory > <nl> + # include < cstdlib > <nl> + # include < unistd . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int ILLEGAL_COLUMN ; <nl> + extern const int ILLEGAL_TYPE_OF_ARGUMENT ; <nl> + extern const int BAD_ARGUMENTS ; <nl> + } <nl> + <nl> + <nl> + / / / Various illegal actions to test diagnostic features of ClickHouse itself . Should not be enabled in production builds . <nl> + class FunctionTrap : public IFunction <nl> + { <nl> + public : <nl> + static constexpr auto name = " trap " ; <nl> + static FunctionPtr create ( const Context & ) <nl> + { <nl> + return std : : make_shared < FunctionTrap > ( ) ; <nl> + } <nl> + <nl> + String getName ( ) const override <nl> + { <nl> + return name ; <nl> + } <nl> + <nl> + size_t getNumberOfArguments ( ) const override <nl> + { <nl> + return 1 ; <nl> + } <nl> + <nl> + DataTypePtr getReturnTypeImpl ( const DataTypes & arguments ) const override <nl> + { <nl> + if ( ! isString ( arguments [ 0 ] ) ) <nl> + throw Exception ( " The only argument for function " + getName ( ) + " must be constant String " , ErrorCodes : : ILLEGAL_TYPE_OF_ARGUMENT ) ; <nl> + <nl> + return std : : make_shared < DataTypeUInt8 > ( ) ; <nl> + } <nl> + <nl> + void executeImpl ( Block & block , const ColumnNumbers & arguments , size_t result , size_t input_rows_count ) override <nl> + { <nl> + if ( const ColumnConst * column = checkAndGetColumnConst < ColumnString > ( block . getByPosition ( arguments [ 0 ] ) . column . get ( ) ) ) <nl> + { <nl> + String mode = column - > getValue < String > ( ) ; <nl> + <nl> + if ( mode = = " read nullptr c + + " ) <nl> + { <nl> + volatile int x = * reinterpret_cast < const volatile int * > ( 0 ) ; <nl> + ( void ) x ; <nl> + } <nl> + else if ( mode = = " read nullptr asm " ) <nl> + { <nl> + __asm__ volatile ( " movq $ 0 , % rax " ) ; <nl> + __asm__ volatile ( " movq ( % rax ) , % rax " ) ; <nl> + } <nl> + else if ( mode = = " illegal instruction " ) <nl> + { <nl> + __asm__ volatile ( " ud2a " ) ; <nl> + } <nl> + else if ( mode = = " abort " ) <nl> + { <nl> + abort ( ) ; <nl> + } <nl> + else if ( mode = = " use after free " ) <nl> + { <nl> + int * x_ptr ; <nl> + { <nl> + auto x = std : : make_unique < int > ( ) ; <nl> + x_ptr = x . get ( ) ; <nl> + } <nl> + * x_ptr = 1 ; <nl> + ( void ) x_ptr ; <nl> + } <nl> + else if ( mode = = " use after scope " ) <nl> + { <nl> + volatile int * x_ptr ; <nl> + [ & ] { <nl> + volatile int x = 0 ; <nl> + x_ptr = & x ; <nl> + ( void ) x ; <nl> + } ( ) ; <nl> + [ & ] { <nl> + volatile int y = 1 ; <nl> + * x_ptr = 2 ; <nl> + ( void ) y ; <nl> + } ( ) ; <nl> + ( void ) x_ptr ; <nl> + } <nl> + else if ( mode = = " uninitialized memory " ) <nl> + { <nl> + int x ; <nl> + ( void ) write ( 2 , & x , sizeof ( x ) ) ; <nl> + } <nl> + else if ( mode = = " data race " ) <nl> + { <nl> + int x = 0 ; <nl> + std : : thread t1 ( [ & ] { + + x ; } ) ; <nl> + std : : thread t2 ( [ & ] { + + x ; } ) ; <nl> + t1 . join ( ) ; <nl> + t2 . join ( ) ; <nl> + } <nl> + else <nl> + throw Exception ( " Unknown trap mode " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> + } <nl> + else <nl> + throw Exception ( " The only argument for function " + getName ( ) + " must be constant String " , ErrorCodes : : ILLEGAL_COLUMN ) ; <nl> + <nl> + block . getByPosition ( result ) . column = block . getByPosition ( result ) . type - > createColumnConst ( input_rows_count , 0ULL ) ; <nl> + } <nl> + } ; <nl> + <nl> + <nl> + void registerFunctionTrap ( FunctionFactory & factory ) <nl> + { <nl> + factory . registerFunction < FunctionTrap > ( ) ; <nl> + } <nl> + <nl> + } <nl> + <nl> + # else <nl> + <nl> + namespace DB <nl> + { <nl> + class FunctionFactory ; <nl> + void registerFunctionTrap ( FunctionFactory & ) { } <nl> + } <nl> + <nl> + # endif <nl> new file mode 100644 <nl> index 00000000000 . . 07c815931b3 <nl> mmm / dev / null <nl> ppp b / dbms / src / IO / PeekableReadBuffer . cpp <nl> <nl> + # include < IO / PeekableReadBuffer . h > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + PeekableReadBuffer : : PeekableReadBuffer ( ReadBuffer & sub_buf_ , size_t start_size_ / * = DBMS_DEFAULT_BUFFER_SIZE * / , <nl> + size_t unread_limit_ / * = default_limit * / ) <nl> + : BufferWithOwnMemory ( start_size_ ) , sub_buf ( sub_buf_ ) , unread_limit ( unread_limit_ ) <nl> + { <nl> + padded & = sub_buf . isPadded ( ) ; <nl> + / / / Read from sub - buffer <nl> + Buffer & sub_working = sub_buf . buffer ( ) ; <nl> + BufferBase : : set ( sub_working . begin ( ) , sub_working . size ( ) , sub_buf . offset ( ) ) ; <nl> + <nl> + checkStateCorrect ( ) ; <nl> + } <nl> + <nl> + bool PeekableReadBuffer : : peekNext ( ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + <nl> + size_t bytes_read = 0 ; <nl> + Position copy_from = pos ; <nl> + size_t bytes_to_copy = sub_buf . available ( ) ; <nl> + if ( useSubbufferOnly ( ) ) <nl> + { <nl> + / / / Don ' t have to copy all data from sub - buffer if there is no data in own memory ( checkpoint and pos are in sub - buffer ) <nl> + if ( checkpoint ) <nl> + copy_from = checkpoint ; <nl> + bytes_read = copy_from - sub_buf . buffer ( ) . begin ( ) ; <nl> + bytes_to_copy = sub_buf . buffer ( ) . end ( ) - copy_from ; / / / sub_buf . available ( ) ; <nl> + if ( ! bytes_to_copy ) <nl> + { <nl> + bytes + = bytes_read ; <nl> + sub_buf . position ( ) = copy_from ; <nl> + <nl> + / / / Both checkpoint and pos are at the end of sub - buffer . Just load next part of data . <nl> + bool res = sub_buf . next ( ) ; <nl> + BufferBase : : set ( sub_buf . buffer ( ) . begin ( ) , sub_buf . buffer ( ) . size ( ) , sub_buf . offset ( ) ) ; <nl> + if ( checkpoint ) <nl> + checkpoint = pos ; <nl> + <nl> + checkStateCorrect ( ) ; <nl> + return res ; <nl> + } <nl> + } <nl> + <nl> + / / / May throw an exception <nl> + resizeOwnMemoryIfNecessary ( bytes_to_copy ) ; <nl> + <nl> + if ( useSubbufferOnly ( ) ) <nl> + { <nl> + bytes + = bytes_read ; <nl> + sub_buf . position ( ) = copy_from ; <nl> + } <nl> + <nl> + / / / Save unread data from sub - buffer to own memory <nl> + memcpy ( memory . data ( ) + peeked_size , sub_buf . position ( ) , bytes_to_copy ) ; <nl> + <nl> + / / / If useSubbufferOnly ( ) is false , then checkpoint is in own memory and it was updated in resizeOwnMemoryIfNecessary <nl> + / / / Otherwise , checkpoint now at the beginning of own memory <nl> + if ( checkpoint & & useSubbufferOnly ( ) ) <nl> + { <nl> + checkpoint = memory . data ( ) ; <nl> + checkpoint_in_own_memory = true ; <nl> + } <nl> + if ( currentlyReadFromOwnMemory ( ) ) <nl> + { <nl> + / / / Update buffer size <nl> + BufferBase : : set ( memory . data ( ) , peeked_size + bytes_to_copy , offset ( ) ) ; <nl> + } <nl> + else <nl> + { <nl> + / / / Switch to reading from own memory <nl> + size_t pos_offset = peeked_size + this - > offset ( ) ; <nl> + if ( useSubbufferOnly ( ) ) <nl> + { <nl> + if ( checkpoint ) <nl> + pos_offset = bytes_to_copy ; <nl> + else <nl> + pos_offset = 0 ; <nl> + } <nl> + BufferBase : : set ( memory . data ( ) , peeked_size + bytes_to_copy , pos_offset ) ; <nl> + <nl> + } <nl> + <nl> + peeked_size + = bytes_to_copy ; <nl> + sub_buf . position ( ) + = bytes_to_copy ; <nl> + <nl> + checkStateCorrect ( ) ; <nl> + return sub_buf . next ( ) ; <nl> + } <nl> + <nl> + void PeekableReadBuffer : : setCheckpoint ( ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + # ifndef NDEBUG <nl> + if ( checkpoint ) <nl> + throw DB : : Exception ( " Does not support recursive checkpoints . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + # endif <nl> + checkpoint_in_own_memory = currentlyReadFromOwnMemory ( ) ; <nl> + if ( ! checkpoint_in_own_memory ) <nl> + { <nl> + / / / Don ' t need to store unread data anymore <nl> + peeked_size = 0 ; <nl> + } <nl> + checkpoint = pos ; <nl> + checkStateCorrect ( ) ; <nl> + } <nl> + <nl> + void PeekableReadBuffer : : dropCheckpoint ( ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + # ifndef NDEBUG <nl> + if ( ! checkpoint ) <nl> + throw DB : : Exception ( " There is no checkpoint " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + # endif <nl> + if ( ! currentlyReadFromOwnMemory ( ) ) <nl> + { <nl> + / / / Don ' t need to store unread data anymore <nl> + peeked_size = 0 ; <nl> + } <nl> + checkpoint = nullptr ; <nl> + checkpoint_in_own_memory = false ; <nl> + checkStateCorrect ( ) ; <nl> + } <nl> + <nl> + void PeekableReadBuffer : : rollbackToCheckpoint ( ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + if ( ! checkpoint ) <nl> + throw DB : : Exception ( " There is no checkpoint " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + else if ( checkpointInOwnMemory ( ) = = currentlyReadFromOwnMemory ( ) ) <nl> + pos = checkpoint ; <nl> + else / / / Checkpoint is in own memory and pos is not . Switch to reading from own memory <nl> + BufferBase : : set ( memory . data ( ) , peeked_size , checkpoint - memory . data ( ) ) ; <nl> + checkStateCorrect ( ) ; <nl> + } <nl> + <nl> + bool PeekableReadBuffer : : nextImpl ( ) <nl> + { <nl> + / / / FIXME wrong bytes count because it can read the same data again after rollbackToCheckpoint ( ) <nl> + / / / However , changing bytes count on every call of next ( ) ( even after rollback ) allows to determine if some pointers were invalidated . <nl> + checkStateCorrect ( ) ; <nl> + bool res ; <nl> + <nl> + if ( ! checkpoint ) <nl> + { <nl> + if ( ! useSubbufferOnly ( ) ) <nl> + { <nl> + / / / All copied data have been read from own memory , continue reading from sub_buf <nl> + peeked_size = 0 ; <nl> + res = sub_buf . hasPendingData ( ) | | sub_buf . next ( ) ; <nl> + } <nl> + else <nl> + { <nl> + / / / Load next data to sub_buf <nl> + sub_buf . position ( ) = pos ; <nl> + res = sub_buf . next ( ) ; <nl> + } <nl> + <nl> + Buffer & sub_working = sub_buf . buffer ( ) ; <nl> + / / / Switch to reading from sub_buf ( or just update it if already switched ) <nl> + BufferBase : : set ( sub_working . begin ( ) , sub_working . size ( ) , 0 ) ; <nl> + } <nl> + else <nl> + { <nl> + if ( currentlyReadFromOwnMemory ( ) ) <nl> + res = sub_buf . hasPendingData ( ) | | sub_buf . next ( ) ; <nl> + else <nl> + res = peekNext ( ) ; <nl> + Buffer & sub_working = sub_buf . buffer ( ) ; <nl> + BufferBase : : set ( sub_working . begin ( ) , sub_working . size ( ) , 0 ) ; <nl> + } <nl> + <nl> + checkStateCorrect ( ) ; <nl> + return res ; <nl> + } <nl> + <nl> + bool PeekableReadBuffer : : useSubbufferOnly ( ) const <nl> + { <nl> + return ! peeked_size ; <nl> + } <nl> + <nl> + void PeekableReadBuffer : : checkStateCorrect ( ) const <nl> + { <nl> + # ifndef NDEBUG <nl> + if ( checkpoint ) <nl> + { <nl> + if ( checkpointInOwnMemory ( ) ) <nl> + { <nl> + if ( ! peeked_size ) <nl> + throw DB : : Exception ( " Checkpoint in empty own buffer " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + if ( currentlyReadFromOwnMemory ( ) & & pos < checkpoint ) <nl> + throw DB : : Exception ( " Current position in own buffer before checkpoint in own buffer " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + } <nl> + else <nl> + { <nl> + if ( peeked_size ) <nl> + throw DB : : Exception ( " Own buffer is not empty " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + if ( currentlyReadFromOwnMemory ( ) ) <nl> + throw DB : : Exception ( " Current position in own buffer before checkpoint in subbuffer " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + if ( pos < checkpoint ) <nl> + throw DB : : Exception ( " Current position in subbuffer before checkpoint in subbuffer " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + } <nl> + } <nl> + else <nl> + { <nl> + if ( ! currentlyReadFromOwnMemory ( ) & & peeked_size ) <nl> + throw DB : : Exception ( " Own buffer is not empty " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + } <nl> + if ( currentlyReadFromOwnMemory ( ) & & ! peeked_size ) <nl> + throw DB : : Exception ( " Pos in empty own buffer " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + if ( unread_limit < memory . size ( ) ) <nl> + throw DB : : Exception ( " Size limit exceed " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + # endif <nl> + } <nl> + <nl> + size_t PeekableReadBuffer : : resizeOwnMemoryIfNecessary ( size_t bytes_to_append ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + bool needUpdateCheckpoint = checkpointInOwnMemory ( ) ; <nl> + bool needUpdatePos = currentlyReadFromOwnMemory ( ) ; <nl> + size_t offset = 0 ; <nl> + if ( needUpdateCheckpoint ) <nl> + offset = checkpoint - memory . data ( ) ; <nl> + else if ( needUpdatePos ) <nl> + offset = this - > offset ( ) ; <nl> + <nl> + size_t new_size = peeked_size + bytes_to_append ; <nl> + if ( memory . size ( ) < new_size ) <nl> + { <nl> + if ( bytes_to_append < offset & & 2 * ( peeked_size - offset ) < = memory . size ( ) ) <nl> + { <nl> + / / / Move unread data to the beginning of own memory instead of resize own memory <nl> + peeked_size - = offset ; <nl> + memmove ( memory . data ( ) , memory . data ( ) + offset , peeked_size ) ; <nl> + bytes + = offset ; <nl> + <nl> + if ( needUpdateCheckpoint ) <nl> + checkpoint - = offset ; <nl> + if ( needUpdatePos ) <nl> + pos - = offset ; <nl> + <nl> + checkStateCorrect ( ) ; <nl> + return 0 ; <nl> + } <nl> + else <nl> + { <nl> + if ( unread_limit < new_size ) <nl> + throw DB : : Exception ( " PeekableReadBuffer : Memory limit exceed " , ErrorCodes : : MEMORY_LIMIT_EXCEEDED ) ; <nl> + <nl> + size_t pos_offset = pos - memory . data ( ) ; <nl> + <nl> + size_t new_size_amortized = memory . size ( ) * 2 ; <nl> + if ( new_size_amortized < new_size ) <nl> + new_size_amortized = new_size ; <nl> + else if ( unread_limit < new_size_amortized ) <nl> + new_size_amortized = unread_limit ; <nl> + memory . resize ( new_size_amortized ) ; <nl> + <nl> + if ( needUpdateCheckpoint ) <nl> + checkpoint = memory . data ( ) + offset ; <nl> + if ( needUpdatePos ) <nl> + { <nl> + BufferBase : : set ( memory . data ( ) , peeked_size , pos_offset ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + checkStateCorrect ( ) ; <nl> + return offset ; <nl> + } <nl> + <nl> + PeekableReadBuffer : : ~ PeekableReadBuffer ( ) <nl> + { <nl> + if ( ! currentlyReadFromOwnMemory ( ) ) <nl> + sub_buf . position ( ) = pos ; <nl> + } <nl> + <nl> + std : : shared_ptr < BufferWithOwnMemory < ReadBuffer > > PeekableReadBuffer : : takeUnreadData ( ) <nl> + { <nl> + checkStateCorrect ( ) ; <nl> + if ( ! currentlyReadFromOwnMemory ( ) ) <nl> + return std : : make_shared < BufferWithOwnMemory < ReadBuffer > > ( 0 ) ; <nl> + size_t unread_size = memory . data ( ) + peeked_size - pos ; <nl> + auto unread = std : : make_shared < BufferWithOwnMemory < ReadBuffer > > ( unread_size ) ; <nl> + memcpy ( unread - > buffer ( ) . begin ( ) , pos , unread_size ) ; <nl> + unread - > BufferBase : : set ( unread - > buffer ( ) . begin ( ) , unread_size , 0 ) ; <nl> + peeked_size = 0 ; <nl> + checkpoint = nullptr ; <nl> + checkpoint_in_own_memory = false ; <nl> + BufferBase : : set ( sub_buf . buffer ( ) . begin ( ) , sub_buf . buffer ( ) . size ( ) , sub_buf . offset ( ) ) ; <nl> + checkStateCorrect ( ) ; <nl> + return unread ; <nl> + } <nl> + <nl> + bool PeekableReadBuffer : : currentlyReadFromOwnMemory ( ) const <nl> + { <nl> + return working_buffer . begin ( ) ! = sub_buf . buffer ( ) . begin ( ) ; <nl> + } <nl> + <nl> + bool PeekableReadBuffer : : checkpointInOwnMemory ( ) const <nl> + { <nl> + return checkpoint_in_own_memory ; <nl> + } <nl> + <nl> + void PeekableReadBuffer : : assertCanBeDestructed ( ) const <nl> + { <nl> + if ( peeked_size & & pos ! = memory . data ( ) + peeked_size ) <nl> + throw DB : : Exception ( " There are data , which were extracted from sub - buffer , but not from peekable buffer . " <nl> + " Cannot destruct peekable buffer correctly because tha data will be lost . " <nl> + " Most likely it ' s a bug . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + } <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 30a38b69e5c <nl> mmm / dev / null <nl> ppp b / dbms / src / IO / PeekableReadBuffer . h <nl> <nl> + # pragma once <nl> + # include < IO / ReadBuffer . h > <nl> + # include < IO / BufferWithOwnMemory . h > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int MEMORY_LIMIT_EXCEEDED ; <nl> + extern const int LOGICAL_ERROR ; <nl> + } <nl> + <nl> + / / / Allows to peek next part of data from sub - buffer without extracting it . <nl> + / / / Also allows to set checkpoint at some position in stream and come back to this position later , <nl> + / / / even if next ( ) was called . <nl> + / / / Sub - buffer should not be accessed directly during the lifelime of peekable buffer . <nl> + / / / If position ( ) of peekable buffer is explicitly set to some position before checkpoint <nl> + / / / ( e . g . by istr . position ( ) = prev_pos ) , behavior is undefined . <nl> + class PeekableReadBuffer : public BufferWithOwnMemory < ReadBuffer > <nl> + { <nl> + friend class PeekableReadBufferCheckpoint ; <nl> + public : <nl> + explicit PeekableReadBuffer ( ReadBuffer & sub_buf_ , size_t start_size_ = DBMS_DEFAULT_BUFFER_SIZE , <nl> + size_t unread_limit_ = 16 * DBMS_DEFAULT_BUFFER_SIZE ) ; <nl> + <nl> + / / / Use takeUnreadData ( ) to extract unread data before destruct object <nl> + ~ PeekableReadBuffer ( ) override ; <nl> + <nl> + / / / Saves unread data to own memory , so it will be possible to read it later . Loads next data to sub - buffer . <nl> + / / / Doesn ' t change checkpoint and position in stream , <nl> + / / / but all pointers ( such as this - > buffer ( ) . end ( ) and this - > position ( ) ) may be invalidated <nl> + / / / @ returns false in case of EOF in sub - buffer , otherwise returns true <nl> + bool peekNext ( ) ; <nl> + <nl> + Buffer & lastPeeked ( ) { return sub_buf . buffer ( ) ; } <nl> + <nl> + / / / Sets checkpoint at current position <nl> + void setCheckpoint ( ) ; <nl> + <nl> + / / / Forget checkpoint and all data between checkpoint and position <nl> + void dropCheckpoint ( ) ; <nl> + <nl> + / / / Sets position at checkpoint . <nl> + / / / All pointers ( such as this - > buffer ( ) . end ( ) ) may be invalidated <nl> + void rollbackToCheckpoint ( ) ; <nl> + <nl> + / / / If position is in own memory , returns buffer with data , which were extracted from sub - buffer , <nl> + / / / but not from this buffer , so the data will not be lost after destruction of this buffer . <nl> + / / / If position is in sub - buffer , returns empty buffer . <nl> + std : : shared_ptr < BufferWithOwnMemory < ReadBuffer > > takeUnreadData ( ) ; <nl> + void assertCanBeDestructed ( ) const ; <nl> + <nl> + private : <nl> + <nl> + bool nextImpl ( ) override ; <nl> + <nl> + inline bool useSubbufferOnly ( ) const ; <nl> + inline bool currentlyReadFromOwnMemory ( ) const ; <nl> + inline bool checkpointInOwnMemory ( ) const ; <nl> + <nl> + void checkStateCorrect ( ) const ; <nl> + <nl> + / / / Makes possible to append ` bytes_to_append ` bytes to data in own memory . <nl> + / / / Updates all invalidated pointers and sizes . <nl> + / / / @ returns new offset of unread data in own memory <nl> + size_t resizeOwnMemoryIfNecessary ( size_t bytes_to_append ) ; <nl> + <nl> + <nl> + ReadBuffer & sub_buf ; <nl> + const size_t unread_limit ; <nl> + size_t peeked_size = 0 ; <nl> + Position checkpoint = nullptr ; <nl> + bool checkpoint_in_own_memory = false ; <nl> + } ; <nl> + <nl> + <nl> + class PeekableReadBufferCheckpoint : boost : : noncopyable <nl> + { <nl> + PeekableReadBuffer & buf ; <nl> + bool auto_rollback ; <nl> + public : <nl> + explicit PeekableReadBufferCheckpoint ( PeekableReadBuffer & buf_ , bool auto_rollback_ = false ) <nl> + : buf ( buf_ ) , auto_rollback ( auto_rollback_ ) { buf . setCheckpoint ( ) ; } <nl> + ~ PeekableReadBufferCheckpoint ( ) <nl> + { <nl> + if ( ! buf . checkpoint ) <nl> + return ; <nl> + if ( auto_rollback ) <nl> + buf . rollbackToCheckpoint ( ) ; <nl> + buf . dropCheckpoint ( ) ; <nl> + } <nl> + <nl> + } ; <nl> + <nl> + } <nl> mmm a / dbms / src / IO / UncompressedCache . h <nl> ppp b / dbms / src / IO / UncompressedCache . h <nl> <nl> # include < Common / ProfileEvents . h > <nl> # include < IO / BufferWithOwnMemory . h > <nl> <nl> - # include < Common / config . h > <nl> - # if USE_MIMALLOC <nl> - # include < Common / MiAllocator . h > <nl> - # endif <nl> - <nl> <nl> namespace ProfileEvents <nl> { <nl> namespace DB <nl> <nl> struct UncompressedCacheCell <nl> { <nl> - # if USE_MIMALLOC <nl> - Memory < MiAllocator > data ; <nl> - # else <nl> Memory < > data ; <nl> - # endif <nl> size_t compressed_size ; <nl> UInt32 additional_bytes ; <nl> } ; <nl> mmm a / dbms / src / IO / createReadBufferFromFileBase . cpp <nl> ppp b / dbms / src / IO / createReadBufferFromFileBase . cpp <nl> namespace ProfileEvents <nl> { <nl> extern const Event CreatedReadBufferOrdinary ; <nl> extern const Event CreatedReadBufferAIO ; <nl> + extern const Event CreatedReadBufferAIOFailed ; <nl> } <nl> <nl> namespace DB <nl> { <nl> - # if ! defined ( __linux__ ) <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int NOT_IMPLEMENTED ; <nl> - } <nl> - # endif <nl> <nl> std : : unique_ptr < ReadBufferFromFileBase > createReadBufferFromFileBase ( const std : : string & filename_ , size_t estimated_size , <nl> size_t aio_threshold , size_t buffer_size_ , int flags_ , char * existing_memory_ , size_t alignment ) <nl> { <nl> - if ( ( aio_threshold = = 0 ) | | ( estimated_size < aio_threshold ) ) <nl> + # if defined ( __linux__ ) | | defined ( __FreeBSD__ ) <nl> + if ( aio_threshold & & estimated_size > = aio_threshold ) <nl> { <nl> - ProfileEvents : : increment ( ProfileEvents : : CreatedReadBufferOrdinary ) ; <nl> - return std : : make_unique < ReadBufferFromFile > ( filename_ , buffer_size_ , flags_ , existing_memory_ , alignment ) ; <nl> + / / / Attempt to open a file with O_DIRECT <nl> + try <nl> + { <nl> + auto res = std : : make_unique < ReadBufferAIO > ( filename_ , buffer_size_ , flags_ , existing_memory_ ) ; <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedReadBufferAIO ) ; <nl> + return res ; <nl> + } <nl> + catch ( const ErrnoException & ) <nl> + { <nl> + / / / Fallback to cached IO if O_DIRECT is not supported . <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedReadBufferAIOFailed ) ; <nl> + } <nl> } <nl> - else <nl> - { <nl> - # if defined ( __linux__ ) | | defined ( __FreeBSD__ ) <nl> - ProfileEvents : : increment ( ProfileEvents : : CreatedReadBufferAIO ) ; <nl> - return std : : make_unique < ReadBufferAIO > ( filename_ , buffer_size_ , flags_ , existing_memory_ ) ; <nl> # else <nl> - throw Exception ( " AIO is implemented only on Linux and FreeBSD " , ErrorCodes : : NOT_IMPLEMENTED ) ; <nl> + ( void ) aio_threshold ; <nl> + ( void ) estimated_size ; <nl> # endif <nl> - } <nl> + <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedReadBufferOrdinary ) ; <nl> + return std : : make_unique < ReadBufferFromFile > ( filename_ , buffer_size_ , flags_ , existing_memory_ , alignment ) ; <nl> } <nl> <nl> } <nl> mmm a / dbms / src / IO / createWriteBufferFromFileBase . cpp <nl> ppp b / dbms / src / IO / createWriteBufferFromFileBase . cpp <nl> namespace ProfileEvents <nl> { <nl> extern const Event CreatedWriteBufferOrdinary ; <nl> extern const Event CreatedWriteBufferAIO ; <nl> + extern const Event CreatedWriteBufferAIOFailed ; <nl> } <nl> <nl> namespace DB <nl> { <nl> <nl> - # if ! defined ( __linux__ ) <nl> - namespace ErrorCodes <nl> - { <nl> - extern const int NOT_IMPLEMENTED ; <nl> - } <nl> - # endif <nl> - <nl> std : : unique_ptr < WriteBufferFromFileBase > createWriteBufferFromFileBase ( const std : : string & filename_ , size_t estimated_size , <nl> size_t aio_threshold , size_t buffer_size_ , int flags_ , mode_t mode , char * existing_memory_ , <nl> size_t alignment ) <nl> { <nl> - if ( ( aio_threshold = = 0 ) | | ( estimated_size < aio_threshold ) ) <nl> + # if defined ( __linux__ ) | | defined ( __FreeBSD__ ) <nl> + if ( aio_threshold & & estimated_size > = aio_threshold ) <nl> { <nl> - ProfileEvents : : increment ( ProfileEvents : : CreatedWriteBufferOrdinary ) ; <nl> - return std : : make_unique < WriteBufferFromFile > ( filename_ , buffer_size_ , flags_ , mode , existing_memory_ , alignment ) ; <nl> + / / / Attempt to open a file with O_DIRECT <nl> + try <nl> + { <nl> + auto res = std : : make_unique < WriteBufferAIO > ( filename_ , buffer_size_ , flags_ , mode , existing_memory_ ) ; <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedWriteBufferAIO ) ; <nl> + return res ; <nl> + } <nl> + catch ( const ErrnoException & ) <nl> + { <nl> + / / / Fallback to cached IO if O_DIRECT is not supported . <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedWriteBufferAIOFailed ) ; <nl> + } <nl> } <nl> - else <nl> - { <nl> - # if defined ( __linux__ ) | | defined ( __FreeBSD__ ) <nl> - ProfileEvents : : increment ( ProfileEvents : : CreatedWriteBufferAIO ) ; <nl> - return std : : make_unique < WriteBufferAIO > ( filename_ , buffer_size_ , flags_ , mode , existing_memory_ ) ; <nl> # else <nl> - throw Exception ( " AIO is implemented only on Linux and FreeBSD " , ErrorCodes : : NOT_IMPLEMENTED ) ; <nl> + ( void ) aio_threshold ; <nl> + ( void ) estimated_size ; <nl> # endif <nl> - } <nl> + <nl> + ProfileEvents : : increment ( ProfileEvents : : CreatedWriteBufferOrdinary ) ; <nl> + return std : : make_unique < WriteBufferFromFile > ( filename_ , buffer_size_ , flags_ , mode , existing_memory_ , alignment ) ; <nl> } <nl> <nl> } <nl> new file mode 100644 <nl> index 00000000000 . . 331184e701c <nl> mmm / dev / null <nl> ppp b / dbms / src / IO / tests / gtest_peekable_read_buffer . cpp <nl> <nl> + # include < gtest / gtest . h > <nl> + <nl> + # include < Core / Types . h > <nl> + # include < IO / ReadHelpers . h > <nl> + # include < IO / ReadBufferFromString . h > <nl> + # include < IO / ConcatReadBuffer . h > <nl> + # include < IO / PeekableReadBuffer . h > <nl> + <nl> + void readAndAssert ( DB : : ReadBuffer & buf , const char * str ) <nl> + { <nl> + size_t n = strlen ( str ) ; <nl> + char tmp [ n ] ; <nl> + buf . readStrict ( tmp , n ) ; <nl> + ASSERT_EQ ( strncmp ( tmp , str , n ) , 0 ) ; <nl> + } <nl> + <nl> + void assertAvailable ( DB : : ReadBuffer & buf , const char * str ) <nl> + { <nl> + size_t n = strlen ( str ) ; <nl> + ASSERT_EQ ( buf . available ( ) , n ) ; <nl> + ASSERT_EQ ( strncmp ( buf . position ( ) , str , n ) , 0 ) ; <nl> + } <nl> + <nl> + TEST ( PeekableReadBuffer , CheckpointsWorkCorrectly ) <nl> + try <nl> + { <nl> + std : : string s1 = " 0123456789 " ; <nl> + std : : string s2 = " qwertyuiop " ; <nl> + std : : string s3 = " asdfghjkl ; " ; <nl> + std : : string s4 = " zxcvbnm , . / " ; <nl> + DB : : ReadBufferFromString b1 ( s1 ) ; <nl> + DB : : ReadBufferFromString b2 ( s2 ) ; <nl> + DB : : ReadBufferFromString b3 ( s3 ) ; <nl> + DB : : ReadBufferFromString b4 ( s4 ) ; <nl> + <nl> + DB : : ConcatReadBuffer concat ( { & b1 , & b2 , & b3 , & b4 } ) ; <nl> + DB : : PeekableReadBuffer peekable ( concat , 0 , 16 ) ; <nl> + <nl> + ASSERT_TRUE ( ! peekable . eof ( ) ) ; <nl> + assertAvailable ( peekable , " 0123456789 " ) ; <nl> + { <nl> + DB : : PeekableReadBufferCheckpoint checkpoint { peekable } ; <nl> + readAndAssert ( peekable , " 01234 " ) ; <nl> + } <nl> + bool exception = false ; <nl> + try <nl> + { <nl> + peekable . rollbackToCheckpoint ( ) ; <nl> + } <nl> + catch ( DB : : Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = DB : : ErrorCodes : : LOGICAL_ERROR ) <nl> + throw ; <nl> + exception = true ; <nl> + } <nl> + ASSERT_TRUE ( exception ) ; <nl> + assertAvailable ( peekable , " 56789 " ) ; <nl> + <nl> + readAndAssert ( peekable , " 56 " ) ; <nl> + <nl> + peekable . setCheckpoint ( ) ; <nl> + readAndAssert ( peekable , " 789qwertyu " ) ; <nl> + peekable . rollbackToCheckpoint ( ) ; <nl> + peekable . dropCheckpoint ( ) ; <nl> + assertAvailable ( peekable , " 789 " ) ; <nl> + peekable . peekNext ( ) ; <nl> + assertAvailable ( peekable , " 789qwertyuiop " ) ; <nl> + ASSERT_EQ ( peekable . lastPeeked ( ) . size ( ) , 10 ) ; <nl> + ASSERT_EQ ( strncmp ( peekable . lastPeeked ( ) . begin ( ) , " asdfghjkl ; " , 10 ) , 0 ) ; <nl> + <nl> + exception = false ; <nl> + try <nl> + { <nl> + DB : : PeekableReadBufferCheckpoint checkpoint { peekable , true } ; <nl> + peekable . ignore ( 30 ) ; <nl> + } <nl> + catch ( DB : : Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = DB : : ErrorCodes : : MEMORY_LIMIT_EXCEEDED ) <nl> + throw ; <nl> + exception = true ; <nl> + } <nl> + ASSERT_TRUE ( exception ) ; <nl> + assertAvailable ( peekable , " 789qwertyuiop " ) ; <nl> + ASSERT_EQ ( peekable . lastPeeked ( ) . size ( ) , 10 ) ; <nl> + ASSERT_EQ ( strncmp ( peekable . lastPeeked ( ) . begin ( ) , " asdfghjkl ; " , 10 ) , 0 ) ; <nl> + <nl> + readAndAssert ( peekable , " 789qwertyu " ) ; <nl> + peekable . setCheckpoint ( ) ; <nl> + readAndAssert ( peekable , " iopasdfghj " ) ; <nl> + assertAvailable ( peekable , " kl ; " ) ; <nl> + peekable . dropCheckpoint ( ) ; <nl> + <nl> + peekable . setCheckpoint ( ) ; <nl> + readAndAssert ( peekable , " kl ; zxcvbnm , . / " ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + peekable . rollbackToCheckpoint ( ) ; <nl> + readAndAssert ( peekable , " kl ; zxcvbnm " ) ; <nl> + peekable . dropCheckpoint ( ) ; <nl> + <nl> + exception = false ; <nl> + try <nl> + { <nl> + peekable . assertCanBeDestructed ( ) ; <nl> + } <nl> + catch ( DB : : Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = DB : : ErrorCodes : : LOGICAL_ERROR ) <nl> + throw ; <nl> + exception = true ; <nl> + } <nl> + ASSERT_TRUE ( exception ) ; <nl> + <nl> + auto buf_ptr = peekable . takeUnreadData ( ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + ASSERT_TRUE ( peekable . eof ( ) ) ; <nl> + <nl> + readAndAssert ( * buf_ptr , " , . / " ) ; <nl> + ASSERT_TRUE ( buf_ptr - > eof ( ) ) ; <nl> + <nl> + peekable . assertCanBeDestructed ( ) ; <nl> + } <nl> + catch ( const DB : : Exception & e ) <nl> + { <nl> + std : : cerr < < e . what ( ) < < " , " < < e . displayText ( ) < < std : : endl ; <nl> + throw ; <nl> + } <nl> + <nl> mmm a / dbms / src / Interpreters / Context . cpp <nl> ppp b / dbms / src / Interpreters / Context . cpp <nl> void Context : : updateSettingsChanges ( const SettingsChanges & changes ) <nl> if ( change . name = = " profile " ) <nl> setProfile ( change . value . safeGet < String > ( ) ) ; <nl> else <nl> - settings . updateFromChange ( change ) ; <nl> + settings . applyChange ( change ) ; <nl> } <nl> } <nl> <nl> String Context : : getCurrentQueryId ( ) const <nl> } <nl> <nl> <nl> + String Context : : getInitialQueryId ( ) const <nl> + { <nl> + return client_info . initial_query_id ; <nl> + } <nl> + <nl> + <nl> void Context : : setCurrentDatabase ( const String & name ) <nl> { <nl> auto lock = getLock ( ) ; <nl> mmm a / dbms / src / Interpreters / Context . h <nl> ppp b / dbms / src / Interpreters / Context . h <nl> class Context <nl> <nl> String getCurrentDatabase ( ) const ; <nl> String getCurrentQueryId ( ) const ; <nl> + <nl> + / / / Id of initiating query for distributed queries ; or current query id if it ' s not a distributed query . <nl> + String getInitialQueryId ( ) const ; <nl> + <nl> void setCurrentDatabase ( const String & name ) ; <nl> void setCurrentQueryId ( const String & query_id ) ; <nl> <nl> mmm a / dbms / src / Interpreters / ExternalLoader . cpp <nl> ppp b / dbms / src / Interpreters / ExternalLoader . cpp <nl> <nl> # include " ExternalLoader . h " <nl> <nl> - # include < cmath > <nl> # include < mutex > <nl> # include < pcg_random . hpp > <nl> # include < common / DateLUT . h > <nl> class ExternalLoader : : LoadingDispatcher : private boost : : noncopyable <nl> class ExternalLoader : : PeriodicUpdater : private boost : : noncopyable <nl> { <nl> public : <nl> + static constexpr UInt64 check_period_sec = 5 ; <nl> + <nl> PeriodicUpdater ( ConfigFilesReader & config_files_reader_ , LoadingDispatcher & loading_dispatcher_ ) <nl> : config_files_reader ( config_files_reader_ ) , loading_dispatcher ( loading_dispatcher_ ) <nl> { <nl> class ExternalLoader : : PeriodicUpdater : private boost : : noncopyable <nl> <nl> ~ PeriodicUpdater ( ) { enable ( false ) ; } <nl> <nl> - void enable ( bool enable_ , const ExternalLoaderUpdateSettings & settings_ = { } ) <nl> + void enable ( bool enable_ ) <nl> { <nl> std : : unique_lock lock { mutex } ; <nl> enabled = enable_ ; <nl> - settings = settings_ ; <nl> <nl> if ( enable_ ) <nl> { <nl> class ExternalLoader : : PeriodicUpdater : private boost : : noncopyable <nl> return std : : chrono : : system_clock : : now ( ) + std : : chrono : : seconds { distribution ( rnd_engine ) } ; <nl> } <nl> <nl> - std : : uniform_int_distribution < UInt64 > distribution ( 0 , static_cast < UInt64 > ( std : : exp2 ( error_count - 1 ) ) ) ; <nl> - std : : chrono : : seconds delay ( std : : min < UInt64 > ( settings . backoff_max_sec , settings . backoff_initial_sec + distribution ( rnd_engine ) ) ) ; <nl> - return std : : chrono : : system_clock : : now ( ) + delay ; <nl> + return std : : chrono : : system_clock : : now ( ) + std : : chrono : : seconds ( ExternalLoadableBackoff { } . calculateDuration ( rnd_engine , error_count ) ) ; <nl> } <nl> <nl> private : <nl> class ExternalLoader : : PeriodicUpdater : private boost : : noncopyable <nl> setThreadName ( " ExterLdrReload " ) ; <nl> <nl> std : : unique_lock lock { mutex } ; <nl> - auto timeout = [ this ] { return std : : chrono : : seconds ( settings . check_period_sec ) ; } ; <nl> auto pred = [ this ] { return ! enabled ; } ; <nl> - while ( ! event . wait_for ( lock , timeout ( ) , pred ) ) <nl> + while ( ! event . wait_for ( lock , std : : chrono : : seconds ( check_period_sec ) , pred ) ) <nl> { <nl> lock . unlock ( ) ; <nl> loading_dispatcher . setConfiguration ( config_files_reader . read ( ) ) ; <nl> class ExternalLoader : : PeriodicUpdater : private boost : : noncopyable <nl> <nl> mutable std : : mutex mutex ; <nl> bool enabled = false ; <nl> - ExternalLoaderUpdateSettings settings ; <nl> ThreadFromGlobalPool thread ; <nl> std : : condition_variable event ; <nl> mutable pcg64 rnd_engine { randomSeed ( ) } ; <nl> void ExternalLoader : : enableAsyncLoading ( bool enable ) <nl> loading_dispatcher - > enableAsyncLoading ( enable ) ; <nl> } <nl> <nl> - void ExternalLoader : : enablePeriodicUpdates ( bool enable_ , const ExternalLoaderUpdateSettings & settings_ ) <nl> + void ExternalLoader : : enablePeriodicUpdates ( bool enable_ ) <nl> { <nl> - periodic_updater - > enable ( enable_ , settings_ ) ; <nl> + periodic_updater - > enable ( enable_ ) ; <nl> } <nl> <nl> bool ExternalLoader : : hasCurrentlyLoadedObjects ( ) const <nl> mmm a / dbms / src / Interpreters / ExternalLoader . h <nl> ppp b / dbms / src / Interpreters / ExternalLoader . h <nl> <nl> <nl> namespace DB <nl> { <nl> - struct ExternalLoaderUpdateSettings <nl> - { <nl> - UInt64 check_period_sec = 5 ; <nl> - UInt64 backoff_initial_sec = 5 ; <nl> - / / / 10 minutes <nl> - UInt64 backoff_max_sec = 10 * 60 ; <nl> - <nl> - ExternalLoaderUpdateSettings ( ) = default ; <nl> - ExternalLoaderUpdateSettings ( UInt64 check_period_sec_ , UInt64 backoff_initial_sec_ , UInt64 backoff_max_sec_ ) <nl> - : check_period_sec ( check_period_sec_ ) , backoff_initial_sec ( backoff_initial_sec_ ) , backoff_max_sec ( backoff_max_sec_ ) { } <nl> - } ; <nl> - <nl> - <nl> / * External configuration structure . <nl> * <nl> * < external_group > <nl> class ExternalLoader <nl> void enableAsyncLoading ( bool enable ) ; <nl> <nl> / / / Sets settings for periodic updates . <nl> - void enablePeriodicUpdates ( bool enable , const ExternalLoaderUpdateSettings & settings = { } ) ; <nl> + void enablePeriodicUpdates ( bool enable ) ; <nl> <nl> / / / Returns the status of the object . <nl> / / / If the object has not been loaded yet then the function returns Status : : NOT_LOADED . <nl> mmm a / dbms / src / Interpreters / IExternalLoadable . cpp <nl> ppp b / dbms / src / Interpreters / IExternalLoadable . cpp <nl> <nl> # include < Interpreters / IExternalLoadable . h > <nl> <nl> # include < Poco / Util / AbstractConfiguration . h > <nl> - <nl> + # include < cmath > <nl> <nl> namespace DB <nl> { <nl> ExternalLoadableLifetime : : ExternalLoadableLifetime ( const Poco : : Util : : AbstractCon <nl> max_sec = has_min ? config . getUInt64 ( config_prefix + " . max " ) : min_sec ; <nl> } <nl> <nl> + <nl> + UInt64 ExternalLoadableBackoff : : calculateDuration ( pcg64 & rnd_engine , size_t error_count ) const <nl> + { <nl> + if ( error_count < 1 ) <nl> + error_count = 1 ; <nl> + std : : uniform_int_distribution < UInt64 > distribution ( 0 , static_cast < UInt64 > ( std : : exp2 ( error_count - 1 ) ) ) ; <nl> + return std : : min < UInt64 > ( backoff_max_sec , backoff_initial_sec + distribution ( rnd_engine ) ) ; <nl> + } <nl> + <nl> } <nl> mmm a / dbms / src / Interpreters / IExternalLoadable . h <nl> ppp b / dbms / src / Interpreters / IExternalLoadable . h <nl> <nl> # include < string > <nl> # include < memory > <nl> # include < boost / noncopyable . hpp > <nl> + # include < pcg_random . hpp > <nl> # include < Core / Types . h > <nl> <nl> <nl> struct ExternalLoadableLifetime <nl> } ; <nl> <nl> <nl> + / / / Delay before trying to load again after error . <nl> + struct ExternalLoadableBackoff <nl> + { <nl> + UInt64 backoff_initial_sec = 5 ; <nl> + UInt64 backoff_max_sec = 10 * 60 ; / / / 10 minutes <nl> + <nl> + / / / Calculates time to try loading again after error . <nl> + UInt64 calculateDuration ( pcg64 & rnd_engine , size_t error_count = 1 ) const ; <nl> + } ; <nl> + <nl> + <nl> / / / Basic interface for external loadable objects . Is used in ExternalLoader . <nl> class IExternalLoadable : public std : : enable_shared_from_this < IExternalLoadable > , private boost : : noncopyable <nl> { <nl> mmm a / dbms / src / Interpreters / InterpreterDescribeQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterDescribeQuery . cpp <nl> BlockInputStreamPtr InterpreterDescribeQuery : : executeImpl ( ) <nl> table = context . getTable ( database_name , table_name ) ; <nl> } <nl> <nl> - auto table_lock = table - > lockStructureForShare ( false , context . getCurrentQueryId ( ) ) ; <nl> + auto table_lock = table - > lockStructureForShare ( false , context . getInitialQueryId ( ) ) ; <nl> columns = table - > getColumns ( ) ; <nl> } <nl> <nl> mmm a / dbms / src / Interpreters / InterpreterInsertQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterInsertQuery . cpp <nl> BlockIO InterpreterInsertQuery : : execute ( ) <nl> checkAccess ( query ) ; <nl> StoragePtr table = getTable ( query ) ; <nl> <nl> - auto table_lock = table - > lockStructureForShare ( true , context . getCurrentQueryId ( ) ) ; <nl> + auto table_lock = table - > lockStructureForShare ( true , context . getInitialQueryId ( ) ) ; <nl> <nl> / / / We create a pipeline of several streams , into which we will write data . <nl> BlockOutputStreamPtr out ; <nl> mmm a / dbms / src / Interpreters / InterpreterKillQueryQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterKillQueryQuery . cpp <nl> Block InterpreterKillQueryQuery : : getSelectResult ( const String & columns , const S <nl> if ( where_expression ) <nl> select_query + = " WHERE " + queryToString ( where_expression ) ; <nl> <nl> - auto use_processors = context . getSettingsRef ( ) . experimental_use_processors ; <nl> - context . getSettingsRef ( ) . experimental_use_processors = false ; <nl> - <nl> - SCOPE_EXIT ( context . getSettingsRef ( ) . experimental_use_processors = use_processors ) ; <nl> - <nl> BlockIO block_io = executeQuery ( select_query , context , true ) ; <nl> Block res = block_io . in - > read ( ) ; <nl> <nl> mmm a / dbms / src / Interpreters / InterpreterRenameQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterRenameQuery . cpp <nl> struct RenameDescription <nl> to_table_name ( elem . to . table ) <nl> { } <nl> <nl> - TableStructureWriteLockHolder from_table_lock ; <nl> - <nl> String from_database_name ; <nl> String from_table_name ; <nl> <nl> BlockIO InterpreterRenameQuery : : execute ( ) <nl> } <nl> } ; <nl> <nl> - std : : map < UniqueTableName , TableStructureWriteLockHolder > tables_from_locks ; <nl> - <nl> / / / Don ' t allow to drop tables ( that we are renaming ) ; don ' t allow to create tables in places where tables will be renamed . <nl> std : : map < UniqueTableName , std : : unique_ptr < DDLGuard > > table_guards ; <nl> <nl> BlockIO InterpreterRenameQuery : : execute ( ) <nl> UniqueTableName from ( descriptions . back ( ) . from_database_name , descriptions . back ( ) . from_table_name ) ; <nl> UniqueTableName to ( descriptions . back ( ) . to_database_name , descriptions . back ( ) . to_table_name ) ; <nl> <nl> - if ( ! tables_from_locks . count ( from ) ) <nl> - if ( auto table = context . tryGetTable ( from . database_name , from . table_name ) ) <nl> - tables_from_locks . emplace ( from , table - > lockExclusively ( context . getCurrentQueryId ( ) ) ) ; <nl> - <nl> - descriptions . back ( ) . from_table_lock = tables_from_locks [ from ] ; <nl> - <nl> - if ( ! table_guards . count ( from ) ) <nl> - table_guards . emplace ( from , context . getDDLGuard ( from . database_name , from . table_name ) ) ; <nl> - <nl> - if ( ! table_guards . count ( to ) ) <nl> - table_guards . emplace ( to , context . getDDLGuard ( to . database_name , to . table_name ) ) ; <nl> + table_guards [ from ] ; <nl> + table_guards [ to ] ; <nl> } <nl> <nl> - / * * All tables are locked . If there are more than one rename in chain , <nl> - * we need to hold global lock while doing all renames . Order matters to avoid deadlocks . <nl> - * It provides atomicity of all RENAME chain as a whole , from the point of view of DBMS client , <nl> - * but only in cases when there was no exceptions during this process and server does not fall . <nl> - * / <nl> - <nl> - decltype ( context . getLock ( ) ) lock ; <nl> - <nl> - if ( descriptions . size ( ) > 1 ) <nl> - lock = context . getLock ( ) ; <nl> + / / / Must do it in consistent order . <nl> + for ( auto & table_guard : table_guards ) <nl> + table_guard . second = context . getDDLGuard ( table_guard . first . database_name , table_guard . first . table_name ) ; <nl> <nl> for ( auto & elem : descriptions ) <nl> { <nl> context . assertTableDoesntExist ( elem . to_database_name , elem . to_table_name ) ; <nl> + auto from_table = context . getTable ( elem . from_database_name , elem . from_table_name ) ; <nl> + auto from_table_lock = from_table - > lockExclusively ( context . getCurrentQueryId ( ) ) ; <nl> <nl> context . getDatabase ( elem . from_database_name ) - > renameTable ( <nl> - context , elem . from_table_name , * context . getDatabase ( elem . to_database_name ) , elem . to_table_name , elem . from_table_lock ) ; <nl> + context , <nl> + elem . from_table_name , <nl> + * context . getDatabase ( elem . to_database_name ) , <nl> + elem . to_table_name , <nl> + from_table_lock ) ; <nl> } <nl> <nl> return { } ; <nl> mmm a / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> InterpreterSelectQuery : : InterpreterSelectQuery ( <nl> } <nl> <nl> if ( storage ) <nl> - table_lock = storage - > lockStructureForShare ( false , context . getCurrentQueryId ( ) ) ; <nl> + table_lock = storage - > lockStructureForShare ( false , context . getInitialQueryId ( ) ) ; <nl> <nl> syntax_analyzer_result = SyntaxAnalyzer ( context , options ) . analyze ( <nl> query_ptr , source_header . getNamesAndTypesList ( ) , required_result_column_names , storage , NamesAndTypesList ( ) ) ; <nl> mmm a / dbms / src / Interpreters / ProcessList . cpp <nl> ppp b / dbms / src / Interpreters / ProcessList . cpp <nl> QueryStatusInfo QueryStatus : : getInfo ( bool get_thread_list , bool get_profile_even <nl> { <nl> std : : lock_guard lock ( thread_group - > mutex ) ; <nl> res . thread_numbers = thread_group - > thread_numbers ; <nl> + res . os_thread_ids = thread_group - > os_thread_ids ; <nl> } <nl> <nl> if ( get_profile_events ) <nl> mmm a / dbms / src / Interpreters / ProcessList . h <nl> ppp b / dbms / src / Interpreters / ProcessList . h <nl> struct QueryStatusInfo <nl> <nl> / / / Optional fields , filled by request <nl> std : : vector < UInt32 > thread_numbers ; <nl> + std : : vector < UInt32 > os_thread_ids ; <nl> std : : shared_ptr < ProfileEvents : : Counters > profile_counters ; <nl> std : : shared_ptr < Settings > query_settings ; <nl> } ; <nl> mmm a / dbms / src / Interpreters / QueryLog . cpp <nl> ppp b / dbms / src / Interpreters / QueryLog . cpp <nl> Block QueryLogElement : : createBlock ( ) <nl> { std : : make_shared < DataTypeUInt32 > ( ) , " revision " } , <nl> <nl> { std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt32 > ( ) ) , " thread_numbers " } , <nl> + { std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt32 > ( ) ) , " os_thread_ids " } , <nl> { std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeString > ( ) ) , " ProfileEvents . Names " } , <nl> { std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt64 > ( ) ) , " ProfileEvents . Values " } , <nl> { std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeString > ( ) ) , " Settings . Names " } , <nl> void QueryLogElement : : appendToBlock ( Block & block ) const <nl> columns [ i + + ] - > insert ( threads_array ) ; <nl> } <nl> <nl> + { <nl> + Array threads_array ; <nl> + threads_array . reserve ( os_thread_ids . size ( ) ) ; <nl> + for ( const UInt32 thread_number : os_thread_ids ) <nl> + threads_array . emplace_back ( UInt64 ( thread_number ) ) ; <nl> + columns [ i + + ] - > insert ( threads_array ) ; <nl> + } <nl> + <nl> if ( profile_counters ) <nl> { <nl> auto column_names = columns [ i + + ] . get ( ) ; <nl> mmm a / dbms / src / Interpreters / QueryLog . h <nl> ppp b / dbms / src / Interpreters / QueryLog . h <nl> struct QueryLogElement <nl> ClientInfo client_info ; <nl> <nl> std : : vector < UInt32 > thread_numbers ; <nl> + std : : vector < UInt32 > os_thread_ids ; <nl> std : : shared_ptr < ProfileEvents : : Counters > profile_counters ; <nl> std : : shared_ptr < Settings > query_settings ; <nl> <nl> mmm a / dbms / src / Interpreters / ThreadStatusExt . cpp <nl> ppp b / dbms / src / Interpreters / ThreadStatusExt . cpp <nl> void ThreadStatus : : initializeQuery ( ) <nl> thread_group - > memory_tracker . setDescription ( " ( for query ) " ) ; <nl> <nl> thread_group - > thread_numbers . emplace_back ( thread_number ) ; <nl> + thread_group - > os_thread_ids . emplace_back ( os_thread_id ) ; <nl> thread_group - > master_thread_number = thread_number ; <nl> thread_group - > master_thread_os_id = os_thread_id ; <nl> <nl> void ThreadStatus : : attachQuery ( const ThreadGroupStatusPtr & thread_group_ , bool <nl> <nl> / / / NOTE : A thread may be attached multiple times if it is reused from a thread pool . <nl> thread_group - > thread_numbers . emplace_back ( thread_number ) ; <nl> + thread_group - > os_thread_ids . emplace_back ( os_thread_id ) ; <nl> } <nl> <nl> if ( query_context ) <nl> mmm a / dbms / src / Interpreters / executeQuery . cpp <nl> ppp b / dbms / src / Interpreters / executeQuery . cpp <nl> static std : : tuple < ASTPtr , BlockIO > executeQueryImpl ( <nl> } <nl> <nl> elem . thread_numbers = std : : move ( info . thread_numbers ) ; <nl> + elem . os_thread_ids = std : : move ( info . os_thread_ids ) ; <nl> elem . profile_counters = std : : move ( info . profile_counters ) ; <nl> <nl> if ( log_queries ) <nl> static std : : tuple < ASTPtr , BlockIO > executeQueryImpl ( <nl> elem . memory_usage = info . peak_memory_usage > 0 ? info . peak_memory_usage : 0 ; <nl> <nl> elem . thread_numbers = std : : move ( info . thread_numbers ) ; <nl> + elem . os_thread_ids = std : : move ( info . os_thread_ids ) ; <nl> elem . profile_counters = std : : move ( info . profile_counters ) ; <nl> } <nl> <nl> mmm a / dbms / src / Processors / Executors / PipelineExecutor . cpp <nl> ppp b / dbms / src / Processors / Executors / PipelineExecutor . cpp <nl> bool PipelineExecutor : : prepareProcessor ( UInt64 pid , Stack & children , Stack & pa <nl> switch ( node . last_processor_status ) <nl> { <nl> case IProcessor : : Status : : NeedData : <nl> - { <nl> - add_neighbours_to_prepare_queue ( ) ; <nl> - try_release_ownership ( ) ; <nl> - <nl> - break ; <nl> - } <nl> case IProcessor : : Status : : PortFull : <nl> { <nl> add_neighbours_to_prepare_queue ( ) ; <nl> mmm a / dbms / src / Processors / Formats / IRowInputFormat . cpp <nl> ppp b / dbms / src / Processors / Formats / IRowInputFormat . cpp <nl> Chunk IRowInputFormat : : generate ( ) <nl> { <nl> if ( params . allow_errors_num > 0 | | params . allow_errors_ratio > 0 ) <nl> { <nl> - Logger * log = & Logger : : get ( " BlockInputStreamFromRowInputStream " ) ; <nl> + Logger * log = & Logger : : get ( " IRowInputFormat " ) ; <nl> LOG_TRACE ( log , " Skipped " < < num_errors < < " rows with errors while reading the input stream " ) ; <nl> } <nl> <nl> mmm a / dbms / src / Processors / Formats / Impl / CSVRowInputFormat . cpp <nl> ppp b / dbms / src / Processors / Formats / Impl / CSVRowInputFormat . cpp <nl> <nl> # include < Processors / Formats / Impl / CSVRowInputFormat . h > <nl> # include < Formats / FormatFactory . h > <nl> # include < DataTypes / DataTypeNullable . h > <nl> + # include < DataTypes / DataTypeNothing . h > <nl> <nl> <nl> namespace DB <nl> namespace ErrorCodes <nl> } <nl> <nl> <nl> - CSVRowInputFormat : : CSVRowInputFormat ( <nl> - ReadBuffer & in_ , Block header_ , Params params_ , bool with_names_ , const FormatSettings & format_settings_ ) <nl> - : IRowInputFormat ( std : : move ( header_ ) , in_ , std : : move ( params_ ) ) <nl> + CSVRowInputFormat : : CSVRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + bool with_names_ , const FormatSettings & format_settings_ ) <nl> + : RowInputFormatWithDiagnosticInfo ( header_ , in_ , params_ ) <nl> , with_names ( with_names_ ) <nl> , format_settings ( format_settings_ ) <nl> { <nl> void CSVRowInputFormat : : addInputColumn ( const String & column_name ) <nl> column_indexes_for_input_fields . emplace_back ( column_index ) ; <nl> } <nl> <nl> - static void skipEndOfLine ( ReadBuffer & istr ) <nl> + static void skipEndOfLine ( ReadBuffer & in ) <nl> { <nl> / / / \ n ( Unix ) or \ r \ n ( DOS / Windows ) or \ n \ r ( Mac OS Classic ) <nl> <nl> - if ( * istr . position ( ) = = ' \ n ' ) <nl> + if ( * in . position ( ) = = ' \ n ' ) <nl> { <nl> - + + istr . position ( ) ; <nl> - if ( ! istr . eof ( ) & & * istr . position ( ) = = ' \ r ' ) <nl> - + + istr . position ( ) ; <nl> + + + in . position ( ) ; <nl> + if ( ! in . eof ( ) & & * in . position ( ) = = ' \ r ' ) <nl> + + + in . position ( ) ; <nl> } <nl> - else if ( * istr . position ( ) = = ' \ r ' ) <nl> + else if ( * in . position ( ) = = ' \ r ' ) <nl> { <nl> - + + istr . position ( ) ; <nl> - if ( ! istr . eof ( ) & & * istr . position ( ) = = ' \ n ' ) <nl> - + + istr . position ( ) ; <nl> + + + in . position ( ) ; <nl> + if ( ! in . eof ( ) & & * in . position ( ) = = ' \ n ' ) <nl> + + + in . position ( ) ; <nl> else <nl> throw Exception ( " Cannot parse CSV format : found \ \ r ( CR ) not followed by \ \ n ( LF ) . " <nl> " Line must end by \ \ n ( LF ) or \ \ r \ \ n ( CR LF ) or \ \ n \ \ r . " , ErrorCodes : : INCORRECT_DATA ) ; <nl> } <nl> - else if ( ! istr . eof ( ) ) <nl> + else if ( ! in . eof ( ) ) <nl> throw Exception ( " Expected end of line " , ErrorCodes : : INCORRECT_DATA ) ; <nl> } <nl> <nl> <nl> - static void skipDelimiter ( ReadBuffer & istr , const char delimiter , bool is_last_column ) <nl> + static void skipDelimiter ( ReadBuffer & in , const char delimiter , bool is_last_column ) <nl> { <nl> if ( is_last_column ) <nl> { <nl> - if ( istr . eof ( ) ) <nl> + if ( in . eof ( ) ) <nl> return ; <nl> <nl> / / / we support the extra delimiter at the end of the line <nl> - if ( * istr . position ( ) = = delimiter ) <nl> + if ( * in . position ( ) = = delimiter ) <nl> { <nl> - + + istr . position ( ) ; <nl> - if ( istr . eof ( ) ) <nl> + + + in . position ( ) ; <nl> + if ( in . eof ( ) ) <nl> return ; <nl> } <nl> <nl> - skipEndOfLine ( istr ) ; <nl> + skipEndOfLine ( in ) ; <nl> } <nl> else <nl> - assertChar ( delimiter , istr ) ; <nl> + assertChar ( delimiter , in ) ; <nl> } <nl> <nl> <nl> / / / Skip ` whitespace ` symbols allowed in CSV . <nl> - static inline void skipWhitespacesAndTabs ( ReadBuffer & buf ) <nl> + static inline void skipWhitespacesAndTabs ( ReadBuffer & in ) <nl> { <nl> - while ( ! buf . eof ( ) <nl> - & & ( * buf . position ( ) = = ' ' <nl> - | | * buf . position ( ) = = ' \ t ' ) ) <nl> - + + buf . position ( ) ; <nl> + while ( ! in . eof ( ) <nl> + & & ( * in . position ( ) = = ' ' <nl> + | | * in . position ( ) = = ' \ t ' ) ) <nl> + + + in . position ( ) ; <nl> } <nl> <nl> <nl> - static void skipRow ( ReadBuffer & istr , const FormatSettings : : CSV & settings , size_t num_columns ) <nl> + static void skipRow ( ReadBuffer & in , const FormatSettings : : CSV & settings , size_t num_columns ) <nl> { <nl> String tmp ; <nl> for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> { <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> - readCSVString ( tmp , istr , settings ) ; <nl> - skipWhitespacesAndTabs ( istr ) ; <nl> + skipWhitespacesAndTabs ( in ) ; <nl> + readCSVString ( tmp , in , settings ) ; <nl> + skipWhitespacesAndTabs ( in ) ; <nl> <nl> - skipDelimiter ( istr , settings . delimiter , i + 1 = = num_columns ) ; <nl> + skipDelimiter ( in , settings . delimiter , i + 1 = = num_columns ) ; <nl> } <nl> } <nl> <nl> void CSVRowInputFormat : : readPrefix ( ) <nl> skipBOMIfExists ( in ) ; <nl> <nl> size_t num_columns = data_types . size ( ) ; <nl> - String tmp ; <nl> auto & header = getPort ( ) . getHeader ( ) ; <nl> <nl> if ( with_names ) <nl> bool CSVRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtension & ext <nl> for ( size_t file_column = 0 ; file_column < column_indexes_for_input_fields . size ( ) ; + + file_column ) <nl> { <nl> const auto & table_column = column_indexes_for_input_fields [ file_column ] ; <nl> - const bool is_last_file_column = <nl> - file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> + const bool is_last_file_column = file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> <nl> if ( table_column ) <nl> { <nl> bool CSVRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtension & ext <nl> return true ; <nl> } <nl> <nl> - <nl> - String CSVRowInputFormat : : getDiagnosticInfo ( ) <nl> - { <nl> - if ( in . eof ( ) ) / / / Buffer has gone , cannot extract information about what has been parsed . <nl> - return { } ; <nl> - <nl> - WriteBufferFromOwnString out ; <nl> - <nl> - auto & header = getPort ( ) . getHeader ( ) ; <nl> - MutableColumns columns = header . cloneEmptyColumns ( ) ; <nl> - <nl> - / / / It is possible to display detailed diagnostics only if the last and next to last rows are still in the read buffer . <nl> - size_t bytes_read_at_start_of_buffer = in . count ( ) - in . offset ( ) ; <nl> - if ( bytes_read_at_start_of_buffer ! = bytes_read_at_start_of_buffer_on_prev_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because two last rows aren ' t in buffer ( rare case ) \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - size_t max_length_of_column_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . name . size ( ) > max_length_of_column_name ) <nl> - max_length_of_column_name = header . safeGetByPosition ( i ) . name . size ( ) ; <nl> - <nl> - size_t max_length_of_data_type_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) > max_length_of_data_type_name ) <nl> - max_length_of_data_type_name = header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) ; <nl> - <nl> - / / / Roll back the cursor to the beginning of the previous or current row and parse all over again . But now we derive detailed information . <nl> - <nl> - if ( pos_of_prev_row ) <nl> - { <nl> - in . position ( ) = pos_of_prev_row ; <nl> - <nl> - out < < " \ nRow " < < ( row_num - 1 ) < < " : \ n " ; <nl> - if ( ! parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ) <nl> - return out . str ( ) ; <nl> - } <nl> - else <nl> - { <nl> - if ( ! pos_of_current_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because parsing of data hasn ' t started . \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - in . position ( ) = pos_of_current_row ; <nl> - } <nl> - <nl> - out < < " \ nRow " < < row_num < < " : \ n " ; <nl> - parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ; <nl> - out < < " \ n " ; <nl> - <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - / * * gcc - 7 generates wrong code with optimization level greater than 1 . <nl> - * See tests : dbms / src / IO / tests / write_int . cpp <nl> - * and dbms / tests / queries / 0_stateless / 00898_parsing_bad_diagnostic_message . sh <nl> - * This is compiler bug . The bug does not present in gcc - 8 and clang - 8 . <nl> - * Nevertheless , we don ' t need high optimization of this function . <nl> - * / <nl> - bool OPTIMIZE ( 1 ) CSVRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) <nl> + bool CSVRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) <nl> { <nl> const char delimiter = format_settings . csv . delimiter ; <nl> <nl> bool OPTIMIZE ( 1 ) CSVRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumn <nl> <nl> if ( column_indexes_for_input_fields [ file_column ] . has_value ( ) ) <nl> { <nl> - const auto & table_column = * column_indexes_for_input_fields [ file_column ] ; <nl> - const auto & current_column_type = data_types [ table_column ] ; <nl> - const bool is_last_file_column = <nl> - file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> - const bool at_delimiter = ! in . eof ( ) & & * in . position ( ) = = delimiter ; <nl> - const bool at_last_column_line_end = is_last_file_column <nl> - & & ( in . eof ( ) | | * in . position ( ) = = ' \ n ' | | * in . position ( ) = = ' \ r ' ) ; <nl> - <nl> auto & header = getPort ( ) . getHeader ( ) ; <nl> - out < < " Column " < < file_column < < " , " < < std : : string ( ( file_column < 10 ? 2 : file_column < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < header . safeGetByPosition ( table_column ) . name < < " , " < < std : : string ( max_length_of_column_name - header . safeGetByPosition ( table_column ) . name . size ( ) , ' ' ) <nl> - < < " type : " < < current_column_type - > getName ( ) < < " , " < < std : : string ( max_length_of_data_type_name - current_column_type - > getName ( ) . size ( ) , ' ' ) ; <nl> - <nl> - if ( format_settings . csv . empty_as_default <nl> - & & ( at_delimiter | | at_last_column_line_end ) ) <nl> - { <nl> - columns [ table_column ] - > insertDefault ( ) ; <nl> - } <nl> - else <nl> - { <nl> - BufferBase : : Position prev_position = in . position ( ) ; <nl> - BufferBase : : Position curr_position = in . position ( ) ; <nl> - std : : exception_ptr exception ; <nl> - <nl> - try <nl> - { <nl> - skipWhitespacesAndTabs ( in ) ; <nl> - prev_position = in . position ( ) ; <nl> - readField ( * columns [ table_column ] , current_column_type , is_last_file_column , table_column ) ; <nl> - curr_position = in . position ( ) ; <nl> - skipWhitespacesAndTabs ( in ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - exception = std : : current_exception ( ) ; <nl> - } <nl> - <nl> - if ( curr_position < prev_position ) <nl> - throw Exception ( " Logical error : parsing is non - deterministic . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - if ( isNativeNumber ( current_column_type ) | | isDateOrDateTime ( current_column_type ) ) <nl> - { <nl> - / / / An empty string instead of a value . <nl> - if ( curr_position = = prev_position ) <nl> - { <nl> - out < < " ERROR : text " ; <nl> - verbosePrintString ( prev_position , std : : min ( prev_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " is not like " < < current_column_type - > getName ( ) < < " \ n " ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - out < < " parsed text : " ; <nl> - verbosePrintString ( prev_position , curr_position , out ) ; <nl> - <nl> - if ( exception ) <nl> - { <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - else <nl> - out < < " ERROR \ n " ; <nl> - return false ; <nl> - } <nl> - <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > haveMaximumSizeOfValue ( ) <nl> - & & * curr_position ! = ' \ n ' & & * curr_position ! = ' \ r ' <nl> - & & * curr_position ! = delimiter ) <nl> - { <nl> - out < < " ERROR : garbage after " < < current_column_type - > getName ( ) < < " : " ; <nl> - verbosePrintString ( curr_position , std : : min ( curr_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - <nl> - return false ; <nl> - } <nl> - } <nl> + size_t col_idx = column_indexes_for_input_fields [ file_column ] . value ( ) ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( header . getByPosition ( col_idx ) . name , data_types [ col_idx ] , * columns [ col_idx ] , <nl> + out , file_column ) ) <nl> + return false ; <nl> } <nl> else <nl> { <nl> static const String skipped_column_str = " < SKIPPED COLUMN > " ; <nl> - out < < " Column " < < file_column < < " , " < < std : : string ( ( file_column < 10 ? 2 : file_column < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_column_name - skipped_column_str . length ( ) , ' ' ) <nl> - < < " type : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_data_type_name - skipped_column_str . length ( ) , ' ' ) ; <nl> - <nl> - String tmp ; <nl> - readCSVString ( tmp , in , format_settings . csv ) ; <nl> + static const DataTypePtr skipped_column_type = std : : make_shared < DataTypeNothing > ( ) ; <nl> + static const MutableColumnPtr skipped_column = skipped_column_type - > createColumn ( ) ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( skipped_column_str , skipped_column_type , * skipped_column , out , file_column ) ) <nl> + return false ; <nl> } <nl> <nl> / / / Delimiters <nl> void CSVRowInputFormat : : syncAfterError ( ) <nl> skipToNextLineOrEOF ( in ) ; <nl> } <nl> <nl> - void CSVRowInputFormat : : updateDiagnosticInfo ( ) <nl> + void CSVRowInputFormat : : tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) <nl> { <nl> - + + row_num ; <nl> + skipWhitespacesAndTabs ( in ) ; <nl> + prev_pos = in . position ( ) ; <nl> <nl> - bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row ; <nl> - bytes_read_at_start_of_buffer_on_current_row = in . count ( ) - in . offset ( ) ; <nl> + if ( column_indexes_for_input_fields [ file_column ] ) <nl> + { <nl> + const bool is_last_file_column = file_column + 1 = = column_indexes_for_input_fields . size ( ) ; <nl> + if ( ! readField ( column , type , is_last_file_column , * column_indexes_for_input_fields [ file_column ] ) ) <nl> + column . insertDefault ( ) ; <nl> + } <nl> + else <nl> + { <nl> + String tmp ; <nl> + readCSVString ( tmp , in , format_settings . csv ) ; <nl> + } <nl> <nl> - pos_of_prev_row = pos_of_current_row ; <nl> - pos_of_current_row = in . position ( ) ; <nl> + curr_pos = in . position ( ) ; <nl> + skipWhitespacesAndTabs ( in ) ; <nl> } <nl> <nl> bool CSVRowInputFormat : : readField ( IColumn & column , const DataTypePtr & type , bool is_last_file_column , size_t column_idx ) <nl> void registerInputFormatProcessorCSV ( FormatFactory & factory ) <nl> IRowInputFormat : : Params params , <nl> const FormatSettings & settings ) <nl> { <nl> - return std : : make_shared < CSVRowInputFormat > ( buf , sample , std : : move ( params ) , with_names , settings ) ; <nl> + return std : : make_shared < CSVRowInputFormat > ( sample , buf , params , with_names , settings ) ; <nl> } ) ; <nl> } <nl> } <nl> mmm a / dbms / src / Processors / Formats / Impl / CSVRowInputFormat . h <nl> ppp b / dbms / src / Processors / Formats / Impl / CSVRowInputFormat . h <nl> <nl> # pragma once <nl> <nl> + # include < optional > <nl> + # include < unordered_map > <nl> + <nl> # include < Core / Block . h > <nl> - # include < Processors / Formats / IRowInputFormat . h > <nl> + # include < Processors / Formats / RowInputFormatWithDiagnosticInfo . h > <nl> # include < Formats / FormatSettings . h > <nl> <nl> <nl> namespace DB <nl> { <nl> <nl> - class ReadBuffer ; <nl> - <nl> / * * A stream for inputting data in csv format . <nl> * Does not conform with https : / / tools . ietf . org / html / rfc4180 because it skips spaces and tabs between values . <nl> * / <nl> - class CSVRowInputFormat : public IRowInputFormat <nl> + class CSVRowInputFormat : public RowInputFormatWithDiagnosticInfo <nl> { <nl> public : <nl> / * * with_names - in the first line the header with column names <nl> - * with_types - on the next line header with type names <nl> * / <nl> - CSVRowInputFormat ( ReadBuffer & in_ , Block header_ , Params params_ , bool with_names_ , const FormatSettings & format_settings_ ) ; <nl> + CSVRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + bool with_names_ , const FormatSettings & format_settings_ ) ; <nl> <nl> String getName ( ) const override { return " CSVRowInputFormat " ; } <nl> <nl> - bool readRow ( MutableColumns & columns , RowReadExtension & ) override ; <nl> + bool readRow ( MutableColumns & columns , RowReadExtension & ext ) override ; <nl> void readPrefix ( ) override ; <nl> bool allowSyncAfterError ( ) const override { return true ; } <nl> void syncAfterError ( ) override ; <nl> <nl> - std : : string getDiagnosticInfo ( ) override ; <nl> - <nl> private : <nl> bool with_names ; <nl> - DataTypes data_types ; <nl> - <nl> const FormatSettings format_settings ; <nl> + DataTypes data_types ; <nl> <nl> using IndexesMap = std : : unordered_map < String , size_t > ; <nl> IndexesMap column_indexes_by_names ; <nl> class CSVRowInputFormat : public IRowInputFormat <nl> using OptionalIndexes = std : : vector < std : : optional < size_t > > ; <nl> OptionalIndexes column_indexes_for_input_fields ; <nl> <nl> - / / / Tracks which colums we have read in a single read ( ) call . <nl> + / / / Tracks which columns we have read in a single read ( ) call . <nl> / / / For columns that are never read , it is initialized to false when we <nl> / / / read the file header , and never changed afterwards . <nl> / / / For other columns , it is updated on each read ( ) call . <nl> class CSVRowInputFormat : public IRowInputFormat <nl> <nl> void addInputColumn ( const String & column_name ) ; <nl> <nl> - / / / For convenient diagnostics in case of an error . <nl> - size_t row_num = 0 ; <nl> - <nl> - / / / How many bytes were read , not counting those that are still in the buffer . <nl> - size_t bytes_read_at_start_of_buffer_on_current_row = 0 ; <nl> - size_t bytes_read_at_start_of_buffer_on_prev_row = 0 ; <nl> - <nl> - char * pos_of_current_row = nullptr ; <nl> - char * pos_of_prev_row = nullptr ; <nl> + bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) override ; <nl> + void tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) override ; <nl> + bool isGarbageAfterField ( size_t , ReadBuffer : : Position pos ) override <nl> + { <nl> + return * pos ! = ' \ n ' & & * pos ! = ' \ r ' & & * pos ! = format_settings . csv . delimiter ; <nl> + } <nl> <nl> / / / For setting input_format_null_as_default <nl> DataTypes nullable_types ; <nl> MutableColumns nullable_columns ; <nl> OptionalIndexes column_idx_to_nullable_column_idx ; <nl> <nl> - void updateDiagnosticInfo ( ) ; <nl> - <nl> - bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) ; <nl> - <nl> bool readField ( IColumn & column , const DataTypePtr & type , bool is_last_file_column , size_t column_idx ) ; <nl> } ; <nl> <nl> mmm a / dbms / src / Processors / Formats / Impl / TabSeparatedRowInputFormat . cpp <nl> ppp b / dbms / src / Processors / Formats / Impl / TabSeparatedRowInputFormat . cpp <nl> <nl> # include < Processors / Formats / Impl / TabSeparatedRowInputFormat . h > <nl> # include < Formats / verbosePrintString . h > <nl> # include < Formats / FormatFactory . h > <nl> + # include < DataTypes / DataTypeNothing . h > <nl> <nl> namespace DB <nl> { <nl> namespace ErrorCodes <nl> } <nl> <nl> <nl> - static void skipTSVRow ( ReadBuffer & istr , const size_t num_columns ) <nl> + static void skipTSVRow ( ReadBuffer & in , const size_t num_columns ) <nl> { <nl> NullSink null_sink ; <nl> <nl> for ( size_t i = 0 ; i < num_columns ; + + i ) <nl> { <nl> - readEscapedStringInto ( null_sink , istr ) ; <nl> - assertChar ( i = = num_columns - 1 ? ' \ n ' : ' \ t ' , istr ) ; <nl> + readEscapedStringInto ( null_sink , in ) ; <nl> + assertChar ( i = = num_columns - 1 ? ' \ n ' : ' \ t ' , in ) ; <nl> } <nl> } <nl> <nl> <nl> / * * Check for a common error case - usage of Windows line feed . <nl> * / <nl> - static void checkForCarriageReturn ( ReadBuffer & istr ) <nl> + static void checkForCarriageReturn ( ReadBuffer & in ) <nl> { <nl> - if ( istr . position ( ) [ 0 ] = = ' \ r ' | | ( istr . position ( ) ! = istr . buffer ( ) . begin ( ) & & istr . position ( ) [ - 1 ] = = ' \ r ' ) ) <nl> + if ( in . position ( ) [ 0 ] = = ' \ r ' | | ( in . position ( ) ! = in . buffer ( ) . begin ( ) & & in . position ( ) [ - 1 ] = = ' \ r ' ) ) <nl> throw Exception ( " \ nYou have carriage return ( \ \ r , 0x0D , ASCII 13 ) at end of first row . " <nl> " \ nIt ' s like your input data has DOS / Windows style line separators , that are illegal in TabSeparated format . " <nl> " You must transform your file to Unix format . " <nl> static void checkForCarriageReturn ( ReadBuffer & istr ) <nl> } <nl> <nl> <nl> - TabSeparatedRowInputFormat : : TabSeparatedRowInputFormat ( <nl> - ReadBuffer & in_ , Block header_ , bool with_names_ , bool with_types_ , Params params_ , const FormatSettings & format_settings_ ) <nl> - : IRowInputFormat ( std : : move ( header_ ) , in_ , std : : move ( params_ ) ) , with_names ( with_names_ ) , with_types ( with_types_ ) , format_settings ( format_settings_ ) <nl> + TabSeparatedRowInputFormat : : TabSeparatedRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + bool with_names_ , bool with_types_ , const FormatSettings & format_settings_ ) <nl> + : RowInputFormatWithDiagnosticInfo ( header_ , in_ , params_ ) , with_names ( with_names_ ) , with_types ( with_types_ ) , format_settings ( format_settings_ ) <nl> { <nl> auto & sample = getPort ( ) . getHeader ( ) ; <nl> size_t num_columns = sample . columns ( ) ; <nl> bool TabSeparatedRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtens <nl> <nl> updateDiagnosticInfo ( ) ; <nl> <nl> - for ( size_t input_position = 0 ; input_position < column_indexes_for_input_fields . size ( ) ; + + input_position ) <nl> + for ( size_t file_column = 0 ; file_column < column_indexes_for_input_fields . size ( ) ; + + file_column ) <nl> { <nl> - const auto & column_index = column_indexes_for_input_fields [ input_position ] ; <nl> + const auto & column_index = column_indexes_for_input_fields [ file_column ] ; <nl> if ( column_index ) <nl> { <nl> data_types [ * column_index ] - > deserializeAsTextEscaped ( * columns [ * column_index ] , in , format_settings ) ; <nl> bool TabSeparatedRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtens <nl> } <nl> <nl> / / / skip separators <nl> - if ( input_position + 1 < column_indexes_for_input_fields . size ( ) ) <nl> + if ( file_column + 1 < column_indexes_for_input_fields . size ( ) ) <nl> { <nl> assertChar ( ' \ t ' , in ) ; <nl> } <nl> bool TabSeparatedRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtens <nl> return true ; <nl> } <nl> <nl> - <nl> - String TabSeparatedRowInputFormat : : getDiagnosticInfo ( ) <nl> - { <nl> - if ( in . eof ( ) ) / / / Buffer has gone , cannot extract information about what has been parsed . <nl> - return { } ; <nl> - <nl> - auto & header = getPort ( ) . getHeader ( ) ; <nl> - WriteBufferFromOwnString out ; <nl> - MutableColumns columns = header . cloneEmptyColumns ( ) ; <nl> - <nl> - / / / It is possible to display detailed diagnostics only if the last and next to last lines are still in the read buffer . <nl> - size_t bytes_read_at_start_of_buffer = in . count ( ) - in . offset ( ) ; <nl> - if ( bytes_read_at_start_of_buffer ! = bytes_read_at_start_of_buffer_on_prev_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because two last rows aren ' t in buffer ( rare case ) \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - size_t max_length_of_column_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . name . size ( ) > max_length_of_column_name ) <nl> - max_length_of_column_name = header . safeGetByPosition ( i ) . name . size ( ) ; <nl> - <nl> - size_t max_length_of_data_type_name = 0 ; <nl> - for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> - if ( header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) > max_length_of_data_type_name ) <nl> - max_length_of_data_type_name = header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) ; <nl> - <nl> - / / / Roll back the cursor to the beginning of the previous or current line and pars all over again . But now we derive detailed information . <nl> - <nl> - if ( pos_of_prev_row ) <nl> - { <nl> - in . position ( ) = pos_of_prev_row ; <nl> - <nl> - out < < " \ nRow " < < ( row_num - 1 ) < < " : \ n " ; <nl> - if ( ! parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ) <nl> - return out . str ( ) ; <nl> - } <nl> - else <nl> - { <nl> - if ( ! pos_of_current_row ) <nl> - { <nl> - out < < " Could not print diagnostic info because parsing of data hasn ' t started . \ n " ; <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - in . position ( ) = pos_of_current_row ; <nl> - } <nl> - <nl> - out < < " \ nRow " < < row_num < < " : \ n " ; <nl> - parseRowAndPrintDiagnosticInfo ( columns , out , max_length_of_column_name , max_length_of_data_type_name ) ; <nl> - out < < " \ n " ; <nl> - <nl> - return out . str ( ) ; <nl> - } <nl> - <nl> - <nl> - bool TabSeparatedRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) <nl> + bool TabSeparatedRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) <nl> { <nl> - for ( size_t input_position = 0 ; input_position < column_indexes_for_input_fields . size ( ) ; + + input_position ) <nl> + for ( size_t file_column = 0 ; file_column < column_indexes_for_input_fields . size ( ) ; + + file_column ) <nl> { <nl> - if ( input_position = = 0 & & in . eof ( ) ) <nl> + if ( file_column = = 0 & & in . eof ( ) ) <nl> { <nl> out < < " < End of stream > \ n " ; <nl> return false ; <nl> } <nl> <nl> - if ( column_indexes_for_input_fields [ input_position ] . has_value ( ) ) <nl> + if ( column_indexes_for_input_fields [ file_column ] . has_value ( ) ) <nl> { <nl> - const auto & column_index = * column_indexes_for_input_fields [ input_position ] ; <nl> - const auto & current_column_type = data_types [ column_index ] ; <nl> - <nl> - const auto & header = getPort ( ) . getHeader ( ) ; <nl> - <nl> - out < < " Column " < < input_position < < " , " < < std : : string ( ( input_position < 10 ? 2 : input_position < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < header . safeGetByPosition ( column_index ) . name < < " , " < < std : : string ( max_length_of_column_name - header . safeGetByPosition ( column_index ) . name . size ( ) , ' ' ) <nl> - < < " type : " < < current_column_type - > getName ( ) < < " , " < < std : : string ( max_length_of_data_type_name - current_column_type - > getName ( ) . size ( ) , ' ' ) ; <nl> - <nl> - auto prev_position = in . position ( ) ; <nl> - std : : exception_ptr exception ; <nl> - <nl> - try <nl> - { <nl> - current_column_type - > deserializeAsTextEscaped ( * columns [ column_index ] , in , format_settings ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - exception = std : : current_exception ( ) ; <nl> - } <nl> - <nl> - auto curr_position = in . position ( ) ; <nl> - <nl> - if ( curr_position < prev_position ) <nl> - throw Exception ( " Logical error : parsing is non - deterministic . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - if ( isNativeNumber ( current_column_type ) | | isDateOrDateTime ( current_column_type ) ) <nl> - { <nl> - / / / An empty string instead of a value . <nl> - if ( curr_position = = prev_position ) <nl> - { <nl> - out < < " ERROR : text " ; <nl> - verbosePrintString ( prev_position , std : : min ( prev_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " is not like " < < current_column_type - > getName ( ) < < " \ n " ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - out < < " parsed text : " ; <nl> - verbosePrintString ( prev_position , curr_position , out ) ; <nl> - <nl> - if ( exception ) <nl> - { <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - else <nl> - out < < " ERROR \ n " ; <nl> + auto & header = getPort ( ) . getHeader ( ) ; <nl> + size_t col_idx = column_indexes_for_input_fields [ file_column ] . value ( ) ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( header . getByPosition ( col_idx ) . name , data_types [ col_idx ] , * columns [ col_idx ] , <nl> + out , file_column ) ) <nl> return false ; <nl> - } <nl> - <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > haveMaximumSizeOfValue ( ) ) <nl> - { <nl> - if ( * curr_position ! = ' \ n ' & & * curr_position ! = ' \ t ' ) <nl> - { <nl> - out < < " ERROR : garbage after " < < current_column_type - > getName ( ) < < " : " ; <nl> - verbosePrintString ( curr_position , std : : min ( curr_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> - out < < " \ n " ; <nl> - <nl> - if ( current_column_type - > getName ( ) = = " DateTime " ) <nl> - out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> - else if ( current_column_type - > getName ( ) = = " Date " ) <nl> - out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> - <nl> - return false ; <nl> - } <nl> - } <nl> } <nl> else <nl> { <nl> static const String skipped_column_str = " < SKIPPED COLUMN > " ; <nl> - out < < " Column " < < input_position < < " , " < < std : : string ( ( input_position < 10 ? 2 : input_position < 100 ? 1 : 0 ) , ' ' ) <nl> - < < " name : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_column_name - skipped_column_str . length ( ) , ' ' ) <nl> - < < " type : " < < skipped_column_str < < " , " < < std : : string ( max_length_of_data_type_name - skipped_column_str . length ( ) , ' ' ) ; <nl> - <nl> - NullSink null_sink ; <nl> - readEscapedStringInto ( null_sink , in ) ; <nl> + static const DataTypePtr skipped_column_type = std : : make_shared < DataTypeNothing > ( ) ; <nl> + static const MutableColumnPtr skipped_column = skipped_column_type - > createColumn ( ) ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( skipped_column_str , skipped_column_type , * skipped_column , out , file_column ) ) <nl> + return false ; <nl> } <nl> <nl> / / / Delimiters <nl> - if ( input_position + 1 = = column_indexes_for_input_fields . size ( ) ) <nl> + if ( file_column + 1 = = column_indexes_for_input_fields . size ( ) ) <nl> { <nl> if ( ! in . eof ( ) ) <nl> { <nl> bool TabSeparatedRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & <nl> { <nl> out < < " ERROR : Line feed found where tab is expected . " <nl> " It ' s like your file has less columns than expected . \ n " <nl> - " And if your file have right number of columns , maybe it have unescaped backslash in value before tab , which cause tab has escaped . \ n " ; <nl> + " And if your file have right number of columns , " <nl> + " maybe it have unescaped backslash in value before tab , which cause tab has escaped . \ n " ; <nl> } <nl> else if ( * in . position ( ) = = ' \ r ' ) <nl> { <nl> bool TabSeparatedRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & <nl> return true ; <nl> } <nl> <nl> - <nl> - void TabSeparatedRowInputFormat : : syncAfterError ( ) <nl> + void TabSeparatedRowInputFormat : : tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) <nl> { <nl> - skipToUnescapedNextLineOrEOF ( in ) ; <nl> + prev_pos = in . position ( ) ; <nl> + if ( column_indexes_for_input_fields [ file_column ] ) <nl> + type - > deserializeAsTextEscaped ( column , in , format_settings ) ; <nl> + else <nl> + { <nl> + NullSink null_sink ; <nl> + readEscapedStringInto ( null_sink , in ) ; <nl> + } <nl> + curr_pos = in . position ( ) ; <nl> } <nl> <nl> - <nl> - void TabSeparatedRowInputFormat : : updateDiagnosticInfo ( ) <nl> + void TabSeparatedRowInputFormat : : syncAfterError ( ) <nl> { <nl> - + + row_num ; <nl> - <nl> - bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row ; <nl> - bytes_read_at_start_of_buffer_on_current_row = in . count ( ) - in . offset ( ) ; <nl> - <nl> - pos_of_prev_row = pos_of_current_row ; <nl> - pos_of_current_row = in . position ( ) ; <nl> + skipToUnescapedNextLineOrEOF ( in ) ; <nl> } <nl> <nl> <nl> void registerInputFormatProcessorTabSeparated ( FormatFactory & factory ) <nl> IRowInputFormat : : Params params , <nl> const FormatSettings & settings ) <nl> { <nl> - return std : : make_shared < TabSeparatedRowInputFormat > ( buf , sample , false , false , std : : move ( params ) , settings ) ; <nl> + return std : : make_shared < TabSeparatedRowInputFormat > ( sample , buf , params , false , false , settings ) ; <nl> } ) ; <nl> } <nl> <nl> void registerInputFormatProcessorTabSeparated ( FormatFactory & factory ) <nl> IRowInputFormat : : Params params , <nl> const FormatSettings & settings ) <nl> { <nl> - return std : : make_shared < TabSeparatedRowInputFormat > ( buf , sample , true , false , std : : move ( params ) , settings ) ; <nl> + return std : : make_shared < TabSeparatedRowInputFormat > ( sample , buf , params , true , false , settings ) ; <nl> } ) ; <nl> } <nl> <nl> void registerInputFormatProcessorTabSeparated ( FormatFactory & factory ) <nl> IRowInputFormat : : Params params , <nl> const FormatSettings & settings ) <nl> { <nl> - return std : : make_shared < TabSeparatedRowInputFormat > ( buf , sample , true , true , std : : move ( params ) , settings ) ; <nl> + return std : : make_shared < TabSeparatedRowInputFormat > ( sample , buf , params , true , true , settings ) ; <nl> } ) ; <nl> } <nl> } <nl> mmm a / dbms / src / Processors / Formats / Impl / TabSeparatedRowInputFormat . h <nl> ppp b / dbms / src / Processors / Formats / Impl / TabSeparatedRowInputFormat . h <nl> <nl> <nl> # include < Core / Block . h > <nl> # include < Formats / FormatSettings . h > <nl> - # include < Processors / Formats / IRowInputFormat . h > <nl> + # include < Processors / Formats / RowInputFormatWithDiagnosticInfo . h > <nl> <nl> <nl> namespace DB <nl> { <nl> <nl> - class ReadBuffer ; <nl> - <nl> - <nl> / * * A stream to input data in tsv format . <nl> * / <nl> - class TabSeparatedRowInputFormat : public IRowInputFormat <nl> + class TabSeparatedRowInputFormat : public RowInputFormatWithDiagnosticInfo <nl> { <nl> public : <nl> / * * with_names - the first line is the header with the names of the columns <nl> * with_types - on the next line header with type names <nl> * / <nl> - TabSeparatedRowInputFormat ( <nl> - ReadBuffer & in_ , Block header_ , bool with_names_ , bool with_types_ , Params params_ , const FormatSettings & format_settings_ ) ; <nl> + TabSeparatedRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + bool with_names_ , bool with_types_ , const FormatSettings & format_settings_ ) ; <nl> <nl> String getName ( ) const override { return " TabSeparatedRowInputFormat " ; } <nl> <nl> class TabSeparatedRowInputFormat : public IRowInputFormat <nl> bool allowSyncAfterError ( ) const override { return true ; } <nl> void syncAfterError ( ) override ; <nl> <nl> - std : : string getDiagnosticInfo ( ) override ; <nl> - <nl> private : <nl> bool with_names ; <nl> bool with_types ; <nl> class TabSeparatedRowInputFormat : public IRowInputFormat <nl> void setupAllColumnsByTableSchema ( ) ; <nl> void fillUnreadColumnsWithDefaults ( MutableColumns & columns , RowReadExtension & ext ) ; <nl> <nl> - / / / For convenient diagnostics in case of an error . <nl> - <nl> - size_t row_num = 0 ; <nl> - <nl> - / / / How many bytes were read , not counting those still in the buffer . <nl> - size_t bytes_read_at_start_of_buffer_on_current_row = 0 ; <nl> - size_t bytes_read_at_start_of_buffer_on_prev_row = 0 ; <nl> - <nl> - char * pos_of_current_row = nullptr ; <nl> - char * pos_of_prev_row = nullptr ; <nl> - <nl> - void updateDiagnosticInfo ( ) ; <nl> - <nl> - bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , <nl> - WriteBuffer & out , size_t max_length_of_column_name , size_t max_length_of_data_type_name ) ; <nl> + bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) override ; <nl> + void tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) override ; <nl> + bool isGarbageAfterField ( size_t , ReadBuffer : : Position pos ) override { return * pos ! = ' \ n ' & & * pos ! = ' \ t ' ; } <nl> } ; <nl> <nl> } <nl> new file mode 100644 <nl> index 00000000000 . . cbaef1b0012 <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / Impl / TemplateBlockOutputFormat . cpp <nl> <nl> + # include < Processors / Formats / Impl / TemplateBlockOutputFormat . h > <nl> + # include < Formats / FormatFactory . h > <nl> + # include < IO / WriteHelpers . h > <nl> + # include < DataTypes / DataTypesNumber . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int SYNTAX_ERROR ; <nl> + } <nl> + <nl> + TemplateBlockOutputFormat : : TemplateBlockOutputFormat ( const Block & header_ , WriteBuffer & out_ , const FormatSettings & settings_ ) <nl> + : IOutputFormat ( header_ , out_ ) , settings ( settings_ ) <nl> + { <nl> + auto & sample = getPort ( PortKind : : Main ) . getHeader ( ) ; <nl> + size_t columns = sample . columns ( ) ; <nl> + types . resize ( columns ) ; <nl> + for ( size_t i = 0 ; i < columns ; + + i ) <nl> + types [ i ] = sample . safeGetByPosition ( i ) . type ; <nl> + <nl> + / / / Parse format string for whole output <nl> + static const String default_format ( " $ { data } " ) ; <nl> + const String & format_str = settings . template_settings . format . empty ( ) ? default_format : settings . template_settings . format ; <nl> + format = ParsedTemplateFormatString ( format_str , [ & ] ( const String & partName ) <nl> + { <nl> + return static_cast < size_t > ( stringToOutputPart ( partName ) ) ; <nl> + } ) ; <nl> + <nl> + / / / Validate format string for whole output <nl> + size_t data_idx = format . format_idx_to_column_idx . size ( ) + 1 ; <nl> + for ( size_t i = 0 ; i < format . format_idx_to_column_idx . size ( ) ; + + i ) <nl> + { <nl> + if ( ! format . format_idx_to_column_idx [ i ] ) <nl> + format . throwInvalidFormat ( " Output part name cannot be empty , it ' s a bug . " , i ) ; <nl> + switch ( static_cast < OutputPart > ( * format . format_idx_to_column_idx [ i ] ) ) <nl> + { <nl> + case OutputPart : : Data : <nl> + data_idx = i ; <nl> + [ [ fallthrough ] ] ; <nl> + case OutputPart : : Totals : <nl> + case OutputPart : : ExtremesMin : <nl> + case OutputPart : : ExtremesMax : <nl> + if ( format . formats [ i ] ! = ColumnFormat : : None ) <nl> + format . throwInvalidFormat ( " Serialization type for data , totals , min and max must be empty or None " , i ) ; <nl> + break ; <nl> + default : <nl> + if ( format . formats [ i ] = = ColumnFormat : : None ) <nl> + format . throwInvalidFormat ( " Serialization type for output part rows , rows_before_limit , time , " <nl> + " rows_read or bytes_read is not specified " , i ) ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( data_idx ! = 0 ) <nl> + format . throwInvalidFormat ( " $ { data } must be the first output part " , 0 ) ; <nl> + <nl> + / / / Parse format string for rows <nl> + row_format = ParsedTemplateFormatString ( settings . template_settings . row_format , [ & ] ( const String & colName ) <nl> + { <nl> + return sample . getPositionByName ( colName ) ; <nl> + } ) ; <nl> + <nl> + / / / Validate format string for rows <nl> + if ( row_format . delimiters . size ( ) = = 1 ) <nl> + row_format . throwInvalidFormat ( " No columns specified " , 0 ) ; <nl> + for ( size_t i = 0 ; i < row_format . columnsCount ( ) ; + + i ) <nl> + { <nl> + if ( ! row_format . format_idx_to_column_idx [ i ] ) <nl> + row_format . throwInvalidFormat ( " Cannot skip format field for output , it ' s a bug . " , i ) ; <nl> + if ( row_format . formats [ i ] = = ColumnFormat : : None ) <nl> + row_format . throwInvalidFormat ( " Serialization type for file column is not specified " , i ) ; <nl> + } <nl> + } <nl> + <nl> + TemplateBlockOutputFormat : : OutputPart TemplateBlockOutputFormat : : stringToOutputPart ( const String & part ) <nl> + { <nl> + if ( part = = " data " ) <nl> + return OutputPart : : Data ; <nl> + else if ( part = = " totals " ) <nl> + return OutputPart : : Totals ; <nl> + else if ( part = = " min " ) <nl> + return OutputPart : : ExtremesMin ; <nl> + else if ( part = = " max " ) <nl> + return OutputPart : : ExtremesMax ; <nl> + else if ( part = = " rows " ) <nl> + return OutputPart : : Rows ; <nl> + else if ( part = = " rows_before_limit " ) <nl> + return OutputPart : : RowsBeforeLimit ; <nl> + else if ( part = = " time " ) <nl> + return OutputPart : : TimeElapsed ; <nl> + else if ( part = = " rows_read " ) <nl> + return OutputPart : : RowsRead ; <nl> + else if ( part = = " bytes_read " ) <nl> + return OutputPart : : BytesRead ; <nl> + else <nl> + throw Exception ( " Unknown output part " + part , ErrorCodes : : SYNTAX_ERROR ) ; <nl> + } <nl> + <nl> + void TemplateBlockOutputFormat : : writeRow ( const Chunk & chunk , size_t row_num ) <nl> + { <nl> + size_t columns = row_format . format_idx_to_column_idx . size ( ) ; <nl> + for ( size_t j = 0 ; j < columns ; + + j ) <nl> + { <nl> + writeString ( row_format . delimiters [ j ] , out ) ; <nl> + <nl> + size_t col_idx = * row_format . format_idx_to_column_idx [ j ] ; <nl> + serializeField ( * chunk . getColumns ( ) [ col_idx ] , * types [ col_idx ] , row_num , row_format . formats [ j ] ) ; <nl> + } <nl> + writeString ( row_format . delimiters [ columns ] , out ) ; <nl> + } <nl> + <nl> + void TemplateBlockOutputFormat : : serializeField ( const IColumn & column , const IDataType & type , size_t row_num , ColumnFormat col_format ) <nl> + { <nl> + switch ( col_format ) <nl> + { <nl> + case ColumnFormat : : Escaped : <nl> + type . serializeAsTextEscaped ( column , row_num , out , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Quoted : <nl> + type . serializeAsTextQuoted ( column , row_num , out , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Csv : <nl> + type . serializeAsTextCSV ( column , row_num , out , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Json : <nl> + type . serializeAsTextJSON ( column , row_num , out , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Xml : <nl> + type . serializeAsTextXML ( column , row_num , out , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Raw : <nl> + type . serializeAsText ( column , row_num , out , settings ) ; <nl> + break ; <nl> + default : <nl> + __builtin_unreachable ( ) ; <nl> + } <nl> + } <nl> + <nl> + template < typename U , typename V > void TemplateBlockOutputFormat : : writeValue ( U value , ColumnFormat col_format ) <nl> + { <nl> + auto type = std : : make_unique < V > ( ) ; <nl> + auto col = type - > createColumn ( ) ; <nl> + col - > insert ( value ) ; <nl> + serializeField ( * col , * type , 0 , col_format ) ; <nl> + } <nl> + <nl> + void TemplateBlockOutputFormat : : consume ( Chunk chunk ) <nl> + { <nl> + doWritePrefix ( ) ; <nl> + <nl> + size_t rows = chunk . getNumRows ( ) ; <nl> + <nl> + for ( size_t i = 0 ; i < rows ; + + i ) <nl> + { <nl> + if ( row_count ) <nl> + writeString ( settings . template_settings . row_between_delimiter , out ) ; <nl> + <nl> + writeRow ( chunk , i ) ; <nl> + + + row_count ; <nl> + } <nl> + } <nl> + <nl> + void TemplateBlockOutputFormat : : doWritePrefix ( ) <nl> + { <nl> + if ( need_write_prefix ) <nl> + { <nl> + writeString ( format . delimiters . front ( ) , out ) ; <nl> + need_write_prefix = false ; <nl> + } <nl> + } <nl> + <nl> + void TemplateBlockOutputFormat : : finalize ( ) <nl> + { <nl> + if ( finalized ) <nl> + return ; <nl> + <nl> + doWritePrefix ( ) ; <nl> + <nl> + size_t parts = format . format_idx_to_column_idx . size ( ) ; <nl> + <nl> + for ( size_t i = 0 ; i < parts ; + + i ) <nl> + { <nl> + auto type = std : : make_shared < DataTypeUInt64 > ( ) ; <nl> + ColumnWithTypeAndName col ( type - > createColumnConst ( 1 , row_count ) , type , String ( " tmp " ) ) ; <nl> + switch ( static_cast < OutputPart > ( * format . format_idx_to_column_idx [ i ] ) ) <nl> + { <nl> + case OutputPart : : Totals : <nl> + if ( ! totals ) <nl> + format . throwInvalidFormat ( " Cannot print totals for this request " , i ) ; <nl> + writeRow ( totals , 0 ) ; <nl> + break ; <nl> + case OutputPart : : ExtremesMin : <nl> + if ( ! extremes ) <nl> + format . throwInvalidFormat ( " Cannot print extremes for this request " , i ) ; <nl> + writeRow ( extremes , 0 ) ; <nl> + break ; <nl> + case OutputPart : : ExtremesMax : <nl> + if ( ! extremes ) <nl> + format . throwInvalidFormat ( " Cannot print extremes for this request " , i ) ; <nl> + writeRow ( extremes , 1 ) ; <nl> + break ; <nl> + case OutputPart : : Rows : <nl> + writeValue < size_t , DataTypeUInt64 > ( row_count , format . formats [ i ] ) ; <nl> + break ; <nl> + case OutputPart : : RowsBeforeLimit : <nl> + if ( ! rows_before_limit_set ) <nl> + format . throwInvalidFormat ( " Cannot print rows_before_limit for this request " , i ) ; <nl> + writeValue < size_t , DataTypeUInt64 > ( rows_before_limit , format . formats [ i ] ) ; <nl> + break ; <nl> + case OutputPart : : TimeElapsed : <nl> + writeValue < double , DataTypeFloat64 > ( watch . elapsedSeconds ( ) , format . formats [ i ] ) ; <nl> + break ; <nl> + case OutputPart : : RowsRead : <nl> + writeValue < size_t , DataTypeUInt64 > ( progress . read_rows . load ( ) , format . formats [ i ] ) ; <nl> + break ; <nl> + case OutputPart : : BytesRead : <nl> + writeValue < size_t , DataTypeUInt64 > ( progress . read_bytes . load ( ) , format . formats [ i ] ) ; <nl> + break ; <nl> + default : <nl> + break ; <nl> + } <nl> + writeString ( format . delimiters [ i + 1 ] , out ) ; <nl> + } <nl> + <nl> + finalized = true ; <nl> + } <nl> + <nl> + <nl> + void registerOutputFormatProcessorTemplate ( FormatFactory & factory ) <nl> + { <nl> + factory . registerOutputFormatProcessor ( " Template " , [ ] ( <nl> + WriteBuffer & buf , <nl> + const Block & sample , <nl> + const Context & , <nl> + FormatFactory : : WriteCallback , <nl> + const FormatSettings & settings ) <nl> + { <nl> + return std : : make_shared < TemplateBlockOutputFormat > ( sample , buf , settings ) ; <nl> + } ) ; <nl> + } <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 9eb5f61d4e7 <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / Impl / TemplateBlockOutputFormat . h <nl> <nl> + # pragma once <nl> + <nl> + # include < Common / Stopwatch . h > <nl> + # include < Core / Block . h > <nl> + # include < Formats / FormatSettings . h > <nl> + # include < Processors / Formats / IOutputFormat . h > <nl> + # include < Formats / ParsedTemplateFormatString . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + class TemplateBlockOutputFormat : public IOutputFormat <nl> + { <nl> + using ColumnFormat = ParsedTemplateFormatString : : ColumnFormat ; <nl> + public : <nl> + TemplateBlockOutputFormat ( const Block & header_ , WriteBuffer & out_ , const FormatSettings & settings_ ) ; <nl> + <nl> + String getName ( ) const override { return " TemplateBlockOutputFormat " ; } <nl> + <nl> + void doWritePrefix ( ) override ; <nl> + <nl> + void setRowsBeforeLimit ( size_t rows_before_limit_ ) override { rows_before_limit = rows_before_limit_ ; rows_before_limit_set = true ; } <nl> + void onProgress ( const Progress & progress_ ) override { progress . incrementPiecewiseAtomically ( progress_ ) ; } <nl> + <nl> + protected : <nl> + void consume ( Chunk chunk ) override ; <nl> + void consumeTotals ( Chunk chunk ) override { totals = std : : move ( chunk ) ; } <nl> + void consumeExtremes ( Chunk chunk ) override { extremes = std : : move ( chunk ) ; } <nl> + void finalize ( ) override ; <nl> + <nl> + enum class OutputPart : size_t <nl> + { <nl> + Data , <nl> + Totals , <nl> + ExtremesMin , <nl> + ExtremesMax , <nl> + Rows , <nl> + RowsBeforeLimit , <nl> + TimeElapsed , <nl> + RowsRead , <nl> + BytesRead <nl> + } ; <nl> + <nl> + OutputPart stringToOutputPart ( const String & part ) ; <nl> + void writeRow ( const Chunk & chunk , size_t row_num ) ; <nl> + void serializeField ( const IColumn & column , const IDataType & type , size_t row_num , ColumnFormat format ) ; <nl> + template < typename U , typename V > void writeValue ( U value , ColumnFormat col_format ) ; <nl> + <nl> + protected : <nl> + const FormatSettings settings ; <nl> + DataTypes types ; <nl> + <nl> + ParsedTemplateFormatString format ; <nl> + ParsedTemplateFormatString row_format ; <nl> + <nl> + size_t rows_before_limit = 0 ; <nl> + bool rows_before_limit_set = false ; <nl> + Chunk totals ; <nl> + Chunk extremes ; <nl> + Progress progress ; <nl> + Stopwatch watch ; <nl> + <nl> + size_t row_count = 0 ; <nl> + bool need_write_prefix = true ; <nl> + } ; <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . c2145f88e69 <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / Impl / TemplateRowInputFormat . cpp <nl> <nl> + # include < Processors / Formats / Impl / TemplateRowInputFormat . h > <nl> + # include < Formats / FormatFactory . h > <nl> + # include < Formats / verbosePrintString . h > <nl> + # include < IO / Operators . h > <nl> + # include < DataTypes / DataTypeNothing . h > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int ATTEMPT_TO_READ_AFTER_EOF ; <nl> + extern const int CANNOT_READ_ALL_DATA ; <nl> + extern const int CANNOT_PARSE_ESCAPE_SEQUENCE ; <nl> + extern const int CANNOT_PARSE_QUOTED_STRING ; <nl> + extern const int SYNTAX_ERROR ; <nl> + } <nl> + <nl> + <nl> + TemplateRowInputFormat : : TemplateRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + const FormatSettings & settings_ , bool ignore_spaces_ ) <nl> + : RowInputFormatWithDiagnosticInfo ( header_ , buf , params_ ) , buf ( in_ ) , data_types ( header_ . getDataTypes ( ) ) , <nl> + settings ( settings_ ) , ignore_spaces ( ignore_spaces_ ) <nl> + { <nl> + / / / Parse format string for whole input <nl> + static const String default_format ( " $ { data } " ) ; <nl> + const String & format_str = settings . template_settings . format . empty ( ) ? default_format : settings . template_settings . format ; <nl> + format = ParsedTemplateFormatString ( format_str , [ & ] ( const String & partName ) - > std : : optional < size_t > <nl> + { <nl> + if ( partName = = " data " ) <nl> + return 0 ; <nl> + else if ( partName . empty ( ) ) / / / For skipping some values in prefix and suffix <nl> + # if ! __clang__ <nl> + # pragma GCC diagnostic push <nl> + # pragma GCC diagnostic ignored " - Wmaybe - uninitialized " <nl> + # endif <nl> + / / / Suppress false - positive warning ( bug in GCC 9 : https : / / gcc . gnu . org / bugzilla / show_bug . cgi ? id = 86465 ) <nl> + return { } ; <nl> + # if ! __clang__ <nl> + # pragma GCC diagnostic pop <nl> + # endif <nl> + throw Exception ( " Unknown input part " + partName , ErrorCodes : : SYNTAX_ERROR ) ; <nl> + } ) ; <nl> + <nl> + / / / Validate format string for whole input <nl> + bool has_data = false ; <nl> + for ( size_t i = 0 ; i < format . columnsCount ( ) ; + + i ) <nl> + { <nl> + if ( format . format_idx_to_column_idx [ i ] ) <nl> + { <nl> + if ( has_data ) <nl> + format . throwInvalidFormat ( " $ { data } can occur only once " , i ) ; <nl> + if ( format . formats [ i ] ! = ColumnFormat : : None ) <nl> + format . throwInvalidFormat ( " $ { data } must have empty or None deserialization type " , i ) ; <nl> + has_data = true ; <nl> + format_data_idx = i ; <nl> + } <nl> + else <nl> + { <nl> + if ( format . formats [ i ] = = ColumnFormat : : Xml | | format . formats [ i ] = = ColumnFormat : : Raw ) <nl> + format . throwInvalidFormat ( " XML and Raw deserialization is not supported " , i ) ; <nl> + } <nl> + } <nl> + <nl> + / / / Parse format string for rows <nl> + row_format = ParsedTemplateFormatString ( settings . template_settings . row_format , [ & ] ( const String & colName ) - > std : : optional < size_t > <nl> + { <nl> + if ( colName . empty ( ) ) <nl> + # if ! __clang__ <nl> + # pragma GCC diagnostic push <nl> + # pragma GCC diagnostic ignored " - Wmaybe - uninitialized " <nl> + # endif <nl> + return { } ; <nl> + # if ! __clang__ <nl> + # pragma GCC diagnostic pop <nl> + # endif <nl> + return header_ . getPositionByName ( colName ) ; <nl> + } ) ; <nl> + <nl> + / / / Validate format string for rows <nl> + std : : vector < UInt8 > column_in_format ( header_ . columns ( ) , false ) ; <nl> + for ( size_t i = 0 ; i < row_format . columnsCount ( ) ; + + i ) <nl> + { <nl> + if ( row_format . formats [ i ] = = ColumnFormat : : Xml | | row_format . formats [ i ] = = ColumnFormat : : Raw ) <nl> + row_format . throwInvalidFormat ( " XML and Raw deserialization is not supported " , i ) ; <nl> + <nl> + if ( row_format . format_idx_to_column_idx [ i ] ) <nl> + { <nl> + if ( row_format . formats [ i ] = = ColumnFormat : : None ) <nl> + row_format . throwInvalidFormat ( " Column is not skipped , but deserialization type is None " , i ) ; <nl> + <nl> + size_t col_idx = * row_format . format_idx_to_column_idx [ i ] ; <nl> + if ( column_in_format [ col_idx ] ) <nl> + row_format . throwInvalidFormat ( " Duplicate column " , i ) ; <nl> + column_in_format [ col_idx ] = true ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : readPrefix ( ) <nl> + { <nl> + size_t last_successfully_parsed_idx = 0 ; <nl> + try <nl> + { <nl> + tryReadPrefixOrSuffix < void > ( last_successfully_parsed_idx , format_data_idx ) ; <nl> + } <nl> + catch ( Exception & e ) <nl> + { <nl> + format . throwInvalidFormat ( e . message ( ) + " While parsing prefix " , last_successfully_parsed_idx ) ; <nl> + } <nl> + } <nl> + <nl> + / / / Asserts delimiters and skips fields in prefix or suffix . <nl> + / / / tryReadPrefixOrSuffix < bool > ( . . . ) is used in checkForSuffix ( ) to avoid throwing an exception after read of each row <nl> + / / / ( most likely false will be returned on first call of checkString ( . . . ) ) <nl> + template < typename ReturnType > <nl> + ReturnType TemplateRowInputFormat : : tryReadPrefixOrSuffix ( size_t & input_part_beg , size_t input_part_end ) <nl> + { <nl> + static constexpr bool throw_exception = std : : is_same_v < ReturnType , void > ; <nl> + <nl> + skipSpaces ( ) ; <nl> + if constexpr ( throw_exception ) <nl> + assertString ( format . delimiters [ input_part_beg ] , buf ) ; <nl> + else <nl> + { <nl> + if ( likely ( ! checkString ( format . delimiters [ input_part_beg ] , buf ) ) ) <nl> + return ReturnType ( false ) ; <nl> + } <nl> + <nl> + while ( input_part_beg < input_part_end ) <nl> + { <nl> + skipSpaces ( ) ; <nl> + if constexpr ( throw_exception ) <nl> + skipField ( format . formats [ input_part_beg ] ) ; <nl> + else <nl> + { <nl> + try <nl> + { <nl> + skipField ( format . formats [ input_part_beg ] ) ; <nl> + } <nl> + catch ( const Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = ErrorCodes : : ATTEMPT_TO_READ_AFTER_EOF & & <nl> + e . code ( ) ! = ErrorCodes : : CANNOT_PARSE_ESCAPE_SEQUENCE & & <nl> + e . code ( ) ! = ErrorCodes : : CANNOT_PARSE_QUOTED_STRING ) <nl> + throw ; <nl> + / / / If it ' s parsing error , then suffix is not found <nl> + return ReturnType ( false ) ; <nl> + } <nl> + } <nl> + + + input_part_beg ; <nl> + <nl> + skipSpaces ( ) ; <nl> + if constexpr ( throw_exception ) <nl> + assertString ( format . delimiters [ input_part_beg ] , buf ) ; <nl> + else <nl> + { <nl> + if ( likely ( ! checkString ( format . delimiters [ input_part_beg ] , buf ) ) ) <nl> + return ReturnType ( false ) ; <nl> + } <nl> + } <nl> + <nl> + if constexpr ( ! throw_exception ) <nl> + return ReturnType ( true ) ; <nl> + } <nl> + <nl> + bool TemplateRowInputFormat : : readRow ( MutableColumns & columns , RowReadExtension & extra ) <nl> + { <nl> + / / / This function can be called again after it returned false <nl> + if ( unlikely ( end_of_stream ) ) <nl> + return false ; <nl> + <nl> + skipSpaces ( ) ; <nl> + <nl> + if ( unlikely ( checkForSuffix ( ) ) ) <nl> + { <nl> + end_of_stream = true ; <nl> + return false ; <nl> + } <nl> + <nl> + updateDiagnosticInfo ( ) ; <nl> + <nl> + if ( likely ( row_num ! = 1 ) ) <nl> + assertString ( settings . template_settings . row_between_delimiter , buf ) ; <nl> + <nl> + extra . read_columns . assign ( columns . size ( ) , false ) ; <nl> + <nl> + for ( size_t i = 0 ; i < row_format . columnsCount ( ) ; + + i ) <nl> + { <nl> + skipSpaces ( ) ; <nl> + assertString ( row_format . delimiters [ i ] , buf ) ; <nl> + skipSpaces ( ) ; <nl> + if ( row_format . format_idx_to_column_idx [ i ] ) <nl> + { <nl> + size_t col_idx = * row_format . format_idx_to_column_idx [ i ] ; <nl> + deserializeField ( * data_types [ col_idx ] , * columns [ col_idx ] , row_format . formats [ i ] ) ; <nl> + extra . read_columns [ col_idx ] = true ; <nl> + } <nl> + else <nl> + skipField ( row_format . formats [ i ] ) ; <nl> + <nl> + } <nl> + <nl> + skipSpaces ( ) ; <nl> + assertString ( row_format . delimiters . back ( ) , buf ) ; <nl> + <nl> + for ( size_t i = 0 ; i < columns . size ( ) ; + + i ) <nl> + if ( ! extra . read_columns [ i ] ) <nl> + data_types [ i ] - > insertDefaultInto ( * columns [ i ] ) ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : deserializeField ( const IDataType & type , IColumn & column , ColumnFormat col_format ) <nl> + { <nl> + try <nl> + { <nl> + switch ( col_format ) <nl> + { <nl> + case ColumnFormat : : Escaped : <nl> + type . deserializeAsTextEscaped ( column , buf , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Quoted : <nl> + type . deserializeAsTextQuoted ( column , buf , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Csv : <nl> + type . deserializeAsTextCSV ( column , buf , settings ) ; <nl> + break ; <nl> + case ColumnFormat : : Json : <nl> + type . deserializeAsTextJSON ( column , buf , settings ) ; <nl> + break ; <nl> + default : <nl> + __builtin_unreachable ( ) ; <nl> + } <nl> + } <nl> + catch ( Exception & e ) <nl> + { <nl> + if ( e . code ( ) = = ErrorCodes : : ATTEMPT_TO_READ_AFTER_EOF ) <nl> + throwUnexpectedEof ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : skipField ( TemplateRowInputFormat : : ColumnFormat col_format ) <nl> + { <nl> + String tmp ; <nl> + constexpr const char * field_name = " < SKIPPED COLUMN > " ; <nl> + constexpr size_t field_name_len = 16 ; <nl> + try <nl> + { <nl> + switch ( col_format ) <nl> + { <nl> + case ColumnFormat : : None : <nl> + / / / Empty field , just skip spaces <nl> + break ; <nl> + case ColumnFormat : : Escaped : <nl> + readEscapedString ( tmp , buf ) ; <nl> + break ; <nl> + case ColumnFormat : : Quoted : <nl> + readQuotedString ( tmp , buf ) ; <nl> + break ; <nl> + case ColumnFormat : : Csv : <nl> + readCSVString ( tmp , buf , settings . csv ) ; <nl> + break ; <nl> + case ColumnFormat : : Json : <nl> + skipJSONField ( buf , StringRef ( field_name , field_name_len ) ) ; <nl> + break ; <nl> + default : <nl> + __builtin_unreachable ( ) ; <nl> + } <nl> + } <nl> + catch ( Exception & e ) <nl> + { <nl> + if ( e . code ( ) = = ErrorCodes : : ATTEMPT_TO_READ_AFTER_EOF ) <nl> + throwUnexpectedEof ( ) ; <nl> + throw ; <nl> + } <nl> + } <nl> + <nl> + / / / Returns true if all rows have been read i . e . there are only suffix and spaces ( if ignore_spaces = = true ) before EOF . <nl> + / / / Otherwise returns false <nl> + bool TemplateRowInputFormat : : checkForSuffix ( ) <nl> + { <nl> + PeekableReadBufferCheckpoint checkpoint { buf } ; <nl> + bool suffix_found = false ; <nl> + size_t last_successfully_parsed_idx = format_data_idx + 1 ; <nl> + try <nl> + { <nl> + suffix_found = tryReadPrefixOrSuffix < bool > ( last_successfully_parsed_idx , format . columnsCount ( ) ) ; <nl> + } <nl> + catch ( const Exception & e ) <nl> + { <nl> + if ( e . code ( ) ! = ErrorCodes : : ATTEMPT_TO_READ_AFTER_EOF & & <nl> + e . code ( ) ! = ErrorCodes : : CANNOT_PARSE_ESCAPE_SEQUENCE & & <nl> + e . code ( ) ! = ErrorCodes : : CANNOT_PARSE_QUOTED_STRING ) <nl> + throw ; <nl> + } <nl> + <nl> + if ( unlikely ( suffix_found ) ) <nl> + { <nl> + skipSpaces ( ) ; <nl> + if ( buf . eof ( ) ) <nl> + return true ; <nl> + } <nl> + <nl> + buf . rollbackToCheckpoint ( ) ; <nl> + return false ; <nl> + } <nl> + <nl> + bool TemplateRowInputFormat : : parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) <nl> + { <nl> + out < < " Suffix does not match : " ; <nl> + size_t last_successfully_parsed_idx = format_data_idx + 1 ; <nl> + const ReadBuffer : : Position row_begin_pos = buf . position ( ) ; <nl> + bool caught = false ; <nl> + try <nl> + { <nl> + PeekableReadBufferCheckpoint checkpoint { buf , true } ; <nl> + tryReadPrefixOrSuffix < void > ( last_successfully_parsed_idx , format . columnsCount ( ) ) ; <nl> + } <nl> + catch ( Exception & e ) <nl> + { <nl> + out < < e . message ( ) < < " Near column " < < last_successfully_parsed_idx ; <nl> + caught = true ; <nl> + } <nl> + if ( ! caught ) <nl> + { <nl> + out < < " There is some data after suffix ( EOF expected , got " ; <nl> + verbosePrintString ( buf . position ( ) , std : : min ( buf . buffer ( ) . end ( ) , buf . position ( ) + 16 ) , out ) ; <nl> + out < < " ) . " ; <nl> + } <nl> + out < < " Format string ( from format_schema ) : \ n " < < format . dump ( ) < < " \ n " ; <nl> + <nl> + if ( row_begin_pos ! = buf . position ( ) ) <nl> + { <nl> + / / / Pointers to buffer memory were invalidated during checking for suffix <nl> + out < < " \ nCannot print more diagnostic info . " ; <nl> + return false ; <nl> + } <nl> + <nl> + out < < " \ nUsing format string ( from format_schema_rows ) : " < < row_format . dump ( ) < < " \ n " ; <nl> + out < < " \ nTrying to parse next row , because suffix does not match : \ n " ; <nl> + try <nl> + { <nl> + if ( likely ( row_num ! = 1 ) ) <nl> + assertString ( settings . template_settings . row_between_delimiter , buf ) ; <nl> + } <nl> + catch ( const DB : : Exception & ) <nl> + { <nl> + writeErrorStringForWrongDelimiter ( out , " delimiter between rows " , settings . template_settings . row_between_delimiter ) ; <nl> + <nl> + return false ; <nl> + } <nl> + for ( size_t i = 0 ; i < row_format . columnsCount ( ) ; + + i ) <nl> + { <nl> + skipSpaces ( ) ; <nl> + try <nl> + { <nl> + assertString ( row_format . delimiters [ i ] , buf ) ; <nl> + } <nl> + catch ( const DB : : Exception & ) <nl> + { <nl> + writeErrorStringForWrongDelimiter ( out , " delimiter before field " + std : : to_string ( i ) , row_format . delimiters [ i ] ) ; <nl> + return false ; <nl> + } <nl> + <nl> + skipSpaces ( ) ; <nl> + if ( row_format . format_idx_to_column_idx [ i ] ) <nl> + { <nl> + auto & header = getPort ( ) . getHeader ( ) ; <nl> + size_t col_idx = * row_format . format_idx_to_column_idx [ i ] ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( header . getByPosition ( col_idx ) . name , data_types [ col_idx ] , <nl> + * columns [ col_idx ] , out , i ) ) <nl> + { <nl> + out < < " Maybe it ' s not possible to deserialize field " + std : : to_string ( i ) + <nl> + " as " + ParsedTemplateFormatString : : formatToString ( row_format . formats [ i ] ) ; <nl> + return false ; <nl> + } <nl> + } <nl> + else <nl> + { <nl> + static const String skipped_column_str = " < SKIPPED COLUMN > " ; <nl> + static const DataTypePtr skipped_column_type = std : : make_shared < DataTypeNothing > ( ) ; <nl> + static const MutableColumnPtr skipped_column = skipped_column_type - > createColumn ( ) ; <nl> + if ( ! deserializeFieldAndPrintDiagnosticInfo ( skipped_column_str , skipped_column_type , * skipped_column , out , i ) ) <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + skipSpaces ( ) ; <nl> + try <nl> + { <nl> + assertString ( row_format . delimiters . back ( ) , buf ) ; <nl> + } <nl> + catch ( const DB : : Exception & ) <nl> + { <nl> + writeErrorStringForWrongDelimiter ( out , " delimiter after last field " , row_format . delimiters . back ( ) ) ; <nl> + return false ; <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : writeErrorStringForWrongDelimiter ( WriteBuffer & out , const String & description , const String & delim ) <nl> + { <nl> + out < < " ERROR : There is no " < < description < < " : expected " ; <nl> + verbosePrintString ( delim . data ( ) , delim . data ( ) + delim . size ( ) , out ) ; <nl> + out < < " , got " ; <nl> + if ( buf . eof ( ) ) <nl> + out < < " < End of stream > " ; <nl> + else <nl> + verbosePrintString ( buf . position ( ) , std : : min ( buf . position ( ) + delim . size ( ) + 10 , buf . buffer ( ) . end ( ) ) , out ) ; <nl> + out < < ' \ n ' ; <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) <nl> + { <nl> + prev_pos = buf . position ( ) ; <nl> + if ( row_format . format_idx_to_column_idx [ file_column ] ) <nl> + deserializeField ( * type , column , row_format . formats [ file_column ] ) ; <nl> + else <nl> + skipField ( row_format . formats [ file_column ] ) ; <nl> + curr_pos = buf . position ( ) ; <nl> + } <nl> + <nl> + bool TemplateRowInputFormat : : isGarbageAfterField ( size_t , ReadBuffer : : Position ) <nl> + { <nl> + / / / Garbage will be considered as wrong delimiter <nl> + return false ; <nl> + } <nl> + <nl> + bool TemplateRowInputFormat : : allowSyncAfterError ( ) const <nl> + { <nl> + return ! row_format . delimiters . back ( ) . empty ( ) | | ! settings . template_settings . row_between_delimiter . empty ( ) ; <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : syncAfterError ( ) <nl> + { <nl> + bool at_beginning_of_row_or_eof = false ; <nl> + while ( ! at_beginning_of_row_or_eof ) <nl> + { <nl> + skipToNextDelimiterOrEof ( row_format . delimiters . back ( ) ) ; <nl> + if ( buf . eof ( ) ) <nl> + { <nl> + end_of_stream = true ; <nl> + return ; <nl> + } <nl> + buf . ignore ( row_format . delimiters . back ( ) . size ( ) ) ; <nl> + <nl> + skipSpaces ( ) ; <nl> + if ( checkForSuffix ( ) ) <nl> + return ; <nl> + <nl> + bool last_delimiter_in_row_found = ! row_format . delimiters . back ( ) . empty ( ) ; <nl> + <nl> + if ( last_delimiter_in_row_found & & checkString ( settings . template_settings . row_between_delimiter , buf ) ) <nl> + at_beginning_of_row_or_eof = true ; <nl> + else <nl> + skipToNextDelimiterOrEof ( settings . template_settings . row_between_delimiter ) ; <nl> + <nl> + if ( buf . eof ( ) ) <nl> + at_beginning_of_row_or_eof = end_of_stream = true ; <nl> + } <nl> + / / / It can happen that buf . position ( ) is not at the beginning of row <nl> + / / / if some delimiters is similar to row_format . delimiters . back ( ) and row_between_delimiter . <nl> + / / / It will cause another parsing error . <nl> + } <nl> + <nl> + / / / Searches for delimiter in input stream and sets buffer position to the beginning of delimiter ( if found ) or EOF ( if not ) <nl> + void TemplateRowInputFormat : : skipToNextDelimiterOrEof ( const String & delimiter ) <nl> + { <nl> + if ( delimiter . empty ( ) ) <nl> + return ; <nl> + <nl> + while ( ! buf . eof ( ) ) <nl> + { <nl> + void * pos = memchr ( buf . position ( ) , delimiter [ 0 ] , buf . available ( ) ) ; <nl> + if ( ! pos ) <nl> + { <nl> + buf . position ( ) + = buf . available ( ) ; <nl> + continue ; <nl> + } <nl> + <nl> + buf . position ( ) = static_cast < ReadBuffer : : Position > ( pos ) ; <nl> + <nl> + PeekableReadBufferCheckpoint checkpoint { buf } ; <nl> + if ( checkString ( delimiter , buf ) ) <nl> + return ; <nl> + <nl> + buf . rollbackToCheckpoint ( ) ; <nl> + + + buf . position ( ) ; <nl> + } <nl> + } <nl> + <nl> + void TemplateRowInputFormat : : throwUnexpectedEof ( ) <nl> + { <nl> + throw Exception ( " Unexpected EOF while parsing row " + std : : to_string ( row_num ) + " . " <nl> + " Maybe last row has wrong format or input doesn ' t contain specified suffix before EOF . " , <nl> + ErrorCodes : : CANNOT_READ_ALL_DATA ) ; <nl> + } <nl> + <nl> + <nl> + void registerInputFormatProcessorTemplate ( FormatFactory & factory ) <nl> + { <nl> + for ( bool ignore_spaces : { false , true } ) <nl> + { <nl> + factory . registerInputFormatProcessor ( ignore_spaces ? " TemplateIgnoreSpaces " : " Template " , [ = ] ( <nl> + ReadBuffer & buf , <nl> + const Block & sample , <nl> + const Context & , <nl> + IRowInputFormat : : Params params , <nl> + const FormatSettings & settings ) <nl> + { <nl> + return std : : make_shared < TemplateRowInputFormat > ( sample , buf , params , settings , ignore_spaces ) ; <nl> + } ) ; <nl> + } <nl> + } <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . ff7b2adc34a <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / Impl / TemplateRowInputFormat . h <nl> <nl> + # pragma once <nl> + <nl> + # include < Core / Block . h > <nl> + # include < Processors / Formats / RowInputFormatWithDiagnosticInfo . h > <nl> + # include < Formats / FormatSettings . h > <nl> + # include < Formats / ParsedTemplateFormatString . h > <nl> + # include < IO / ReadHelpers . h > <nl> + # include < IO / PeekableReadBuffer . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + class TemplateRowInputFormat : public RowInputFormatWithDiagnosticInfo <nl> + { <nl> + using ColumnFormat = ParsedTemplateFormatString : : ColumnFormat ; <nl> + public : <nl> + TemplateRowInputFormat ( const Block & header_ , ReadBuffer & in_ , const Params & params_ , <nl> + const FormatSettings & settings_ , bool ignore_spaces_ ) ; <nl> + <nl> + String getName ( ) const override { return " TemplateRowInputFormat " ; } <nl> + <nl> + bool readRow ( MutableColumns & columns , RowReadExtension & extra ) override ; <nl> + <nl> + void readPrefix ( ) override ; <nl> + <nl> + bool allowSyncAfterError ( ) const override ; <nl> + void syncAfterError ( ) override ; <nl> + <nl> + private : <nl> + void deserializeField ( const IDataType & type , IColumn & column , ColumnFormat col_format ) ; <nl> + void skipField ( ColumnFormat col_format ) ; <nl> + inline void skipSpaces ( ) { if ( ignore_spaces ) skipWhitespaceIfAny ( buf ) ; } <nl> + <nl> + template < typename ReturnType = void > <nl> + ReturnType tryReadPrefixOrSuffix ( size_t & input_part_beg , size_t input_part_end ) ; <nl> + bool checkForSuffix ( ) ; <nl> + [ [ noreturn ] ] void throwUnexpectedEof ( ) ; <nl> + <nl> + bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) override ; <nl> + void tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , ReadBuffer : : Position & prev_pos , <nl> + ReadBuffer : : Position & curr_pos ) override ; <nl> + bool isGarbageAfterField ( size_t after_col_idx , ReadBuffer : : Position pos ) override ; <nl> + void writeErrorStringForWrongDelimiter ( WriteBuffer & out , const String & description , const String & delim ) ; <nl> + <nl> + void skipToNextDelimiterOrEof ( const String & delimiter ) ; <nl> + <nl> + private : <nl> + PeekableReadBuffer buf ; <nl> + DataTypes data_types ; <nl> + <nl> + FormatSettings settings ; <nl> + ParsedTemplateFormatString format ; <nl> + ParsedTemplateFormatString row_format ; <nl> + const bool ignore_spaces ; <nl> + <nl> + size_t format_data_idx ; <nl> + bool end_of_stream = false ; <nl> + } ; <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 452cfa46acf <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / RowInputFormatWithDiagnosticInfo . cpp <nl> <nl> + # include < Processors / Formats / RowInputFormatWithDiagnosticInfo . h > <nl> + # include < Formats / verbosePrintString . h > <nl> + # include < IO / Operators . h > <nl> + # include < IO / WriteBufferFromString . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + namespace ErrorCodes <nl> + { <nl> + extern const int LOGICAL_ERROR ; <nl> + } <nl> + <nl> + DB : : RowInputFormatWithDiagnosticInfo : : RowInputFormatWithDiagnosticInfo ( const Block & header_ , ReadBuffer & in_ , const Params & params_ ) <nl> + : IRowInputFormat ( header_ , in_ , params_ ) <nl> + { <nl> + } <nl> + <nl> + void DB : : RowInputFormatWithDiagnosticInfo : : updateDiagnosticInfo ( ) <nl> + { <nl> + + + row_num ; <nl> + <nl> + bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row ; <nl> + bytes_read_at_start_of_buffer_on_current_row = in . count ( ) - in . offset ( ) ; <nl> + <nl> + offset_of_prev_row = offset_of_current_row ; <nl> + offset_of_current_row = in . offset ( ) ; <nl> + } <nl> + <nl> + String DB : : RowInputFormatWithDiagnosticInfo : : getDiagnosticInfo ( ) <nl> + { <nl> + if ( in . eof ( ) ) / / / Buffer has gone , cannot extract information about what has been parsed . <nl> + return { } ; <nl> + <nl> + WriteBufferFromOwnString out ; <nl> + <nl> + auto & header = getPort ( ) . getHeader ( ) ; <nl> + MutableColumns columns = header . cloneEmptyColumns ( ) ; <nl> + <nl> + / / / It is possible to display detailed diagnostics only if the last and next to last rows are still in the read buffer . <nl> + size_t bytes_read_at_start_of_buffer = in . count ( ) - in . offset ( ) ; <nl> + if ( bytes_read_at_start_of_buffer ! = bytes_read_at_start_of_buffer_on_prev_row ) <nl> + { <nl> + out < < " Could not print diagnostic info because two last rows aren ' t in buffer ( rare case ) \ n " ; <nl> + return out . str ( ) ; <nl> + } <nl> + <nl> + max_length_of_column_name = 0 ; <nl> + for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> + if ( header . safeGetByPosition ( i ) . name . size ( ) > max_length_of_column_name ) <nl> + max_length_of_column_name = header . safeGetByPosition ( i ) . name . size ( ) ; <nl> + <nl> + max_length_of_data_type_name = 0 ; <nl> + for ( size_t i = 0 ; i < header . columns ( ) ; + + i ) <nl> + if ( header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) > max_length_of_data_type_name ) <nl> + max_length_of_data_type_name = header . safeGetByPosition ( i ) . type - > getName ( ) . size ( ) ; <nl> + <nl> + / / / Roll back the cursor to the beginning of the previous or current row and parse all over again . But now we derive detailed information . <nl> + <nl> + if ( offset_of_prev_row < = in . buffer ( ) . size ( ) ) <nl> + { <nl> + in . position ( ) = in . buffer ( ) . begin ( ) + offset_of_prev_row ; <nl> + <nl> + out < < " \ nRow " < < ( row_num - 1 ) < < " : \ n " ; <nl> + if ( ! parseRowAndPrintDiagnosticInfo ( columns , out ) ) <nl> + return out . str ( ) ; <nl> + } <nl> + else <nl> + { <nl> + if ( in . buffer ( ) . size ( ) < offset_of_current_row ) <nl> + { <nl> + out < < " Could not print diagnostic info because parsing of data hasn ' t started . \ n " ; <nl> + return out . str ( ) ; <nl> + } <nl> + <nl> + in . position ( ) = in . buffer ( ) . begin ( ) + offset_of_current_row ; <nl> + } <nl> + <nl> + out < < " \ nRow " < < row_num < < " : \ n " ; <nl> + parseRowAndPrintDiagnosticInfo ( columns , out ) ; <nl> + out < < " \ n " ; <nl> + <nl> + return out . str ( ) ; <nl> + } <nl> + <nl> + bool RowInputFormatWithDiagnosticInfo : : deserializeFieldAndPrintDiagnosticInfo ( const String & col_name , <nl> + const DataTypePtr & type , <nl> + IColumn & column , <nl> + WriteBuffer & out , <nl> + size_t file_column ) <nl> + { <nl> + out < < " Column " < < file_column < < " , " < < std : : string ( ( file_column < 10 ? 2 : file_column < 100 ? 1 : 0 ) , ' ' ) <nl> + < < " name : " < < alignedName ( col_name , max_length_of_column_name ) <nl> + < < " type : " < < alignedName ( type - > getName ( ) , max_length_of_data_type_name ) ; <nl> + <nl> + auto prev_position = in . position ( ) ; <nl> + auto curr_position = in . position ( ) ; <nl> + std : : exception_ptr exception ; <nl> + <nl> + try <nl> + { <nl> + tryDeserializeFiled ( type , column , file_column , prev_position , curr_position ) ; <nl> + } <nl> + catch ( . . . ) <nl> + { <nl> + exception = std : : current_exception ( ) ; <nl> + } <nl> + <nl> + if ( curr_position < prev_position ) <nl> + throw Exception ( " Logical error : parsing is non - deterministic . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + <nl> + if ( isNativeNumber ( type ) | | isDateOrDateTime ( type ) ) <nl> + { <nl> + / / / An empty string instead of a value . <nl> + if ( curr_position = = prev_position ) <nl> + { <nl> + out < < " ERROR : text " ; <nl> + verbosePrintString ( prev_position , std : : min ( prev_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> + out < < " is not like " < < type - > getName ( ) < < " \ n " ; <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + out < < " parsed text : " ; <nl> + verbosePrintString ( prev_position , curr_position , out ) ; <nl> + <nl> + if ( exception ) <nl> + { <nl> + if ( type - > getName ( ) = = " DateTime " ) <nl> + out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> + else if ( type - > getName ( ) = = " Date " ) <nl> + out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> + else <nl> + out < < " ERROR \ n " ; <nl> + return false ; <nl> + } <nl> + <nl> + out < < " \ n " ; <nl> + <nl> + if ( type - > haveMaximumSizeOfValue ( ) ) <nl> + { <nl> + if ( isGarbageAfterField ( file_column , curr_position ) ) <nl> + { <nl> + out < < " ERROR : garbage after " < < type - > getName ( ) < < " : " ; <nl> + verbosePrintString ( curr_position , std : : min ( curr_position + 10 , in . buffer ( ) . end ( ) ) , out ) ; <nl> + out < < " \ n " ; <nl> + <nl> + if ( type - > getName ( ) = = " DateTime " ) <nl> + out < < " ERROR : DateTime must be in YYYY - MM - DD hh : mm : ss or NNNNNNNNNN ( unix timestamp , exactly 10 digits ) format . \ n " ; <nl> + else if ( type - > getName ( ) = = " Date " ) <nl> + out < < " ERROR : Date must be in YYYY - MM - DD format . \ n " ; <nl> + <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + String RowInputFormatWithDiagnosticInfo : : alignedName ( const String & name , size_t max_length ) const <nl> + { <nl> + size_t spaces_count = max_length > = name . size ( ) ? max_length - name . size ( ) : 0 ; <nl> + return name + " , " + std : : string ( spaces_count , ' ' ) ; <nl> + } <nl> + <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 98dea066436 <nl> mmm / dev / null <nl> ppp b / dbms / src / Processors / Formats / RowInputFormatWithDiagnosticInfo . h <nl> <nl> + # pragma once <nl> + <nl> + # include < Core / Block . h > <nl> + # include < Processors / Formats / IRowInputFormat . h > <nl> + # include < IO / ReadBuffer . h > <nl> + # include < limits > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + class RowInputFormatWithDiagnosticInfo : public IRowInputFormat <nl> + { <nl> + public : <nl> + RowInputFormatWithDiagnosticInfo ( const Block & header_ , ReadBuffer & in_ , const Params & params_ ) ; <nl> + <nl> + String getDiagnosticInfo ( ) override ; <nl> + <nl> + protected : <nl> + void updateDiagnosticInfo ( ) ; <nl> + bool deserializeFieldAndPrintDiagnosticInfo ( const String & col_name , const DataTypePtr & type , IColumn & column , <nl> + WriteBuffer & out , size_t file_column ) ; <nl> + String alignedName ( const String & name , size_t max_length ) const ; <nl> + <nl> + virtual bool parseRowAndPrintDiagnosticInfo ( MutableColumns & columns , WriteBuffer & out ) = 0 ; <nl> + virtual void tryDeserializeFiled ( const DataTypePtr & type , IColumn & column , size_t file_column , <nl> + ReadBuffer : : Position & prev_pos , ReadBuffer : : Position & curr_pos ) = 0 ; <nl> + virtual bool isGarbageAfterField ( size_t after_input_pos_idx , ReadBuffer : : Position pos ) = 0 ; <nl> + <nl> + / / / For convenient diagnostics in case of an error . <nl> + size_t row_num = 0 ; <nl> + <nl> + private : <nl> + / / / How many bytes were read , not counting those still in the buffer . <nl> + size_t bytes_read_at_start_of_buffer_on_current_row = 0 ; <nl> + size_t bytes_read_at_start_of_buffer_on_prev_row = 0 ; <nl> + <nl> + size_t offset_of_current_row = std : : numeric_limits < size_t > : : max ( ) ; <nl> + size_t offset_of_prev_row = std : : numeric_limits < size_t > : : max ( ) ; <nl> + <nl> + / / / For alignment of diagnostic info . <nl> + size_t max_length_of_column_name = 0 ; <nl> + size_t max_length_of_data_type_name = 0 ; <nl> + } ; <nl> + <nl> + } <nl> mmm a / dbms / src / Storages / AlterCommands . cpp <nl> ppp b / dbms / src / Storages / AlterCommands . cpp <nl> void AlterCommands : : validate ( const IStorage & table , const Context & context ) <nl> } <nl> } <nl> else if ( command . type = = AlterCommand : : MODIFY_SETTING ) <nl> - { <nl> for ( const auto & change : command . settings_changes ) <nl> - { <nl> - if ( ! table . hasSetting ( change . name ) ) <nl> - { <nl> - throw Exception { " Storage ' " + table . getName ( ) + " ' doesn ' t have setting ' " + change . name + " ' " , ErrorCodes : : UNKNOWN_SETTING } ; <nl> - } <nl> - } <nl> - } <nl> + table . checkSettingCanBeChanged ( change . name ) ; <nl> } <nl> <nl> / * * Existing defaulted columns may require default expression extensions with a type conversion , <nl> mmm a / dbms / src / Storages / IStorage . cpp <nl> ppp b / dbms / src / Storages / IStorage . cpp <nl> bool IStorage : : isVirtualColumn ( const String & column_name ) const <nl> return getColumns ( ) . get ( column_name ) . is_virtual ; <nl> } <nl> <nl> - bool IStorage : : hasSetting ( const String & / * setting_name * / ) const <nl> + void IStorage : : checkSettingCanBeChanged ( const String & / * setting_name * / ) const <nl> { <nl> if ( ! supportsSettings ( ) ) <nl> throw Exception ( " Storage ' " + getName ( ) + " ' doesn ' t support settings . " , ErrorCodes : : SETTINGS_ARE_NOT_SUPPORTED ) ; <nl> - return false ; <nl> } <nl> <nl> TableStructureReadLockHolder IStorage : : lockStructureForShare ( bool will_add_new_data , const String & query_id ) <nl> IDatabase : : ASTModifier IStorage : : getSettingsModifier ( const SettingsChanges & new <nl> / / / Make storage settings unique <nl> for ( const auto & change : new_changes ) <nl> { <nl> - if ( hasSetting ( change . name ) ) <nl> - { <nl> - auto finder = [ & change ] ( const SettingChange & c ) { return c . name = = change . name ; } ; <nl> - if ( auto it = std : : find_if ( storage_changes . begin ( ) , storage_changes . end ( ) , finder ) ; it ! = storage_changes . end ( ) ) <nl> - it - > value = change . value ; <nl> - else <nl> - storage_changes . push_back ( change ) ; <nl> - } <nl> + checkSettingCanBeChanged ( change . name ) ; <nl> + <nl> + auto finder = [ & change ] ( const SettingChange & c ) { return c . name = = change . name ; } ; <nl> + if ( auto it = std : : find_if ( storage_changes . begin ( ) , storage_changes . end ( ) , finder ) ; it ! = storage_changes . end ( ) ) <nl> + it - > value = change . value ; <nl> else <nl> - throw Exception { " Storage ' " + getName ( ) + " ' doesn ' t have setting ' " + change . name + " ' " , ErrorCodes : : UNKNOWN_SETTING } ; <nl> + storage_changes . push_back ( change ) ; <nl> } <nl> } <nl> } ; <nl> mmm a / dbms / src / Storages / IStorage . h <nl> ppp b / dbms / src / Storages / IStorage . h <nl> class IStorage : public std : : enable_shared_from_this < IStorage > <nl> / / / If | need_all | is set , then checks that all the columns of the table are in the block . <nl> void check ( const Block & block , bool need_all = false ) const ; <nl> <nl> - / / / Check storage has setting . Exception will be thrown if it doesn ' t support settings at all . <nl> - virtual bool hasSetting ( const String & setting_name ) const ; <nl> + / / / Check storage has setting and setting can be modified . <nl> + virtual void checkSettingCanBeChanged ( const String & setting_name ) const ; <nl> <nl> protected : / / / still thread - unsafe part . <nl> void setIndices ( IndicesDescription indices_ ) ; <nl> class IStorage : public std : : enable_shared_from_this < IStorage > <nl> virtual bool isVirtualColumn ( const String & column_name ) const ; <nl> <nl> / / / Returns modifier of settings in storage definition <nl> - virtual IDatabase : : ASTModifier getSettingsModifier ( const SettingsChanges & new_changes ) const ; <nl> + IDatabase : : ASTModifier getSettingsModifier ( const SettingsChanges & new_changes ) const ; <nl> <nl> private : <nl> ColumnsDescription columns ; / / / combined real and virtual columns <nl> mmm a / dbms / src / Storages / Kafka / KafkaSettings . cpp <nl> ppp b / dbms / src / Storages / Kafka / KafkaSettings . cpp <nl> void KafkaSettings : : loadFromQuery ( ASTStorage & storage_def ) <nl> { <nl> try <nl> { <nl> - loadFromChanges ( storage_def . settings - > changes ) ; <nl> + applyChanges ( storage_def . settings - > changes ) ; <nl> } <nl> catch ( Exception & e ) <nl> { <nl> mmm a / dbms / src / Storages / Kafka / KafkaSettings . h <nl> ppp b / dbms / src / Storages / Kafka / KafkaSettings . h <nl> struct KafkaSettings : public SettingsCollection < KafkaSettings > <nl> { <nl> <nl> <nl> - / / / M ( mutable ) for normal settings , IM ( immutable ) for not updateable settings . <nl> - # define LIST_OF_KAFKA_SETTINGS ( M , IM ) \ <nl> - IM ( SettingString , kafka_broker_list , " " , " A comma - separated list of brokers for Kafka engine . " ) \ <nl> - IM ( SettingString , kafka_topic_list , " " , " A list of Kafka topics . " ) \ <nl> - IM ( SettingString , kafka_group_name , " " , " A group of Kafka consumers . " ) \ <nl> - IM ( SettingString , kafka_format , " " , " The message format for Kafka engine . " ) \ <nl> - IM ( SettingChar , kafka_row_delimiter , ' \ 0 ' , " The character to be considered as a delimiter in Kafka message . " ) \ <nl> - IM ( SettingString , kafka_schema , " " , " Schema identifier ( used by schema - based formats ) for Kafka engine " ) \ <nl> - IM ( SettingUInt64 , kafka_num_consumers , 1 , " The number of consumers per table for Kafka engine . " ) \ <nl> - IM ( SettingUInt64 , kafka_max_block_size , 0 , " The maximum block size per table for Kafka engine . " ) \ <nl> - IM ( SettingUInt64 , kafka_skip_broken_messages , 0 , " Skip at least this number of broken messages from Kafka topic per block " ) \ <nl> - IM ( SettingUInt64 , kafka_commit_every_batch , 0 , " Commit every consumed and handled batch instead of a single commit after writing a whole block " ) <nl> + # define LIST_OF_KAFKA_SETTINGS ( M ) \ <nl> + M ( SettingString , kafka_broker_list , " " , " A comma - separated list of brokers for Kafka engine . " ) \ <nl> + M ( SettingString , kafka_topic_list , " " , " A list of Kafka topics . " ) \ <nl> + M ( SettingString , kafka_group_name , " " , " A group of Kafka consumers . " ) \ <nl> + M ( SettingString , kafka_format , " " , " The message format for Kafka engine . " ) \ <nl> + M ( SettingChar , kafka_row_delimiter , ' \ 0 ' , " The character to be considered as a delimiter in Kafka message . " ) \ <nl> + M ( SettingString , kafka_schema , " " , " Schema identifier ( used by schema - based formats ) for Kafka engine " ) \ <nl> + M ( SettingUInt64 , kafka_num_consumers , 1 , " The number of consumers per table for Kafka engine . " ) \ <nl> + M ( SettingUInt64 , kafka_max_block_size , 0 , " The maximum block size per table for Kafka engine . " ) \ <nl> + M ( SettingUInt64 , kafka_skip_broken_messages , 0 , " Skip at least this number of broken messages from Kafka topic per block " ) \ <nl> + M ( SettingUInt64 , kafka_commit_every_batch , 0 , " Commit every consumed and handled batch instead of a single commit after writing a whole block " ) <nl> <nl> DECLARE_SETTINGS_COLLECTION ( LIST_OF_KAFKA_SETTINGS ) <nl> <nl> mmm a / dbms / src / Storages / Kafka / StorageKafka . cpp <nl> ppp b / dbms / src / Storages / Kafka / StorageKafka . cpp <nl> namespace ErrorCodes <nl> extern const int BAD_ARGUMENTS ; <nl> extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH ; <nl> extern const int UNSUPPORTED_METHOD ; <nl> + extern const int UNKNOWN_SETTING ; <nl> + extern const int READONLY_SETTING ; <nl> } <nl> <nl> namespace <nl> bool StorageKafka : : streamToViews ( ) <nl> } <nl> <nl> <nl> - bool StorageKafka : : hasSetting ( const String & setting_name ) const <nl> + void StorageKafka : : checkSettingCanBeChanged ( const String & setting_name ) const <nl> { <nl> - return KafkaSettings : : findIndex ( setting_name ) ! = KafkaSettings : : npos ; <nl> - } <nl> + if ( KafkaSettings : : findIndex ( setting_name ) = = KafkaSettings : : npos ) <nl> + throw Exception { " Storage ' " + getName ( ) + " ' doesn ' t have setting ' " + setting_name + " ' " , ErrorCodes : : UNKNOWN_SETTING } ; <nl> <nl> - IDatabase : : ASTModifier StorageKafka : : getSettingsModifier ( const SettingsChanges & / * new_changes * / ) const <nl> - { <nl> - throw Exception ( " Storage ' " + getName ( ) + " ' doesn ' t support settings alter " , ErrorCodes : : UNSUPPORTED_METHOD ) ; <nl> + throw Exception { " Setting ' " + setting_name + " ' is readonly for storage ' " + getName ( ) + " ' " , ErrorCodes : : READONLY_SETTING } ; <nl> } <nl> <nl> void registerStorageKafka ( StorageFactory & factory ) <nl> mmm a / dbms / src / Storages / Kafka / StorageKafka . h <nl> ppp b / dbms / src / Storages / Kafka / StorageKafka . h <nl> class StorageKafka : public ext : : shared_ptr_helper < StorageKafka > , public IStorag <nl> const auto & getSchemaName ( ) const { return schema_name ; } <nl> const auto & skipBroken ( ) const { return skip_broken ; } <nl> <nl> - bool hasSetting ( const String & setting_name ) const override ; <nl> - <nl> + void checkSettingCanBeChanged ( const String & setting_name ) const override ; <nl> <nl> protected : <nl> StorageKafka ( <nl> class StorageKafka : public ext : : shared_ptr_helper < StorageKafka > , public IStorag <nl> size_t num_consumers_ , UInt64 max_block_size_ , size_t skip_broken , <nl> bool intermediate_commit_ ) ; <nl> <nl> - IDatabase : : ASTModifier getSettingsModifier ( const SettingsChanges & new_changes ) const override ; <nl> private : <nl> / / Configuration and state <nl> String table_name ; <nl> mmm a / dbms / src / Storages / LiveView / StorageLiveView . cpp <nl> ppp b / dbms / src / Storages / LiveView / StorageLiveView . cpp <nl> void registerStorageLiveView ( StorageFactory & factory ) <nl> { <nl> factory . registerStorage ( " LiveView " , [ ] ( const StorageFactory : : Arguments & args ) <nl> { <nl> - if ( ! args . local_context . getSettingsRef ( ) . allow_experimental_live_view ) <nl> + if ( ! args . attach & & ! args . local_context . getSettingsRef ( ) . allow_experimental_live_view ) <nl> throw Exception ( " Experimental LIVE VIEW feature is not enabled ( the setting ' allow_experimental_live_view ' ) " , ErrorCodes : : SUPPORT_IS_DISABLED ) ; <nl> <nl> return StorageLiveView : : create ( args . table_name , args . database_name , args . local_context , args . query , args . columns ) ; <nl> mmm a / dbms / src / Storages / MergeTree / IMergedBlockOutputStream . cpp <nl> ppp b / dbms / src / Storages / MergeTree / IMergedBlockOutputStream . cpp <nl> void IMergedBlockOutputStream : : calculateAndSerializeSkipIndices ( <nl> { <nl> / / / Creating block for update <nl> Block indices_update_block ( skip_indexes_columns ) ; <nl> - size_t skip_index_current_mark = 0 ; <nl> + size_t skip_index_current_data_mark = 0 ; <nl> <nl> / / / Filling and writing skip indices like in IMergedBlockOutputStream : : writeColumn <nl> for ( size_t i = 0 ; i < skip_indices . size ( ) ; + + i ) <nl> void IMergedBlockOutputStream : : calculateAndSerializeSkipIndices ( <nl> const auto index = skip_indices [ i ] ; <nl> auto & stream = * skip_indices_streams [ i ] ; <nl> size_t prev_pos = 0 ; <nl> - skip_index_current_mark = skip_index_mark ; <nl> + skip_index_current_data_mark = skip_index_data_mark ; <nl> while ( prev_pos < rows ) <nl> { <nl> UInt64 limit = 0 ; <nl> void IMergedBlockOutputStream : : calculateAndSerializeSkipIndices ( <nl> } <nl> else <nl> { <nl> - limit = index_granularity . getMarkRows ( skip_index_current_mark ) ; <nl> + limit = index_granularity . getMarkRows ( skip_index_current_data_mark ) ; <nl> if ( skip_indices_aggregators [ i ] - > empty ( ) ) <nl> { <nl> skip_indices_aggregators [ i ] = index - > createIndexAggregator ( ) ; <nl> void IMergedBlockOutputStream : : calculateAndSerializeSkipIndices ( <nl> / / / to be compatible with normal . mrk2 file format <nl> if ( can_use_adaptive_granularity ) <nl> writeIntBinary ( 1UL , stream . marks ) ; <nl> - <nl> - + + skip_index_current_mark ; <nl> } <nl> + / / / this mark is aggregated , go to the next one <nl> + skip_index_current_data_mark + + ; <nl> } <nl> <nl> size_t pos = prev_pos ; <nl> void IMergedBlockOutputStream : : calculateAndSerializeSkipIndices ( <nl> prev_pos = pos ; <nl> } <nl> } <nl> - skip_index_mark = skip_index_current_mark ; <nl> + skip_index_data_mark = skip_index_current_data_mark ; <nl> } <nl> <nl> void IMergedBlockOutputStream : : finishSkipIndicesSerialization ( <nl> mmm a / dbms / src / Storages / MergeTree / IMergedBlockOutputStream . h <nl> ppp b / dbms / src / Storages / MergeTree / IMergedBlockOutputStream . h <nl> class IMergedBlockOutputStream : public IBlockOutputStream <nl> size_t aio_threshold ; <nl> <nl> size_t current_mark = 0 ; <nl> - size_t skip_index_mark = 0 ; <nl> + <nl> + / / / Number of mark in data from which skip indices have to start <nl> + / / / aggregation . I . e . it ' s data mark number , not skip indices mark . <nl> + size_t skip_index_data_mark = 0 ; <nl> <nl> const bool can_use_adaptive_granularity ; <nl> const std : : string marks_file_extension ; <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> namespace ErrorCodes <nl> extern const int INCORRECT_FILE_NAME ; <nl> extern const int BAD_DATA_PART_NAME ; <nl> extern const int UNKNOWN_SETTING ; <nl> + extern const int READONLY_SETTING ; <nl> } <nl> <nl> <nl> void MergeTreeData : : checkAlter ( const AlterCommands & commands , const Context & c <nl> setTTLExpressions ( new_columns . getColumnTTLs ( ) , new_ttl_table_ast , / * only_check = * / true ) ; <nl> <nl> for ( const auto & setting : new_changes ) <nl> - { <nl> - if ( ! hasSetting ( setting . name ) ) <nl> - throw Exception { " Storage ' " + getName ( ) + " ' doesn ' t have setting ' " + setting . name + " ' " , ErrorCodes : : UNKNOWN_SETTING } ; <nl> - } <nl> + checkSettingCanBeChanged ( setting . name ) ; <nl> <nl> / / / Check that type conversions are possible . <nl> ExpressionActionsPtr unused_expression ; <nl> void MergeTreeData : : changeSettings ( <nl> if ( ! new_changes . empty ( ) ) <nl> { <nl> MergeTreeSettings copy = * getSettings ( ) ; <nl> - copy . updateFromChanges ( new_changes ) ; <nl> + copy . applyChanges ( new_changes ) ; <nl> storage_settings . set ( std : : make_unique < const MergeTreeSettings > ( copy ) ) ; <nl> } <nl> } <nl> <nl> - bool MergeTreeData : : hasSetting ( const String & setting_name ) const <nl> + void MergeTreeData : : checkSettingCanBeChanged ( const String & setting_name ) const <nl> { <nl> - return MergeTreeSettings : : findIndex ( setting_name ) ! = MergeTreeSettings : : npos ; <nl> + if ( MergeTreeSettings : : findIndex ( setting_name ) = = MergeTreeSettings : : npos ) <nl> + throw Exception { " Storage ' " + getName ( ) + " ' doesn ' t have setting ' " + setting_name + " ' " , ErrorCodes : : UNKNOWN_SETTING } ; <nl> + if ( MergeTreeSettings : : isReadonlySetting ( setting_name ) ) <nl> + throw Exception { " Setting ' " + setting_name + " ' is readonly for storage ' " + getName ( ) + " ' " , ErrorCodes : : READONLY_SETTING } ; <nl> + <nl> } <nl> <nl> void MergeTreeData : : removeEmptyColumnsFromPart ( MergeTreeData : : MutableDataPartPtr & data_part ) <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeData . h <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeData . h <nl> class MergeTreeData : public IStorage <nl> TableStructureWriteLockHolder & table_lock_holder ) ; <nl> <nl> / / / All MergeTreeData children have settings . <nl> - bool hasSetting ( const String & setting_name ) const override ; <nl> + void checkSettingCanBeChanged ( const String & setting_name ) const override ; <nl> <nl> / / / Remove columns , that have been markedd as empty after zeroing values with expired ttl <nl> void removeEmptyColumnsFromPart ( MergeTreeData : : MutableDataPartPtr & data_part ) ; <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataMergerMutator . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataMergerMutator . cpp <nl> MergeTreeData : : MutableDataPartPtr MergeTreeDataMergerMutator : : mergePartsToTempor <nl> NamesAndTypesList all_columns = data . getColumns ( ) . getAllPhysical ( ) ; <nl> const auto data_settings = data . getSettings ( ) ; <nl> <nl> - NamesAndTypesList gathering_columns , merging_columns ; <nl> + NamesAndTypesList gathering_columns ; <nl> + NamesAndTypesList merging_columns ; <nl> Names gathering_column_names , merging_column_names ; <nl> extractMergingAndGatheringColumns ( <nl> all_columns , data . sorting_key_expr , data . skip_indices , <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeSettings . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeSettings . cpp <nl> void MergeTreeSettings : : loadFromQuery ( ASTStorage & storage_def ) <nl> { <nl> try <nl> { <nl> - loadFromChanges ( storage_def . settings - > changes ) ; <nl> + applyChanges ( storage_def . settings - > changes ) ; <nl> } <nl> catch ( Exception & e ) <nl> { <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeSettings . h <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeSettings . h <nl> <nl> <nl> # include < Core / Defines . h > <nl> # include < Core / SettingsCommon . h > <nl> + # include < Common / SettingsChanges . h > <nl> <nl> <nl> namespace Poco <nl> class ASTStorage ; <nl> struct MergeTreeSettings : public SettingsCollection < MergeTreeSettings > <nl> { <nl> <nl> - / / / M ( mutable ) for normal settings , IM ( immutable ) for not updateable settings . <nl> - # define LIST_OF_MERGE_TREE_SETTINGS ( M , IM ) \ <nl> - IM ( SettingUInt64 , index_granularity , 8192 , " How many rows correspond to one primary key value . " ) \ <nl> + # define LIST_OF_MERGE_TREE_SETTINGS ( M ) \ <nl> + M ( SettingUInt64 , index_granularity , 8192 , " How many rows correspond to one primary key value . " ) \ <nl> \ <nl> / * * Merge settings . * / \ <nl> M ( SettingUInt64 , max_bytes_to_merge_at_max_space_in_pool , 150ULL * 1024 * 1024 * 1024 , " Maximum in total size of parts to merge , when there are maximum free threads in background pool ( or entries in replication queue ) . " ) \ <nl> struct MergeTreeSettings : public SettingsCollection < MergeTreeSettings > <nl> M ( SettingBool , use_minimalistic_part_header_in_zookeeper , false , " Store part header ( checksums and columns ) in a compact format and a single part znode instead of separate znodes ( < part > / columns and < part > / checksums ) . This can dramatically reduce snapshot size in ZooKeeper . Before enabling check that all replicas support new format . " ) \ <nl> M ( SettingUInt64 , finished_mutations_to_keep , 100 , " How many records about mutations that are done to keep . If zero , then keep all of them . " ) \ <nl> M ( SettingUInt64 , min_merge_bytes_to_use_direct_io , 10ULL * 1024 * 1024 * 1024 , " Minimal amount of bytes to enable O_DIRECT in merge ( 0 - disabled ) . " ) \ <nl> - IM ( SettingUInt64 , index_granularity_bytes , 10 * 1024 * 1024 , " Approximate amount of bytes in single granule ( 0 - disabled ) . " ) \ <nl> + M ( SettingUInt64 , index_granularity_bytes , 10 * 1024 * 1024 , " Approximate amount of bytes in single granule ( 0 - disabled ) . " ) \ <nl> M ( SettingInt64 , merge_with_ttl_timeout , 3600 * 24 , " Minimal time in seconds , when merge with TTL can be repeated . " ) \ <nl> M ( SettingBool , ttl_only_drop_parts , false , " Only drop altogether the expired parts and not partially prune them . " ) \ <nl> M ( SettingBool , write_final_mark , 1 , " Write final mark after end of column ( 0 - disabled , do nothing if index_granularity_bytes = 0 ) " ) \ <nl> struct MergeTreeSettings : public SettingsCollection < MergeTreeSettings > <nl> <nl> / / / NOTE : will rewrite the AST to add immutable settings . <nl> void loadFromQuery ( ASTStorage & storage_def ) ; <nl> + <nl> + / / / We check settings after storage creation <nl> + static bool isReadonlySetting ( const String & name ) <nl> + { <nl> + return name = = " index_granularity " | | name = = " index_granularity_bytes " ; <nl> + } <nl> } ; <nl> <nl> using MergeTreeSettingsPtr = std : : shared_ptr < const MergeTreeSettings > ; <nl> mmm a / dbms / src / Storages / MergeTree / MergedBlockOutputStream . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergedBlockOutputStream . cpp <nl> void MergedBlockOutputStream : : writeImpl ( const Block & block , const IColumn : : Perm <nl> else if ( skip_indexes_column_name_to_position . end ( ) ! = skip_index_column_it ) <nl> { <nl> const auto & index_column = * skip_indexes_columns [ skip_index_column_it - > second ] . column ; <nl> - writeColumn ( column . name , * column . type , index_column , offset_columns , false , serialization_states [ i ] , current_mark ) ; <nl> + std : : tie ( std : : ignore , new_index_offset ) = writeColumn ( column . name , * column . type , index_column , offset_columns , false , serialization_states [ i ] , current_mark ) ; <nl> } <nl> else <nl> { <nl> void MergedBlockOutputStream : : writeImpl ( const Block & block , const IColumn : : Perm <nl> <nl> rows_count + = rows ; <nl> <nl> + / / / Should be written before index offset update , because we calculate , <nl> + / / / indices of currently written granules <nl> calculateAndSerializeSkipIndices ( skip_indexes_columns , rows ) ; <nl> <nl> { <nl> mmm a / dbms / src / Storages / MergeTree / MergedColumnOnlyOutputStream . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergedColumnOnlyOutputStream . cpp <nl> void MergedColumnOnlyOutputStream : : write ( const Block & block ) <nl> if ( ! rows ) <nl> return ; <nl> <nl> - calculateAndSerializeSkipIndices ( skip_indexes_columns , rows ) ; <nl> <nl> size_t new_index_offset = 0 ; <nl> size_t new_current_mark = 0 ; <nl> void MergedColumnOnlyOutputStream : : write ( const Block & block ) <nl> std : : tie ( new_current_mark , new_index_offset ) = writeColumn ( column . name , * column . type , * column . column , offset_columns , skip_offsets , serialization_states [ i ] , current_mark ) ; <nl> } <nl> <nl> + / / / Should be written before index offset update , because we calculate , <nl> + / / / indices of currently written granules <nl> + calculateAndSerializeSkipIndices ( skip_indexes_columns , rows ) ; <nl> + <nl> index_offset = new_index_offset ; <nl> current_mark = new_current_mark ; <nl> } <nl> MergeTreeData : : DataPart : : Checksums MergedColumnOnlyOutputStream : : writeSuffixAndG <nl> serialize_settings . getter = createStreamGetter ( column . name , already_written_offset_columns , skip_offsets ) ; <nl> column . type - > serializeBinaryBulkStateSuffix ( serialize_settings , serialization_states [ i ] ) ; <nl> <nl> - <nl> if ( with_final_mark ) <nl> writeFinalMark ( column . name , column . type , offset_columns , skip_offsets , serialize_settings . path ) ; <nl> } <nl> mmm a / dbms / src / Storages / System / StorageSystemDictionaries . cpp <nl> ppp b / dbms / src / Storages / System / StorageSystemDictionaries . cpp <nl> void StorageSystemDictionaries : : fillData ( MutableColumns & res_columns , const Con <nl> res_columns [ i + + ] - > insert ( static_cast < Int8 > ( load_result . status ) ) ; <nl> res_columns [ i + + ] - > insert ( load_result . origin ) ; <nl> <nl> - if ( load_result . object ) <nl> - { <nl> - const auto dict_ptr = std : : static_pointer_cast < const IDictionaryBase > ( load_result . object ) ; <nl> + std : : exception_ptr last_exception = load_result . exception ; <nl> <nl> + const auto dict_ptr = std : : dynamic_pointer_cast < const IDictionaryBase > ( load_result . object ) ; <nl> + if ( dict_ptr ) <nl> + { <nl> res_columns [ i + + ] - > insert ( dict_ptr - > getTypeName ( ) ) ; <nl> <nl> const auto & dict_struct = dict_ptr - > getStructure ( ) ; <nl> void StorageSystemDictionaries : : fillData ( MutableColumns & res_columns , const Con <nl> res_columns [ i + + ] - > insert ( dict_ptr - > getElementCount ( ) ) ; <nl> res_columns [ i + + ] - > insert ( dict_ptr - > getLoadFactor ( ) ) ; <nl> res_columns [ i + + ] - > insert ( dict_ptr - > getSource ( ) - > toString ( ) ) ; <nl> + <nl> + if ( ! last_exception ) <nl> + last_exception = dict_ptr - > getLastException ( ) ; <nl> } <nl> else <nl> { <nl> void StorageSystemDictionaries : : fillData ( MutableColumns & res_columns , const Con <nl> res_columns [ i + + ] - > insert ( static_cast < UInt64 > ( std : : chrono : : system_clock : : to_time_t ( load_result . loading_start_time ) ) ) ; <nl> res_columns [ i + + ] - > insert ( std : : chrono : : duration_cast < std : : chrono : : duration < float > > ( load_result . loading_duration ) . count ( ) ) ; <nl> <nl> - if ( load_result . exception ) <nl> - res_columns [ i + + ] - > insert ( getExceptionMessage ( load_result . exception , false ) ) ; <nl> + if ( last_exception ) <nl> + res_columns [ i + + ] - > insert ( getExceptionMessage ( last_exception , false ) ) ; <nl> else <nl> res_columns [ i + + ] - > insertDefault ( ) ; <nl> } <nl> mmm a / dbms / src / Storages / System / StorageSystemProcesses . cpp <nl> ppp b / dbms / src / Storages / System / StorageSystemProcesses . cpp <nl> NamesAndTypesList StorageSystemProcesses : : getNamesAndTypes ( ) <nl> { " query " , std : : make_shared < DataTypeString > ( ) } , <nl> <nl> { " thread_numbers " , std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt32 > ( ) ) } , <nl> + { " os_thread_ids " , std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt32 > ( ) ) } , <nl> { " ProfileEvents . Names " , std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeString > ( ) ) } , <nl> { " ProfileEvents . Values " , std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeUInt64 > ( ) ) } , <nl> { " Settings . Names " , std : : make_shared < DataTypeArray > ( std : : make_shared < DataTypeString > ( ) ) } , <nl> void StorageSystemProcesses : : fillData ( MutableColumns & res_columns , const Contex <nl> res_columns [ i + + ] - > insert ( threads_array ) ; <nl> } <nl> <nl> + { <nl> + Array threads_array ; <nl> + threads_array . reserve ( process . os_thread_ids . size ( ) ) ; <nl> + for ( const UInt32 thread_number : process . os_thread_ids ) <nl> + threads_array . emplace_back ( thread_number ) ; <nl> + res_columns [ i + + ] - > insert ( threads_array ) ; <nl> + } <nl> + <nl> { <nl> IColumn * column_profile_events_names = res_columns [ i + + ] . get ( ) ; <nl> IColumn * column_profile_events_values = res_columns [ i + + ] . get ( ) ; <nl> deleted file mode 100644 <nl> index 8f1b0e23a85 . . 00000000000 <nl> mmm a / dbms / tests / integration / test_dictionaries / configs / dictionaries / . gitignore <nl> ppp / dev / null <nl> <nl> - * <nl> - ! . gitignore <nl> - ! source . tsv <nl> - ! dictionary_preset * <nl> \ No newline at end of file <nl> deleted file mode 100644 <nl> index 251fe7f31ee . . 00000000000 <nl> mmm a / dbms / tests / integration / test_dictionaries / test . py <nl> ppp / dev / null <nl> <nl> - import pytest <nl> - import os <nl> - import time <nl> - <nl> - from helpers . cluster import ClickHouseCluster <nl> - from helpers . test_tools import TSV , assert_eq_with_retry <nl> - from generate_dictionaries import generate_structure , generate_dictionaries , DictionaryTestTable <nl> - <nl> - SCRIPT_DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - <nl> - cluster = None <nl> - instance = None <nl> - test_table = None <nl> - <nl> - <nl> - def get_status ( dictionary_name ) : <nl> - return instance . query ( " SELECT status FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) <nl> - <nl> - <nl> - def get_loading_start_time ( dictionary_name ) : <nl> - s = instance . query ( " SELECT loading_start_time FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) <nl> - if s = = " 0000 - 00 - 00 00 : 00 : 00 " : <nl> - return None <nl> - return time . strptime ( s , " % Y - % m - % d % H : % M : % S " ) <nl> - <nl> - <nl> - def get_loading_duration ( dictionary_name ) : <nl> - return float ( instance . query ( " SELECT loading_duration FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) ) <nl> - <nl> - <nl> - def replace_in_file_in_container ( file_name , what , replace_with ) : <nl> - instance . exec_in_container ( ' sed - i " s / ' + what + ' / ' + replace_with + ' / g " ' + file_name ) <nl> - <nl> - <nl> - def setup_module ( module ) : <nl> - global cluster <nl> - global instance <nl> - global test_table <nl> - <nl> - structure = generate_structure ( ) <nl> - dictionary_files = generate_dictionaries ( os . path . join ( SCRIPT_DIR , ' configs / dictionaries ' ) , structure ) <nl> - <nl> - cluster = ClickHouseCluster ( __file__ , base_configs_dir = os . path . join ( SCRIPT_DIR , ' configs ' ) ) <nl> - instance = cluster . add_instance ( ' instance ' , main_configs = dictionary_files ) <nl> - test_table = DictionaryTestTable ( os . path . join ( SCRIPT_DIR , ' configs / dictionaries / source . tsv ' ) ) <nl> - <nl> - <nl> - @ pytest . fixture ( scope = " module " ) <nl> - def started_cluster ( ) : <nl> - try : <nl> - cluster . start ( ) <nl> - instance . query ( " CREATE DATABASE IF NOT EXISTS dict ENGINE = Dictionary " ) <nl> - test_table . create_clickhouse_source ( instance ) <nl> - for line in TSV ( instance . query ( ' select name from system . dictionaries ' ) ) . lines : <nl> - print line , <nl> - <nl> - # Create table ` test . small_dict_source ` <nl> - instance . query ( ' ' ' <nl> - drop table if exists test . small_dict_source ; <nl> - create table test . small_dict_source ( id UInt64 , a String , b Int32 , c Float64 ) engine = Log ; <nl> - insert into test . small_dict_source values ( 0 , ' water ' , 10 , 1 ) , ( 1 , ' air ' , 40 , 0 . 01 ) , ( 2 , ' earth ' , 100 , 1 . 7 ) ; <nl> - ' ' ' ) <nl> - <nl> - yield cluster <nl> - <nl> - finally : <nl> - cluster . shutdown ( ) <nl> - <nl> - <nl> - @ pytest . fixture ( params = [ <nl> - # name , keys , use_parent <nl> - ( ' clickhouse_hashed ' , ( ' id ' , ) , True ) , <nl> - ( ' clickhouse_flat ' , ( ' id ' , ) , True ) , <nl> - ( ' clickhouse_complex_integers_key_hashed ' , ( ' key0 ' , ' key1 ' ) , False ) , <nl> - ( ' clickhouse_complex_mixed_key_hashed ' , ( ' key0_str ' , ' key1 ' ) , False ) , <nl> - ( ' clickhouse_range_hashed ' , ( ' id ' , ' StartDate ' , ' EndDate ' ) , False ) , <nl> - ] , <nl> - ids = [ ' clickhouse_hashed ' , ' clickhouse_flat ' , <nl> - ' clickhouse_complex_integers_key_hashed ' , <nl> - ' clickhouse_complex_mixed_key_hashed ' , <nl> - ' clickhouse_range_hashed ' ] <nl> - ) <nl> - def dictionary_structure ( started_cluster , request ) : <nl> - return request . param <nl> - <nl> - <nl> - def test_select_all ( dictionary_structure ) : <nl> - name , keys , use_parent = dictionary_structure <nl> - query = instance . query <nl> - <nl> - structure = test_table . get_structure_for_keys ( keys , use_parent ) <nl> - query ( ' ' ' <nl> - DROP TABLE IF EXISTS test . { 0 } <nl> - ' ' ' . format ( name ) ) <nl> - <nl> - create_query = " CREATE TABLE test . { 0 } ( { 1 } ) engine = Dictionary ( { 0 } ) " . format ( name , structure ) <nl> - TSV ( query ( create_query ) ) <nl> - <nl> - result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> - <nl> - diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = True ) <nl> - print test_table . process_diff ( diff ) <nl> - assert not diff <nl> - <nl> - <nl> - @ pytest . fixture ( params = [ <nl> - # name , keys , use_parent <nl> - ( ' clickhouse_cache ' , ( ' id ' , ) , True ) , <nl> - ( ' clickhouse_complex_integers_key_cache ' , ( ' key0 ' , ' key1 ' ) , False ) , <nl> - ( ' clickhouse_complex_mixed_key_cache ' , ( ' key0_str ' , ' key1 ' ) , False ) <nl> - ] , <nl> - ids = [ ' clickhouse_cache ' , ' clickhouse_complex_integers_key_cache ' , ' clickhouse_complex_mixed_key_cache ' ] <nl> - ) <nl> - def cached_dictionary_structure ( started_cluster , request ) : <nl> - return request . param <nl> - <nl> - <nl> - def test_select_all_from_cached ( cached_dictionary_structure ) : <nl> - name , keys , use_parent = cached_dictionary_structure <nl> - query = instance . query <nl> - <nl> - structure = test_table . get_structure_for_keys ( keys , use_parent ) <nl> - query ( ' ' ' <nl> - DROP TABLE IF EXISTS test . { 0 } <nl> - ' ' ' . format ( name ) ) <nl> - <nl> - create_query = " CREATE TABLE test . { 0 } ( { 1 } ) engine = Dictionary ( { 0 } ) " . format ( name , structure ) <nl> - TSV ( query ( create_query ) ) <nl> - <nl> - for i in range ( 4 ) : <nl> - result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> - diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = False ) <nl> - print test_table . process_diff ( diff ) <nl> - assert not diff <nl> - <nl> - key = [ ] <nl> - for key_name in keys : <nl> - if key_name . endswith ( ' str ' ) : <nl> - key . append ( " ' " + str ( i ) + " ' " ) <nl> - else : <nl> - key . append ( str ( i ) ) <nl> - if len ( key ) = = 1 : <nl> - key = ' toUInt64 ( ' + str ( i ) + ' ) ' <nl> - else : <nl> - key = str ( ' ( ' + ' , ' . join ( key ) + ' ) ' ) <nl> - query ( " select dictGetUInt8 ( ' { 0 } ' , ' UInt8_ ' , { 1 } ) " . format ( name , key ) ) <nl> - <nl> - result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> - diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = True ) <nl> - print test_table . process_diff ( diff ) <nl> - assert not diff <nl> - <nl> - <nl> - def test_null_value ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - assert TSV ( query ( " select dictGetUInt8 ( ' clickhouse_cache ' , ' UInt8_ ' , toUInt64 ( 12121212 ) ) " ) ) = = TSV ( " 1 " ) <nl> - assert TSV ( query ( " select dictGetString ( ' clickhouse_cache ' , ' String_ ' , toUInt64 ( 12121212 ) ) " ) ) = = TSV ( " implicit - default " ) <nl> - assert TSV ( query ( " select dictGetDate ( ' clickhouse_cache ' , ' Date_ ' , toUInt64 ( 12121212 ) ) " ) ) = = TSV ( " 2015 - 11 - 25 " ) <nl> - <nl> - # Check , that empty null_value interprets as default value <nl> - assert TSV ( query ( " select dictGetUInt64 ( ' clickhouse_cache ' , ' UInt64_ ' , toUInt64 ( 12121212 ) ) " ) ) = = TSV ( " 0 " ) <nl> - assert TSV ( query ( " select dictGetDateTime ( ' clickhouse_cache ' , ' DateTime_ ' , toUInt64 ( 12121212 ) ) " ) ) = = TSV ( " 0000 - 00 - 00 00 : 00 : 00 " ) <nl> - <nl> - <nl> - def test_dictionary_dependency ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - # dictionaries_lazy_load = = false , so these dictionary are not loaded . <nl> - assert get_status ( ' dep_x ' ) = = ' NOT_LOADED ' <nl> - assert get_status ( ' dep_y ' ) = = ' NOT_LOADED ' <nl> - assert get_status ( ' dep_z ' ) = = ' NOT_LOADED ' <nl> - <nl> - # Dictionary ' dep_x ' depends on ' dep_z ' , which depends on ' dep_y ' . <nl> - # So they all should be loaded at once . <nl> - assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> - assert get_status ( ' dep_x ' ) = = ' LOADED ' <nl> - assert get_status ( ' dep_y ' ) = = ' LOADED ' <nl> - assert get_status ( ' dep_z ' ) = = ' LOADED ' <nl> - <nl> - # Other dictionaries should work too . <nl> - assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> - <nl> - assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " XX \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " YY \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " ZZ \ n " <nl> - <nl> - # Update the source table . <nl> - query ( " insert into test . small_dict_source values ( 3 , ' fire ' , 30 , 8 ) " ) <nl> - <nl> - # Wait for dictionaries to be reloaded . <nl> - assert_eq_with_retry ( instance , " SELECT dictHas ( ' dep_y ' , toUInt64 ( 3 ) ) " , " 1 " , sleep_time = 2 , retry_count = 10 ) <nl> - assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " XX \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " ZZ \ n " <nl> - <nl> - # dep_x and dep_z are updated only when there ` intDiv ( count ( ) , 4 ) ` is changed . <nl> - query ( " insert into test . small_dict_source values ( 4 , ' ether ' , 404 , 0 . 001 ) " ) <nl> - assert_eq_with_retry ( instance , " SELECT dictHas ( ' dep_x ' , toUInt64 ( 4 ) ) " , " 1 " , sleep_time = 2 , retry_count = 10 ) <nl> - assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> - assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> - <nl> - <nl> - def test_reload_while_loading ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> - assert get_status ( ' longload ' ) = = " NOT_LOADED " <nl> - assert get_loading_duration ( ' longload ' ) = = 0 <nl> - <nl> - # It ' s not possible to get a value from the dictionary within 1 . 0 second , so the following query fails by timeout . <nl> - assert query ( " SELECT dictGetInt32 ( ' longload ' , ' a ' , toUInt64 ( 5 ) ) " , timeout = 1 , ignore_error = True ) = = " " <nl> - <nl> - # The dictionary is now loading . <nl> - assert get_status ( ' longload ' ) = = " LOADING " <nl> - start_time , duration = get_loading_start_time ( ' longload ' ) , get_loading_duration ( ' longload ' ) <nl> - assert duration > 0 <nl> - <nl> - time . sleep ( 0 . 5 ) # Still loading . <nl> - assert get_status ( ' longload ' ) = = " LOADING " <nl> - prev_start_time , prev_duration = start_time , duration <nl> - start_time , duration = get_loading_start_time ( ' longload ' ) , get_loading_duration ( ' longload ' ) <nl> - assert start_time = = prev_start_time <nl> - assert duration > = prev_duration <nl> - <nl> - # SYSTEM RELOAD DICTIONARY should restart loading . <nl> - query ( " SYSTEM RELOAD DICTIONARY ' longload ' " ) <nl> - assert get_status ( ' longload ' ) = = " LOADING " <nl> - prev_start_time , prev_duration = start_time , duration <nl> - start_time , duration = get_loading_start_time ( ' longload ' ) , get_loading_duration ( ' longload ' ) <nl> - assert start_time > prev_start_time <nl> - assert duration < prev_duration <nl> - <nl> - time . sleep ( 0 . 5 ) # Still loading . <nl> - assert get_status ( ' longload ' ) = = " LOADING " <nl> - prev_start_time , prev_duration = start_time , duration <nl> - start_time , duration = get_loading_start_time ( ' longload ' ) , get_loading_duration ( ' longload ' ) <nl> - assert start_time = = prev_start_time <nl> - assert duration > = prev_duration <nl> - <nl> - # SYSTEM RELOAD DICTIONARIES should restart loading again . <nl> - query ( " SYSTEM RELOAD DICTIONARIES " ) <nl> - assert get_status ( ' longload ' ) = = " LOADING " <nl> - prev_start_time , prev_duration = start_time , duration <nl> - start_time , duration = get_loading_start_time ( ' longload ' ) , get_loading_duration ( ' longload ' ) <nl> - assert start_time > prev_start_time <nl> - assert duration < prev_duration <nl> - <nl> - # Changing the configuration file should restart loading one more time . <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_longload . xml ' , ' sleep 100 ' , ' sleep 0 ' ) <nl> - time . sleep ( 5 ) # Configuration files are reloaded once in 5 seconds . <nl> - <nl> - # This time loading should finish quickly . <nl> - assert get_status ( ' longload ' ) = = " LOADED " <nl> - assert query ( " SELECT dictGetInt32 ( ' longload ' , ' a ' , toUInt64 ( 5 ) ) " ) = = " 6 \ n " <nl> - <nl> - <nl> - def test_reload_after_loading ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - assert query ( " SELECT dictGetInt32 ( ' cmd ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 8 \ n " <nl> - assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - <nl> - # Change the dictionaries ' data . <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_cmd . xml ' , ' 8 ' , ' 81 ' ) <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_file . txt ' , ' 10 ' , ' 101 ' ) <nl> - <nl> - # SYSTEM RELOAD ' name ' reloads only the specified dictionary . <nl> - query ( " SYSTEM RELOAD DICTIONARY ' cmd ' " ) <nl> - assert query ( " SELECT dictGetInt32 ( ' cmd ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 81 \ n " <nl> - assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - <nl> - query ( " SYSTEM RELOAD DICTIONARY ' file ' " ) <nl> - assert query ( " SELECT dictGetInt32 ( ' cmd ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 81 \ n " <nl> - assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 101 \ n " <nl> - <nl> - # SYSTEM RELOAD DICTIONARIES reloads all loaded dictionaries . <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_cmd . xml ' , ' 81 ' , ' 82 ' ) <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_file . txt ' , ' 101 ' , ' 102 ' ) <nl> - query ( " SYSTEM RELOAD DICTIONARIES " ) <nl> - assert query ( " SELECT dictGetInt32 ( ' cmd ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 82 \ n " <nl> - assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 102 \ n " <nl> - <nl> - # Configuration files are reloaded and lifetimes are checked automatically once in 5 seconds . <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_cmd . xml ' , ' 82 ' , ' 83 ' ) <nl> - replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / dictionary_preset_file . txt ' , ' 102 ' , ' 103 ' ) <nl> - time . sleep ( 5 ) <nl> - assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 103 \ n " <nl> - assert query ( " SELECT dictGetInt32 ( ' cmd ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 83 \ n " <nl> - <nl> - <nl> - def test_reload_after_fail_by_system_reload ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> - assert get_status ( " no_file " ) = = " NOT_LOADED " <nl> - <nl> - # We expect an error because the file source doesn ' t exist . <nl> - expected_error = " No such file " <nl> - assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> - assert get_status ( " no_file " ) = = " FAILED " <nl> - <nl> - # SYSTEM RELOAD should not change anything now , the status is still FAILED . <nl> - query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> - assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> - assert get_status ( " no_file " ) = = " FAILED " <nl> - <nl> - # Creating the file source makes the dictionary able to load . <nl> - instance . copy_file_to_container ( os . path . join ( SCRIPT_DIR , " configs / dictionaries / dictionary_preset_file . txt " ) , " / etc / clickhouse - server / config . d / dictionary_preset_no_file . txt " ) <nl> - query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> - query ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - assert get_status ( " no_file " ) = = " LOADED " <nl> - <nl> - # Removing the file source should not spoil the loaded dictionary . <nl> - instance . exec_in_container ( " rm / etc / clickhouse - server / config . d / dictionary_preset_no_file . txt " ) <nl> - query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> - query ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - assert get_status ( " no_file " ) = = " LOADED " <nl> - <nl> - <nl> - def test_reload_after_fail_by_timer ( started_cluster ) : <nl> - query = instance . query <nl> - <nl> - # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> - assert get_status ( " no_file_2 " ) = = " NOT_LOADED " <nl> - <nl> - # We expect an error because the file source doesn ' t exist . <nl> - expected_error = " No such file " <nl> - assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> - assert get_status ( " no_file_2 " ) = = " FAILED " <nl> - <nl> - # Passed time should not change anything now , the status is still FAILED . <nl> - time . sleep ( 6 ) ; <nl> - assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> - assert get_status ( " no_file_2 " ) = = " FAILED " <nl> - <nl> - # Creating the file source makes the dictionary able to load . <nl> - instance . copy_file_to_container ( os . path . join ( SCRIPT_DIR , " configs / dictionaries / dictionary_preset_file . txt " ) , " / etc / clickhouse - server / config . d / dictionary_preset_no_file_2 . txt " ) <nl> - time . sleep ( 6 ) ; <nl> - query ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - assert get_status ( " no_file_2 " ) = = " LOADED " <nl> - <nl> - # Removing the file source should not spoil the loaded dictionary . <nl> - instance . exec_in_container ( " rm / etc / clickhouse - server / config . d / dictionary_preset_no_file_2 . txt " ) <nl> - time . sleep ( 6 ) ; <nl> - query ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> - assert get_status ( " no_file_2 " ) = = " LOADED " <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_cached_dictionary_string / __init__ . py <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / __init__ . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / configs / config . xml <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / configs / config . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / configs / dictionaries / . gitkeep <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / configs / dictionaries / . gitkeep <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_cached_dictionary_string / configs / users . xml <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / configs / users . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / dictionary . py <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / dictionary . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / external_sources . py <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / external_sources . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / fake_cert . pem <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / fake_cert . pem <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / http_server . py <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / http_server . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / test . py <nl> rename to dbms / tests / integration / test_dictionaries_all_layouts_and_sources / test . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / __init__ . py <nl> rename to dbms / tests / integration / test_dictionaries_complex_key_cache_string / __init__ . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_cached_dictionary_string / configs / config . xml <nl> rename to dbms / tests / integration / test_dictionaries_complex_key_cache_string / configs / config . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_cached_dictionary_string / configs / dictionaries / complex_key_cache_string . xml <nl> rename to dbms / tests / integration / test_dictionaries_complex_key_cache_string / configs / dictionaries / complex_key_cache_string . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / users . xml <nl> rename to dbms / tests / integration / test_dictionaries_complex_key_cache_string / configs / users . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_cached_dictionary_string / test . py <nl> rename to dbms / tests / integration / test_dictionaries_complex_key_cache_string / test . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / __init__ . py <nl> rename to dbms / tests / integration / test_dictionaries_depend_on_dictionaries / __init__ . py <nl> new file mode 100644 <nl> index 00000000000 . . b60daf72dcf <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / config . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < logger > <nl> + < level > trace < / level > <nl> + < log > / var / log / clickhouse - server / clickhouse - server . log < / log > <nl> + < errorlog > / var / log / clickhouse - server / clickhouse - server . err . log < / errorlog > <nl> + < size > 1000M < / size > <nl> + < count > 10 < / count > <nl> + < / logger > <nl> + <nl> + < tcp_port > 9000 < / tcp_port > <nl> + < listen_host > 127 . 0 . 0 . 1 < / listen_host > <nl> + <nl> + < openSSL > <nl> + < client > <nl> + < cacheSessions > true < / cacheSessions > <nl> + < verificationMode > none < / verificationMode > <nl> + < invalidCertificateHandler > <nl> + < name > AcceptCertificateHandler < / name > <nl> + < / invalidCertificateHandler > <nl> + < / client > <nl> + < / openSSL > <nl> + <nl> + < max_concurrent_queries > 500 < / max_concurrent_queries > <nl> + < mark_cache_size > 5368709120 < / mark_cache_size > <nl> + < path > . / clickhouse / < / path > <nl> + < users_config > users . xml < / users_config > <nl> + <nl> + < dictionaries_config > / etc / clickhouse - server / config . d / * . xml < / dictionaries_config > <nl> + < / yandex > <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_dep_x . xml <nl> rename to dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / dictionaries / dep_x . xml <nl> similarity index 95 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_dep_y . xml <nl> rename to dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / dictionaries / dep_y . xml <nl> mmm a / dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_dep_y . xml <nl> ppp b / dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / dictionaries / dep_y . xml <nl> <nl> < user > default < / user > <nl> < password > < / password > <nl> < db > test < / db > <nl> - < table > small_dict_source < / table > <nl> + < table > elements < / table > <nl> < / clickhouse > <nl> < / source > <nl> < lifetime > 5 < / lifetime > <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_dep_z . xml <nl> rename to dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / dictionaries / dep_z . xml <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_external_dictionaries / configs / users . xml <nl> rename to dbms / tests / integration / test_dictionaries_depend_on_dictionaries / configs / users . xml <nl> new file mode 100644 <nl> index 00000000000 . . c0ce0af0313 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_depend_on_dictionaries / test . py <nl> <nl> + import pytest <nl> + import os <nl> + from helpers . cluster import ClickHouseCluster <nl> + from helpers . test_tools import assert_eq_with_retry <nl> + <nl> + SCRIPT_DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> + DICTIONARY_FILES = [ ' configs / dictionaries / dep_x . xml ' , ' configs / dictionaries / dep_y . xml ' , ' configs / dictionaries / dep_z . xml ' ] <nl> + <nl> + cluster = ClickHouseCluster ( __file__ , base_configs_dir = os . path . join ( SCRIPT_DIR , ' configs ' ) ) <nl> + instance = cluster . add_instance ( ' instance ' , main_configs = DICTIONARY_FILES ) <nl> + <nl> + <nl> + @ pytest . fixture ( scope = " module " ) <nl> + def started_cluster ( ) : <nl> + try : <nl> + cluster . start ( ) <nl> + <nl> + instance . query ( ' ' ' <nl> + CREATE DATABASE IF NOT EXISTS dict ENGINE = Dictionary ; <nl> + CREATE DATABASE IF NOT EXISTS test ; <nl> + DROP TABLE IF EXISTS test . elements ; <nl> + CREATE TABLE test . elements ( id UInt64 , a String , b Int32 , c Float64 ) ENGINE = Log ; <nl> + INSERT INTO test . elements VALUES ( 0 , ' water ' , 10 , 1 ) , ( 1 , ' air ' , 40 , 0 . 01 ) , ( 2 , ' earth ' , 100 , 1 . 7 ) ; <nl> + ' ' ' ) <nl> + <nl> + yield cluster <nl> + <nl> + finally : <nl> + cluster . shutdown ( ) <nl> + <nl> + <nl> + def get_status ( dictionary_name ) : <nl> + return instance . query ( " SELECT status FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) <nl> + <nl> + <nl> + def test_get_data ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + # dictionaries_lazy_load = = false , so these dictionary are not loaded . <nl> + assert get_status ( ' dep_x ' ) = = ' NOT_LOADED ' <nl> + assert get_status ( ' dep_y ' ) = = ' NOT_LOADED ' <nl> + assert get_status ( ' dep_z ' ) = = ' NOT_LOADED ' <nl> + <nl> + # Dictionary ' dep_x ' depends on ' dep_z ' , which depends on ' dep_y ' . <nl> + # So they all should be loaded at once . <nl> + assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> + assert get_status ( ' dep_x ' ) = = ' LOADED ' <nl> + assert get_status ( ' dep_y ' ) = = ' LOADED ' <nl> + assert get_status ( ' dep_z ' ) = = ' LOADED ' <nl> + <nl> + # Other dictionaries should work too . <nl> + assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 1 ) ) " ) = = " air \ n " <nl> + <nl> + assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " XX \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " YY \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " ZZ \ n " <nl> + <nl> + # Update the source table . <nl> + query ( " INSERT INTO test . elements VALUES ( 3 , ' fire ' , 30 , 8 ) " ) <nl> + <nl> + # Wait for dictionaries to be reloaded . <nl> + assert_eq_with_retry ( instance , " SELECT dictHas ( ' dep_y ' , toUInt64 ( 3 ) ) " , " 1 " , sleep_time = 2 , retry_count = 10 ) <nl> + assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " XX \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " ZZ \ n " <nl> + <nl> + # dep_x and dep_z are updated only when there ` intDiv ( count ( ) , 4 ) ` is changed . <nl> + query ( " INSERT INTO test . elements VALUES ( 4 , ' ether ' , 404 , 0 . 001 ) " ) <nl> + assert_eq_with_retry ( instance , " SELECT dictHas ( ' dep_x ' , toUInt64 ( 4 ) ) " , " 1 " , sleep_time = 2 , retry_count = 10 ) <nl> + assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 3 ) ) " ) = = " fire \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_x ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_y ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> + assert query ( " SELECT dictGetString ( ' dep_z ' , ' a ' , toUInt64 ( 4 ) ) " ) = = " ether \ n " <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00960_live_view_watch_events_live . reference <nl> rename to dbms / tests / integration / test_dictionaries_null_value / __init__ . py <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / config . xml <nl> rename to dbms / tests / integration / test_dictionaries_null_value / configs / config . xml <nl> new file mode 100644 <nl> index 00000000000 . . 9a1ae0732db <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_null_value / configs / dictionaries / cache . xml <nl> <nl> + < yandex > <nl> + < dictionary > <nl> + < name > cache < / name > <nl> + <nl> + < source > <nl> + < clickhouse > <nl> + < host > localhost < / host > <nl> + < port > 9000 < / port > <nl> + < user > default < / user > <nl> + < password > < / password > <nl> + < db > test < / db > <nl> + < table > source < / table > <nl> + < / clickhouse > <nl> + < / source > <nl> + <nl> + < lifetime > 0 < / lifetime > <nl> + <nl> + < layout > <nl> + < cache > < size_in_cells > 128 < / size_in_cells > < / cache > <nl> + < / layout > <nl> + <nl> + < structure > <nl> + < id > <nl> + < name > id < / name > <nl> + < / id > <nl> + <nl> + < attribute > <nl> + < name > UInt8_ < / name > <nl> + < type > UInt8 < / type > <nl> + < null_value > 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > UInt16_ < / name > <nl> + < type > UInt16 < / type > <nl> + < null_value > 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > UInt32_ < / name > <nl> + < type > UInt32 < / type > <nl> + < null_value > 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > UInt64_ < / name > <nl> + < type > UInt64 < / type > <nl> + < null_value > < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Int8_ < / name > <nl> + < type > Int8 < / type > <nl> + < null_value > - 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Int16_ < / name > <nl> + < type > Int16 < / type > <nl> + < null_value > - 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Int32_ < / name > <nl> + < type > Int32 < / type > <nl> + < null_value > - 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Int64_ < / name > <nl> + < type > Int64 < / type > <nl> + < null_value > - 1 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Float32_ < / name > <nl> + < type > Float32 < / type > <nl> + < null_value > 2 . 71828 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Float64_ < / name > <nl> + < type > Float64 < / type > <nl> + < null_value > 2 . 71828 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > String_ < / name > <nl> + < type > String < / type > <nl> + < null_value > implicit - default < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Date_ < / name > <nl> + < type > Date < / type > <nl> + < null_value > 2015 - 11 - 25 < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > DateTime_ < / name > <nl> + < type > DateTime < / type > <nl> + < null_value > < / null_value > <nl> + < / attribute > <nl> + <nl> + < attribute > <nl> + < name > Parent < / name > <nl> + < type > UInt64 < / type > <nl> + < hierarchical > true < / hierarchical > <nl> + < null_value > 0 < / null_value > <nl> + < / attribute > <nl> + < / structure > <nl> + < / dictionary > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . 6061af8e33d <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_null_value / configs / users . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < profiles > <nl> + < default > <nl> + < / default > <nl> + < / profiles > <nl> + <nl> + < users > <nl> + < default > <nl> + < password > < / password > <nl> + < networks incl = " networks " replace = " replace " > <nl> + < ip > : : / 0 < / ip > <nl> + < / networks > <nl> + < profile > default < / profile > <nl> + < quota > default < / quota > <nl> + < / default > <nl> + < / users > <nl> + <nl> + < quotas > <nl> + < default > <nl> + < / default > <nl> + < / quotas > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . e31f397c246 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_null_value / test . py <nl> <nl> + import pytest <nl> + import os <nl> + from helpers . cluster import ClickHouseCluster <nl> + from helpers . test_tools import TSV , assert_eq_with_retry <nl> + <nl> + SCRIPT_DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> + DICTIONARY_FILES = [ ' configs / dictionaries / cache . xml ' ] <nl> + <nl> + cluster = ClickHouseCluster ( __file__ , base_configs_dir = os . path . join ( SCRIPT_DIR , ' configs ' ) ) <nl> + instance = cluster . add_instance ( ' instance ' , main_configs = DICTIONARY_FILES ) <nl> + <nl> + <nl> + @ pytest . fixture ( scope = " module " ) <nl> + def started_cluster ( ) : <nl> + try : <nl> + cluster . start ( ) <nl> + <nl> + instance . query ( ' ' ' <nl> + CREATE DATABASE IF NOT EXISTS test ; <nl> + DROP TABLE IF EXISTS test . source ; <nl> + CREATE TABLE test . source ( id UInt64 , key0 UInt8 , key0_str String , key1 UInt8 , <nl> + StartDate Date , EndDate Date , <nl> + UInt8_ UInt8 , UInt16_ UInt16 , UInt32_ UInt32 , UInt64_ UInt64 , <nl> + Int8_ Int8 , Int16_ Int16 , Int32_ Int32 , Int64_ Int64 , <nl> + Float32_ Float32 , Float64_ Float64 , <nl> + String_ String , <nl> + Date_ Date , DateTime_ DateTime , Parent UInt64 ) ENGINE = Log ; <nl> + ' ' ' ) <nl> + <nl> + yield cluster <nl> + <nl> + finally : <nl> + cluster . shutdown ( ) <nl> + <nl> + <nl> + def test_null_value ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + assert query ( " select dictGetUInt8 ( ' cache ' , ' UInt8_ ' , toUInt64 ( 12121212 ) ) " ) = = " 1 \ n " <nl> + assert query ( " select dictGetString ( ' cache ' , ' String_ ' , toUInt64 ( 12121212 ) ) " ) = = " implicit - default \ n " <nl> + assert query ( " select dictGetDate ( ' cache ' , ' Date_ ' , toUInt64 ( 12121212 ) ) " ) = = " 2015 - 11 - 25 \ n " <nl> + <nl> + # Check , that empty null_value interprets as default value <nl> + assert query ( " select dictGetUInt64 ( ' cache ' , ' UInt64_ ' , toUInt64 ( 12121212 ) ) " ) = = " 0 \ n " <nl> + assert query ( " select dictGetDateTime ( ' cache ' , ' DateTime_ ' , toUInt64 ( 12121212 ) ) " ) = = " 0000 - 00 - 00 00 : 00 : 00 \ n " <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00962_temporary_live_view_watch_live . reference <nl> rename to dbms / tests / integration / test_dictionaries_select_all / __init__ . py <nl> new file mode 100644 <nl> index 00000000000 . . 1e4c14585a9 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_select_all / configs / config . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < logger > <nl> + < level > trace < / level > <nl> + < log > / var / log / clickhouse - server / clickhouse - server . log < / log > <nl> + < errorlog > / var / log / clickhouse - server / clickhouse - server . err . log < / errorlog > <nl> + < size > 1000M < / size > <nl> + < count > 10 < / count > <nl> + < / logger > <nl> + <nl> + < tcp_port > 9000 < / tcp_port > <nl> + < listen_host > 127 . 0 . 0 . 1 < / listen_host > <nl> + <nl> + < openSSL > <nl> + < client > <nl> + < cacheSessions > true < / cacheSessions > <nl> + < verificationMode > none < / verificationMode > <nl> + < invalidCertificateHandler > <nl> + < name > AcceptCertificateHandler < / name > <nl> + < / invalidCertificateHandler > <nl> + < / client > <nl> + < / openSSL > <nl> + <nl> + < max_concurrent_queries > 500 < / max_concurrent_queries > <nl> + < mark_cache_size > 5368709120 < / mark_cache_size > <nl> + < path > . / clickhouse / < / path > <nl> + < users_config > users . xml < / users_config > <nl> + <nl> + < dictionaries_config > / etc / clickhouse - server / config . d / * . xml < / dictionaries_config > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . cc461064a39 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_select_all / configs / dictionaries / . gitignore <nl> <nl> + * <nl> + ! . gitignore <nl> + ! source . tsv <nl> \ No newline at end of file <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / source . tsv <nl> rename to dbms / tests / integration / test_dictionaries_select_all / configs / dictionaries / source . tsv <nl> new file mode 100644 <nl> index 00000000000 . . 6061af8e33d <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_select_all / configs / users . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < profiles > <nl> + < default > <nl> + < / default > <nl> + < / profiles > <nl> + <nl> + < users > <nl> + < default > <nl> + < password > < / password > <nl> + < networks incl = " networks " replace = " replace " > <nl> + < ip > : : / 0 < / ip > <nl> + < / networks > <nl> + < profile > default < / profile > <nl> + < quota > default < / quota > <nl> + < / default > <nl> + < / users > <nl> + <nl> + < quotas > <nl> + < default > <nl> + < / default > <nl> + < / quotas > <nl> + < / yandex > <nl> similarity index 96 % <nl> rename from dbms / tests / integration / test_dictionaries / generate_dictionaries . py <nl> rename to dbms / tests / integration / test_dictionaries_select_all / generate_dictionaries . py <nl> mmm a / dbms / tests / integration / test_dictionaries / generate_dictionaries . py <nl> ppp b / dbms / tests / integration / test_dictionaries_select_all / generate_dictionaries . py <nl> <nl> ' Date ' , ' DateTime ' <nl> ] <nl> <nl> - explicit_defaults = [ <nl> - ' 42 ' , ' 42 ' , ' 42 ' , ' 42 ' , <nl> - ' - 42 ' , ' - 42 ' , ' - 42 ' , ' - 42 ' , <nl> - ' 1 . 5 ' , ' 1 . 6 ' , <nl> - " ' explicit - default ' " , <nl> - " ' 2015 - 01 - 01 ' " , " ' 2015 - 01 - 01 00 : 00 : 00 ' " <nl> - ] <nl> <nl> implicit_defaults = [ <nl> ' 1 ' , ' 1 ' , ' 1 ' , ' ' , <nl> def generate_dictionaries ( path , structure ) : <nl> <nl> file_names = [ ] <nl> <nl> - # Add ready dictionaries . <nl> - file_names . extend ( glob . glob ( os . path . join ( path , " * dictionary_preset * " ) ) ) <nl> - <nl> # Generate dictionaries . <nl> for ( name , key_idx , has_parent ) , ( source , layout ) in zip ( structure , sources_and_layouts ) : <nl> filename = os . path . join ( path , ' dictionary_ % s . xml ' % name ) <nl> new file mode 100644 <nl> index 00000000000 . . 8bad8a9b214 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_select_all / test . py <nl> <nl> + import pytest <nl> + import os <nl> + from helpers . cluster import ClickHouseCluster <nl> + from helpers . test_tools import TSV , assert_eq_with_retry <nl> + from generate_dictionaries import generate_structure , generate_dictionaries , DictionaryTestTable <nl> + <nl> + SCRIPT_DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> + <nl> + cluster = None <nl> + instance = None <nl> + test_table = None <nl> + <nl> + <nl> + def setup_module ( module ) : <nl> + global cluster <nl> + global instance <nl> + global test_table <nl> + <nl> + structure = generate_structure ( ) <nl> + dictionary_files = generate_dictionaries ( os . path . join ( SCRIPT_DIR , ' configs / dictionaries ' ) , structure ) <nl> + <nl> + cluster = ClickHouseCluster ( __file__ , base_configs_dir = os . path . join ( SCRIPT_DIR , ' configs ' ) ) <nl> + instance = cluster . add_instance ( ' instance ' , main_configs = dictionary_files ) <nl> + test_table = DictionaryTestTable ( os . path . join ( SCRIPT_DIR , ' configs / dictionaries / source . tsv ' ) ) <nl> + <nl> + <nl> + @ pytest . fixture ( scope = " module " ) <nl> + def started_cluster ( ) : <nl> + try : <nl> + cluster . start ( ) <nl> + test_table . create_clickhouse_source ( instance ) <nl> + for line in TSV ( instance . query ( ' select name from system . dictionaries ' ) ) . lines : <nl> + print line , <nl> + <nl> + yield cluster <nl> + <nl> + finally : <nl> + cluster . shutdown ( ) <nl> + <nl> + <nl> + @ pytest . fixture ( params = [ <nl> + # name , keys , use_parent <nl> + ( ' clickhouse_hashed ' , ( ' id ' , ) , True ) , <nl> + ( ' clickhouse_flat ' , ( ' id ' , ) , True ) , <nl> + ( ' clickhouse_complex_integers_key_hashed ' , ( ' key0 ' , ' key1 ' ) , False ) , <nl> + ( ' clickhouse_complex_mixed_key_hashed ' , ( ' key0_str ' , ' key1 ' ) , False ) , <nl> + ( ' clickhouse_range_hashed ' , ( ' id ' , ' StartDate ' , ' EndDate ' ) , False ) , <nl> + ] , <nl> + ids = [ ' clickhouse_hashed ' , ' clickhouse_flat ' , <nl> + ' clickhouse_complex_integers_key_hashed ' , <nl> + ' clickhouse_complex_mixed_key_hashed ' , <nl> + ' clickhouse_range_hashed ' ] <nl> + ) <nl> + def dictionary_structure ( started_cluster , request ) : <nl> + return request . param <nl> + <nl> + <nl> + def test_select_all ( dictionary_structure ) : <nl> + name , keys , use_parent = dictionary_structure <nl> + query = instance . query <nl> + <nl> + structure = test_table . get_structure_for_keys ( keys , use_parent ) <nl> + query ( ' ' ' <nl> + DROP TABLE IF EXISTS test . { 0 } <nl> + ' ' ' . format ( name ) ) <nl> + <nl> + create_query = " CREATE TABLE test . { 0 } ( { 1 } ) engine = Dictionary ( { 0 } ) " . format ( name , structure ) <nl> + TSV ( query ( create_query ) ) <nl> + <nl> + result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> + <nl> + diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = True ) <nl> + print test_table . process_diff ( diff ) <nl> + assert not diff <nl> + <nl> + <nl> + @ pytest . fixture ( params = [ <nl> + # name , keys , use_parent <nl> + ( ' clickhouse_cache ' , ( ' id ' , ) , True ) , <nl> + ( ' clickhouse_complex_integers_key_cache ' , ( ' key0 ' , ' key1 ' ) , False ) , <nl> + ( ' clickhouse_complex_mixed_key_cache ' , ( ' key0_str ' , ' key1 ' ) , False ) <nl> + ] , <nl> + ids = [ ' clickhouse_cache ' , ' clickhouse_complex_integers_key_cache ' , ' clickhouse_complex_mixed_key_cache ' ] <nl> + ) <nl> + def cached_dictionary_structure ( started_cluster , request ) : <nl> + return request . param <nl> + <nl> + <nl> + def test_select_all_from_cached ( cached_dictionary_structure ) : <nl> + name , keys , use_parent = cached_dictionary_structure <nl> + query = instance . query <nl> + <nl> + structure = test_table . get_structure_for_keys ( keys , use_parent ) <nl> + query ( ' ' ' <nl> + DROP TABLE IF EXISTS test . { 0 } <nl> + ' ' ' . format ( name ) ) <nl> + <nl> + create_query = " CREATE TABLE test . { 0 } ( { 1 } ) engine = Dictionary ( { 0 } ) " . format ( name , structure ) <nl> + TSV ( query ( create_query ) ) <nl> + <nl> + for i in range ( 4 ) : <nl> + result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> + diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = False ) <nl> + print test_table . process_diff ( diff ) <nl> + assert not diff <nl> + <nl> + key = [ ] <nl> + for key_name in keys : <nl> + if key_name . endswith ( ' str ' ) : <nl> + key . append ( " ' " + str ( i ) + " ' " ) <nl> + else : <nl> + key . append ( str ( i ) ) <nl> + if len ( key ) = = 1 : <nl> + key = ' toUInt64 ( ' + str ( i ) + ' ) ' <nl> + else : <nl> + key = str ( ' ( ' + ' , ' . join ( key ) + ' ) ' ) <nl> + query ( " select dictGetUInt8 ( ' { 0 } ' , ' UInt8_ ' , { 1 } ) " . format ( name , key ) ) <nl> + <nl> + result = TSV ( query ( ' select * from test . { 0 } ' . format ( name ) ) ) <nl> + diff = test_table . compare_by_keys ( keys , result . lines , use_parent , add_not_found_rows = True ) <nl> + print test_table . process_diff ( diff ) <nl> + assert not diff <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00963_temporary_live_view_watch_live_timeout . reference <nl> rename to dbms / tests / integration / test_dictionaries_update_and_reload / __init__ . py <nl> new file mode 100644 <nl> index 00000000000 . . b60daf72dcf <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / config . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < logger > <nl> + < level > trace < / level > <nl> + < log > / var / log / clickhouse - server / clickhouse - server . log < / log > <nl> + < errorlog > / var / log / clickhouse - server / clickhouse - server . err . log < / errorlog > <nl> + < size > 1000M < / size > <nl> + < count > 10 < / count > <nl> + < / logger > <nl> + <nl> + < tcp_port > 9000 < / tcp_port > <nl> + < listen_host > 127 . 0 . 0 . 1 < / listen_host > <nl> + <nl> + < openSSL > <nl> + < client > <nl> + < cacheSessions > true < / cacheSessions > <nl> + < verificationMode > none < / verificationMode > <nl> + < invalidCertificateHandler > <nl> + < name > AcceptCertificateHandler < / name > <nl> + < / invalidCertificateHandler > <nl> + < / client > <nl> + < / openSSL > <nl> + <nl> + < max_concurrent_queries > 500 < / max_concurrent_queries > <nl> + < mark_cache_size > 5368709120 < / mark_cache_size > <nl> + < path > . / clickhouse / < / path > <nl> + < users_config > users . xml < / users_config > <nl> + <nl> + < dictionaries_config > / etc / clickhouse - server / config . d / * . xml < / dictionaries_config > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . 4142706259a <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / cache_xypairs . xml <nl> <nl> + < yandex > <nl> + < dictionary > <nl> + < name > cache_xypairs < / name > <nl> + < source > <nl> + < clickhouse > <nl> + < host > localhost < / host > <nl> + < port > 9000 < / port > <nl> + < user > default < / user > <nl> + < password > < / password > <nl> + < db > test < / db > <nl> + < table > xypairs < / table > <nl> + < / clickhouse > <nl> + < / source > <nl> + < lifetime > 1 < / lifetime > <nl> + < layout > <nl> + < cache > <nl> + < size_in_cells > 5 < / size_in_cells > <nl> + < / cache > <nl> + < / layout > <nl> + < structure > <nl> + < id > <nl> + < name > x < / name > <nl> + < / id > <nl> + < attribute > <nl> + < name > y < / name > <nl> + < type > UInt64 < / type > <nl> + < null_value > 0 < / null_value > <nl> + < / attribute > <nl> + < / structure > <nl> + < / dictionary > <nl> + < / yandex > <nl> similarity index 93 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_cmd . xml <nl> rename to dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / executable . xml <nl> mmm a / dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_cmd . xml <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / executable . xml <nl> <nl> < ? xml version = " 1 . 0 " ? > <nl> < yandex > <nl> < dictionary > <nl> - < name > cmd < / name > <nl> + < name > executable < / name > <nl> < source > <nl> < executable > <nl> < command > echo ' 7 \ t8 ' ; < / command > <nl> similarity index 100 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_file . txt <nl> rename to dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / file . txt <nl> similarity index 82 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_file . xml <nl> rename to dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / file . xml <nl> mmm a / dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_file . xml <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / file . xml <nl> <nl> < name > file < / name > <nl> < source > <nl> < file > <nl> - < path > / etc / clickhouse - server / config . d / dictionary_preset_file . txt < / path > <nl> + < path > / etc / clickhouse - server / config . d / file . txt < / path > <nl> < format > TabSeparated < / format > <nl> < / file > <nl> < / source > <nl> <nl> < name > no_file < / name > <nl> < source > <nl> < file > <nl> - < path > / etc / clickhouse - server / config . d / dictionary_preset_no_file . txt < / path > <nl> + < path > / etc / clickhouse - server / config . d / no_file . txt < / path > <nl> < format > TabSeparated < / format > <nl> < / file > <nl> < / source > <nl> <nl> < name > no_file_2 < / name > <nl> < source > <nl> < file > <nl> - < path > / etc / clickhouse - server / config . d / dictionary_preset_no_file_2 . txt < / path > <nl> + < path > / etc / clickhouse - server / config . d / no_file_2 . txt < / path > <nl> < format > TabSeparated < / format > <nl> < / file > <nl> < / source > <nl> similarity index 94 % <nl> rename from dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_longload . xml <nl> rename to dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / slow . xml <nl> mmm a / dbms / tests / integration / test_dictionaries / configs / dictionaries / dictionary_preset_longload . xml <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / dictionaries / slow . xml <nl> <nl> < ? xml version = " 1 . 0 " ? > <nl> < yandex > <nl> < dictionary > <nl> - < name > longload < / name > <nl> + < name > slow < / name > <nl> < source > <nl> < executable > <nl> < command > sleep 100 & amp ; & amp ; echo ' 5 \ t6 ' ; < / command > <nl> new file mode 100644 <nl> index 00000000000 . . 6061af8e33d <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / configs / users . xml <nl> <nl> + < ? xml version = " 1 . 0 " ? > <nl> + < yandex > <nl> + < profiles > <nl> + < default > <nl> + < / default > <nl> + < / profiles > <nl> + <nl> + < users > <nl> + < default > <nl> + < password > < / password > <nl> + < networks incl = " networks " replace = " replace " > <nl> + < ip > : : / 0 < / ip > <nl> + < / networks > <nl> + < profile > default < / profile > <nl> + < quota > default < / quota > <nl> + < / default > <nl> + < / users > <nl> + <nl> + < quotas > <nl> + < default > <nl> + < / default > <nl> + < / quotas > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . b972dc6c918 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_dictionaries_update_and_reload / test . py <nl> <nl> + import pytest <nl> + import os <nl> + import time <nl> + from helpers . cluster import ClickHouseCluster <nl> + from helpers . test_tools import assert_eq_with_retry <nl> + <nl> + SCRIPT_DIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> + DICTIONARY_FILES = [ ' configs / dictionaries / cache_xypairs . xml ' , ' configs / dictionaries / executable . xml ' , ' configs / dictionaries / file . xml ' , ' configs / dictionaries / file . txt ' , ' configs / dictionaries / slow . xml ' ] <nl> + <nl> + cluster = ClickHouseCluster ( __file__ , base_configs_dir = os . path . join ( SCRIPT_DIR , ' configs ' ) ) <nl> + instance = cluster . add_instance ( ' instance ' , main_configs = DICTIONARY_FILES ) <nl> + <nl> + <nl> + @ pytest . fixture ( scope = " module " ) <nl> + def started_cluster ( ) : <nl> + try : <nl> + cluster . start ( ) <nl> + instance . query ( " CREATE DATABASE IF NOT EXISTS test " ) <nl> + <nl> + yield cluster <nl> + <nl> + finally : <nl> + cluster . shutdown ( ) <nl> + <nl> + <nl> + def get_status ( dictionary_name ) : <nl> + return instance . query ( " SELECT status FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) <nl> + <nl> + <nl> + def get_last_exception ( dictionary_name ) : <nl> + return instance . query ( " SELECT last_exception FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) . replace ( " \ \ ' " , " ' " ) <nl> + <nl> + <nl> + def get_loading_start_time ( dictionary_name ) : <nl> + s = instance . query ( " SELECT loading_start_time FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) . rstrip ( " \ n " ) <nl> + if s = = " 0000 - 00 - 00 00 : 00 : 00 " : <nl> + return None <nl> + return time . strptime ( s , " % Y - % m - % d % H : % M : % S " ) <nl> + <nl> + <nl> + def get_loading_duration ( dictionary_name ) : <nl> + return float ( instance . query ( " SELECT loading_duration FROM system . dictionaries WHERE name = ' " + dictionary_name + " ' " ) ) <nl> + <nl> + <nl> + def replace_in_file_in_container ( file_name , what , replace_with ) : <nl> + instance . exec_in_container ( ' sed - i " s / ' + what + ' / ' + replace_with + ' / g " ' + file_name ) <nl> + <nl> + <nl> + def test_reload_while_loading ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> + assert get_status ( ' slow ' ) = = " NOT_LOADED " <nl> + assert get_loading_duration ( ' slow ' ) = = 0 <nl> + <nl> + # It ' s not possible to get a value from the dictionary within 1 . 0 second , so the following query fails by timeout . <nl> + assert query ( " SELECT dictGetInt32 ( ' slow ' , ' a ' , toUInt64 ( 5 ) ) " , timeout = 1 , ignore_error = True ) = = " " <nl> + <nl> + # The dictionary is now loading . <nl> + assert get_status ( ' slow ' ) = = " LOADING " <nl> + start_time , duration = get_loading_start_time ( ' slow ' ) , get_loading_duration ( ' slow ' ) <nl> + assert duration > 0 <nl> + <nl> + time . sleep ( 0 . 5 ) # Still loading . <nl> + assert get_status ( ' slow ' ) = = " LOADING " <nl> + prev_start_time , prev_duration = start_time , duration <nl> + start_time , duration = get_loading_start_time ( ' slow ' ) , get_loading_duration ( ' slow ' ) <nl> + assert start_time = = prev_start_time <nl> + assert duration > = prev_duration <nl> + <nl> + # SYSTEM RELOAD DICTIONARY should restart loading . <nl> + query ( " SYSTEM RELOAD DICTIONARY ' slow ' " ) <nl> + assert get_status ( ' slow ' ) = = " LOADING " <nl> + prev_start_time , prev_duration = start_time , duration <nl> + start_time , duration = get_loading_start_time ( ' slow ' ) , get_loading_duration ( ' slow ' ) <nl> + assert start_time > prev_start_time <nl> + assert duration < prev_duration <nl> + <nl> + time . sleep ( 0 . 5 ) # Still loading . <nl> + assert get_status ( ' slow ' ) = = " LOADING " <nl> + prev_start_time , prev_duration = start_time , duration <nl> + start_time , duration = get_loading_start_time ( ' slow ' ) , get_loading_duration ( ' slow ' ) <nl> + assert start_time = = prev_start_time <nl> + assert duration > = prev_duration <nl> + <nl> + # SYSTEM RELOAD DICTIONARIES should restart loading again . <nl> + query ( " SYSTEM RELOAD DICTIONARIES " ) <nl> + assert get_status ( ' slow ' ) = = " LOADING " <nl> + prev_start_time , prev_duration = start_time , duration <nl> + start_time , duration = get_loading_start_time ( ' slow ' ) , get_loading_duration ( ' slow ' ) <nl> + assert start_time > prev_start_time <nl> + assert duration < prev_duration <nl> + <nl> + # Changing the configuration file should restart loading one more time . <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / slow . xml ' , ' sleep 100 ' , ' sleep 0 ' ) <nl> + time . sleep ( 5 ) # Configuration files are reloaded once in 5 seconds . <nl> + <nl> + # This time loading should finish quickly . <nl> + assert get_status ( ' slow ' ) = = " LOADED " <nl> + assert query ( " SELECT dictGetInt32 ( ' slow ' , ' a ' , toUInt64 ( 5 ) ) " ) = = " 6 \ n " <nl> + <nl> + <nl> + def test_reload_after_loading ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + assert query ( " SELECT dictGetInt32 ( ' executable ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 8 \ n " <nl> + assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + <nl> + # Change the dictionaries ' data . <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / executable . xml ' , ' 8 ' , ' 81 ' ) <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / file . txt ' , ' 10 ' , ' 101 ' ) <nl> + <nl> + # SYSTEM RELOAD ' name ' reloads only the specified dictionary . <nl> + query ( " SYSTEM RELOAD DICTIONARY ' executable ' " ) <nl> + assert query ( " SELECT dictGetInt32 ( ' executable ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 81 \ n " <nl> + assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + <nl> + query ( " SYSTEM RELOAD DICTIONARY ' file ' " ) <nl> + assert query ( " SELECT dictGetInt32 ( ' executable ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 81 \ n " <nl> + assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 101 \ n " <nl> + <nl> + # SYSTEM RELOAD DICTIONARIES reloads all loaded dictionaries . <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / executable . xml ' , ' 81 ' , ' 82 ' ) <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / file . txt ' , ' 101 ' , ' 102 ' ) <nl> + query ( " SYSTEM RELOAD DICTIONARIES " ) <nl> + assert query ( " SELECT dictGetInt32 ( ' executable ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 82 \ n " <nl> + assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 102 \ n " <nl> + <nl> + # Configuration files are reloaded and lifetimes are checked automatically once in 5 seconds . <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / executable . xml ' , ' 82 ' , ' 83 ' ) <nl> + replace_in_file_in_container ( ' / etc / clickhouse - server / config . d / file . txt ' , ' 102 ' , ' 103 ' ) <nl> + time . sleep ( 5 ) <nl> + assert query ( " SELECT dictGetInt32 ( ' file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 103 \ n " <nl> + assert query ( " SELECT dictGetInt32 ( ' executable ' , ' a ' , toUInt64 ( 7 ) ) " ) = = " 83 \ n " <nl> + <nl> + <nl> + def test_reload_after_fail_by_system_reload ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> + assert get_status ( " no_file " ) = = " NOT_LOADED " <nl> + <nl> + # We expect an error because the file source doesn ' t exist . <nl> + expected_error = " No such file " <nl> + assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> + assert get_status ( " no_file " ) = = " FAILED " <nl> + <nl> + # SYSTEM RELOAD should not change anything now , the status is still FAILED . <nl> + query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> + assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> + assert get_status ( " no_file " ) = = " FAILED " <nl> + <nl> + # Creating the file source makes the dictionary able to load . <nl> + instance . copy_file_to_container ( os . path . join ( SCRIPT_DIR , " configs / dictionaries / file . txt " ) , " / etc / clickhouse - server / config . d / no_file . txt " ) <nl> + query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> + query ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + assert get_status ( " no_file " ) = = " LOADED " <nl> + <nl> + # Removing the file source should not spoil the loaded dictionary . <nl> + instance . exec_in_container ( " rm / etc / clickhouse - server / config . d / no_file . txt " ) <nl> + query ( " SYSTEM RELOAD DICTIONARY ' no_file ' " ) <nl> + query ( " SELECT dictGetInt32 ( ' no_file ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + assert get_status ( " no_file " ) = = " LOADED " <nl> + <nl> + <nl> + def test_reload_after_fail_by_timer ( started_cluster ) : <nl> + query = instance . query <nl> + <nl> + # dictionaries_lazy_load = = false , so this dictionary is not loaded . <nl> + assert get_status ( " no_file_2 " ) = = " NOT_LOADED " <nl> + <nl> + # We expect an error because the file source doesn ' t exist . <nl> + expected_error = " No such file " <nl> + assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> + assert get_status ( " no_file_2 " ) = = " FAILED " <nl> + <nl> + # Passed time should not change anything now , the status is still FAILED . <nl> + time . sleep ( 6 ) ; <nl> + assert expected_error in instance . query_and_get_error ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) <nl> + assert get_status ( " no_file_2 " ) = = " FAILED " <nl> + <nl> + # Creating the file source makes the dictionary able to load . <nl> + instance . copy_file_to_container ( os . path . join ( SCRIPT_DIR , " configs / dictionaries / file . txt " ) , " / etc / clickhouse - server / config . d / no_file_2 . txt " ) <nl> + time . sleep ( 6 ) ; <nl> + query ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + assert get_status ( " no_file_2 " ) = = " LOADED " <nl> + <nl> + # Removing the file source should not spoil the loaded dictionary . <nl> + instance . exec_in_container ( " rm / etc / clickhouse - server / config . d / no_file_2 . txt " ) <nl> + time . sleep ( 6 ) ; <nl> + query ( " SELECT dictGetInt32 ( ' no_file_2 ' , ' a ' , toUInt64 ( 9 ) ) " ) = = " 10 \ n " <nl> + assert get_status ( " no_file_2 " ) = = " LOADED " <nl> + <nl> + <nl> + def test_reload_after_fail_in_cache_dictionary ( started_cluster ) : <nl> + query = instance . query <nl> + query_and_get_error = instance . query_and_get_error <nl> + <nl> + # Can ' t get a value from the cache dictionary because the source ( table ` test . xypairs ` ) doesn ' t respond . <nl> + expected_error = " Table test . xypairs doesn ' t exist " <nl> + assert expected_error in query_and_get_error ( " SELECT dictGetUInt64 ( ' cache_xypairs ' , ' y ' , toUInt64 ( 1 ) ) " ) <nl> + assert get_status ( " cache_xypairs " ) = = " LOADED " <nl> + assert expected_error in get_last_exception ( " cache_xypairs " ) <nl> + <nl> + # Create table ` test . xypairs ` . <nl> + query ( ' ' ' <nl> + DROP TABLE IF EXISTS test . xypairs ; <nl> + CREATE TABLE test . xypairs ( x UInt64 , y UInt64 ) ENGINE = Log ; <nl> + INSERT INTO test . xypairs VALUES ( 1 , 56 ) , ( 3 , 78 ) ; <nl> + ' ' ' ) <nl> + <nl> + # Cache dictionary now works . <nl> + assert_eq_with_retry ( instance , " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 1 ) ) " , " 56 " , ignore_error = True ) <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 2 ) ) " ) = = " 0 " <nl> + assert get_last_exception ( " cache_xypairs " ) = = " " <nl> + <nl> + # Drop table ` test . xypairs ` . <nl> + query ( ' DROP TABLE test . xypairs ' ) <nl> + <nl> + # Values are cached so we can get them . <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 1 ) ) " ) = = " 56 " <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 2 ) ) " ) = = " 0 " <nl> + assert get_last_exception ( " cache_xypairs " ) = = " " <nl> + <nl> + # But we can ' t get a value from the source table which isn ' t cached . <nl> + assert expected_error in query_and_get_error ( " SELECT dictGetUInt64 ( ' cache_xypairs ' , ' y ' , toUInt64 ( 3 ) ) " ) <nl> + assert expected_error in get_last_exception ( " cache_xypairs " ) <nl> + <nl> + # Passed time should not spoil the cache . <nl> + time . sleep ( 5 ) ; <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 1 ) ) " ) = = " 56 " <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 2 ) ) " ) = = " 0 " <nl> + assert expected_error in query_and_get_error ( " SELECT dictGetUInt64 ( ' cache_xypairs ' , ' y ' , toUInt64 ( 3 ) ) " ) <nl> + assert expected_error in get_last_exception ( " cache_xypairs " ) <nl> + <nl> + # Create table ` test . xypairs ` again with changed values . <nl> + query ( ' ' ' <nl> + CREATE TABLE test . xypairs ( x UInt64 , y UInt64 ) ENGINE = Log ; <nl> + INSERT INTO test . xypairs VALUES ( 1 , 57 ) , ( 3 , 79 ) ; <nl> + ' ' ' ) <nl> + <nl> + # The cache dictionary returns new values now . <nl> + assert_eq_with_retry ( instance , " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 1 ) ) " , " 57 " ) <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 2 ) ) " ) = = " 0 " <nl> + query ( " SELECT dictGet ( ' cache_xypairs ' , ' y ' , toUInt64 ( 3 ) ) " ) = = " 79 " <nl> + assert get_last_exception ( " cache_xypairs " ) = = " " <nl> mmm a / dbms / tests / integration / test_storage_kafka / test . py <nl> ppp b / dbms / tests / integration / test_storage_kafka / test . py <nl> def insert ( ) : <nl> assert int ( result ) = = messages_num * threads_num , ' ClickHouse lost some messages : { } ' . format ( result ) <nl> <nl> <nl> - @ pytest . mark . timeout ( 120 ) <nl> + @ pytest . mark . timeout ( 300 ) <nl> def test_kafka_commit_on_block_write ( kafka_cluster ) : <nl> instance . query ( ' ' ' <nl> DROP TABLE IF EXISTS test . view ; <nl> mmm a / dbms / tests / queries / 0_stateless / 00763_lock_buffer . sh <nl> ppp b / dbms / tests / queries / 0_stateless / 00763_lock_buffer . sh <nl> function thread1 ( ) <nl> <nl> function thread2 ( ) <nl> { <nl> - seq 1 1000 | sed - r - e ' s / . + / SELECT count ( ) FROM test . buffer_00763_2 ; / ' | $ { CLICKHOUSE_CLIENT } - - multiquery - - server_logs_file = ' / dev / null ' - - ignore - error 2 > & 1 | grep - vP ' ^ 0 $ | ^ 10 $ | ^ Received exception | ^ Code : 60 | ^ Code : 218 ' <nl> + seq 1 1000 | sed - r - e ' s / . + / SELECT count ( ) FROM test . buffer_00763_2 ; / ' | $ { CLICKHOUSE_CLIENT } - - multiquery - - server_logs_file = ' / dev / null ' - - ignore - error 2 > & 1 | grep - vP ' ^ 0 $ | ^ 10 $ | ^ Received exception | ^ Code : 60 | ^ Code : 218 | ^ Code : 473 ' <nl> } <nl> <nl> thread1 & <nl> mmm a / dbms / tests / queries / 0_stateless / 00763_long_lock_buffer_alter_destination_table . sh <nl> ppp b / dbms / tests / queries / 0_stateless / 00763_long_lock_buffer_alter_destination_table . sh <nl> <nl> # ! / usr / bin / env bash <nl> set - e <nl> <nl> + CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL = none <nl> + <nl> CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> . $ CURDIR / . . / shell_config . sh <nl> <nl> function thread1 ( ) <nl> <nl> function thread2 ( ) <nl> { <nl> - seq 1 2000 | sed - r - e ' s / . + / SELECT sum ( length ( s ) ) FROM test . buffer_00763_1 ; / ' | $ { CLICKHOUSE_CLIENT } - - multiquery - - server_logs_file = ' / dev / null ' - - ignore - error 2 > & 1 | grep - vP ' ^ 3 $ ' <nl> + seq 1 2000 | sed - r - e ' s / . + / SELECT sum ( length ( s ) ) FROM test . buffer_00763_1 ; / ' | $ { CLICKHOUSE_CLIENT } - - multiquery - - ignore - error 2 > & 1 | grep - vP ' ( ^ 3 $ | ^ Received exception from server | ^ Code : 473 ) ' <nl> } <nl> <nl> thread1 & <nl> mmm a / dbms / tests / queries / 0_stateless / 00838_system_tables_drop_table_race . sh <nl> ppp b / dbms / tests / queries / 0_stateless / 00838_system_tables_drop_table_race . sh <nl> CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> $ CLICKHOUSE_CLIENT - q " DROP TABLE IF EXISTS table " <nl> <nl> seq 1 100 | sed - r - e " s / . + / CREATE TABLE table ( x UInt8 ) ENGINE = MergeTree ORDER BY x ; DROP TABLE table ; / " | $ CLICKHOUSE_CLIENT - n & <nl> - seq 1 100 | sed - r - e " s / . + / SELECT * FROM system . tables WHERE database = ' $ { CLICKHOUSE_DATABASE } ' LIMIT 1000000 , 1 ; / " | $ CLICKHOUSE_CLIENT - n & <nl> + seq 1 100 | sed - r - e " s / . + / SELECT * FROM system . tables WHERE database = ' $ { CLICKHOUSE_DATABASE } ' LIMIT 1000000 , 1 ; / " | $ CLICKHOUSE_CLIENT - n 2 > / dev / null & <nl> <nl> wait <nl> mmm a / dbms / tests / queries / 0_stateless / 00909_arrayEnumerateUniq . reference <nl> ppp b / dbms / tests / queries / 0_stateless / 00909_arrayEnumerateUniq . reference <nl> a1 , a2 12 [ 1 , 2 ] <nl> 1 2019 - 06 - 06 1 4 2 1 5 1 [ 1 , 2 ] [ 1001 , 1002 ] [ 1 , 1 ] <nl> 1 2019 - 06 - 06 1 4 2 1 5 0 [ 1 , 2 ] [ 1002 , 1003 ] [ 1 , 1 ] <nl> 1 2019 - 06 - 06 1 4 2 1 6 0 [ 3 ] [ 2001 ] [ 1 ] <nl> + - - empty <nl> + [ [ 1 ] , [ ] , [ 2 ] ] <nl> + [ [ 1 ] , [ ] , [ 2 ] ] <nl> + [ [ 1 ] , [ ] , [ 2 ] , [ ] , [ 3 ] , [ ] , [ 4 ] , [ ] , [ 5 ] , [ ] , [ 6 ] , [ ] , [ 7 ] , [ ] , [ 8 ] , [ ] , [ 9 ] ] <nl> + [ [ ] , [ 1 ] , [ ] , [ 2 ] , [ ] , [ 3 ] , [ ] , [ 4 ] , [ ] , [ 5 ] , [ ] , [ 6 ] , [ ] , [ 7 ] , [ ] , [ 8 ] ] <nl> + [ [ 1 ] , [ 2 ] , [ ] , [ 3 ] ] <nl> mmm a / dbms / tests / queries / 0_stateless / 00909_arrayEnumerateUniq . sql <nl> ppp b / dbms / tests / queries / 0_stateless / 00909_arrayEnumerateUniq . sql <nl> ARRAY JOIN <nl> Test . PuidVal AS PuidValArr ; <nl> <nl> DROP TABLE arr_tests_visits ; <nl> + <nl> + <nl> + select ' - - empty ' ; <nl> + SELECT arrayEnumerateUniqRanked ( [ [ ' a ' ] , [ ] , [ ' a ' ] ] ) ; <nl> + SELECT arrayEnumerateUniqRanked ( [ [ 1 ] , [ ] , [ 1 ] ] ) ; <nl> + SELECT arrayEnumerateUniqRanked ( [ [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] ] ) ; <nl> + SELECT arrayEnumerateUniqRanked ( [ [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] , [ ] , [ 1 ] ] ) ; <nl> + SELECT arrayEnumerateUniqRanked ( [ [ 1 ] , [ 1 ] , [ ] , [ 1 ] ] ) ; <nl> mmm a / dbms / tests / queries / 0_stateless / 00933_test_fix_extra_seek_on_compressed_cache . sh <nl> ppp b / dbms / tests / queries / 0_stateless / 00933_test_fix_extra_seek_on_compressed_cache . sh <nl> $ CLICKHOUSE_CLIENT - - use_uncompressed_cache = 1 - - query_id = " test - query - uncompresse <nl> sleep 1 <nl> $ CLICKHOUSE_CLIENT - - query = " SYSTEM FLUSH LOGS " <nl> <nl> - $ CLICKHOUSE_CLIENT - - query = " SELECT ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' Seek ' ) ] , ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' ReadCompressedBytes ' ) ] , ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' UncompressedCacheHits ' ) ] AS hit FROM system . query_log WHERE ( query_id = ' test - query - uncompressed - cache ' ) AND ( type = 2 ) ORDER BY event_time DESC LIMIT 1 " <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' Seek ' ) ] , ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' ReadCompressedBytes ' ) ] , ProfileEvents . Values [ indexOf ( ProfileEvents . Names , ' UncompressedCacheHits ' ) ] AS hit FROM system . query_log WHERE ( query_id = ' test - query - uncompressed - cache ' ) AND ( type = 2 ) AND event_date > = yesterday ( ) ORDER BY event_time DESC LIMIT 1 " <nl> <nl> $ CLICKHOUSE_CLIENT - - query = " DROP TABLE IF EXISTS small_table " <nl> <nl> mmm a / dbms / tests / queries / 0_stateless / 00933_ttl_with_default . sql <nl> ppp b / dbms / tests / queries / 0_stateless / 00933_ttl_with_default . sql <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 1 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 2 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 3 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 4 ) ; <nl> + select sleep ( 0 . 7 ) format Null ; - - wait if very fast merge happen <nl> optimize table ttl_00933_2 final ; <nl> select a from ttl_00933_2 order by a ; <nl> <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 1 , 100 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 2 , 200 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 3 , 300 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 4 , 400 ) ; <nl> + select sleep ( 0 . 7 ) format Null ; - - wait if very fast merge happen <nl> optimize table ttl_00933_2 final ; <nl> select a , b from ttl_00933_2 order by a ; <nl> <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 1 , 5 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2000 - 10 - 10 00 : 00 : 00 ' ) , 2 , 10 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 3 , 15 ) ; <nl> insert into ttl_00933_2 values ( toDateTime ( ' 2100 - 10 - 10 00 : 00 : 00 ' ) , 4 , 20 ) ; <nl> + select sleep ( 0 . 7 ) format Null ; - - wait if very fast merge happen <nl> optimize table ttl_00933_2 final ; <nl> select a , b from ttl_00933_2 order by a ; <nl> <nl> new file mode 100644 <nl> index 00000000000 . . c4cfb4ed3a4 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00937_template_output_format . reference <nl> <nl> + { prefix } <nl> + n : " 123 " , s1 : qwe , rty , s2 : ' as " df \ ' gh ' , s3 : " " , s4 : " zx <nl> + cv bn m " , d : 2016 - 01 - 01 , n : 123 ; <nl> + n : " 456 " , s1 : as " df \ ' gh , s2 : ' ' , s3 : " zx \ ncv \ tbn m " , s4 : " qwe , rty " , d : 2016 - 01 - 02 , n : 456 ; <nl> + n : " 9876543210 " , s1 : , s2 : ' zx \ ncv \ tbn m ' , s3 : " qwe , rty " , s4 : " as " " df ' gh " , d : 2016 - 01 - 03 , n : 9876543210 ; <nl> + n : " 789 " , s1 : zx \ ncv \ tbn m , s2 : ' qwe , rty ' , s3 : " as \ " df ' gh " , s4 : " " , d : 2016 - 01 - 04 , n : 789 <nl> + mmmmmm <nl> + n : " 0 " , s1 : , s2 : ' ' , s3 : " " , s4 : " " , d : 0000 - 00 - 00 , n : 0 <nl> + mmmmmm <nl> + n : " 123 " , s1 : , s2 : ' ' , s3 : " " , s4 : " " , d : 2016 - 01 - 01 , n : 123 <nl> + mmmmmm <nl> + n : " 9876543210 " , s1 : zx \ ncv \ tbn m , s2 : ' zx \ ncv \ tbn m ' , s3 : " zx \ ncv \ tbn m " , s4 : " zx <nl> + cv bn m " , d : 2016 - 01 - 04 , n : 9876543210 <nl> + 4 rows <nl> + before limit 4 <nl> + read 4 $ suffix $ <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 00000000000 . . 7a981c641da <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00937_template_output_format . sql <nl> <nl> + DROP TABLE IF EXISTS template ; <nl> + CREATE TABLE template ( s1 String , s2 String , ` s 3 ` String , " s 4 " String , n UInt64 , d Date ) ENGINE = Memory ; <nl> + INSERT INTO template VALUES <nl> + ( ' qwe , rty ' , ' as " df ' ' gh ' , ' ' , ' zx \ ncv \ tbn m ' , 123 , ' 2016 - 01 - 01 ' ) , ( ' as " df ' ' gh ' , ' ' , ' zx \ ncv \ tbn m ' , ' qwe , rty ' , 456 , ' 2016 - 01 - 02 ' ) , ( ' ' , ' zx \ ncv \ tbn m ' , ' qwe , rty ' , ' as " df ' ' gh ' , 9876543210 , ' 2016 - 01 - 03 ' ) , ( ' zx \ ncv \ tbn m ' , ' qwe , rty ' , ' as " df ' ' gh ' , ' ' , 789 , ' 2016 - 01 - 04 ' ) ; <nl> + <nl> + SELECT * FROM template WITH TOTALS LIMIT 4 FORMAT Template SETTINGS <nl> + extremes = 1 , <nl> + format_schema = ' { prefix } \ n $ { data : None } \ nmmmmmm \ n $ { totals : } \ nmmmmmm \ n $ { min } \ nmmmmmm \ n $ { max } \ n $ { rows : Escaped } rows \ nbefore limit $ { rows_before_limit : XML } \ nread $ { rows_read : Escaped } $ $ suffix $ $ ' , <nl> + format_schema_rows = ' n : \ t $ { n : JSON } , s1 : \ t $ { s1 : Escaped } , s2 : \ t $ { s2 : Quoted } , s3 : \ t $ { ` s 3 ` : JSON } , s4 : \ t $ { " s 4 " : CSV } , d : \ t $ { d : Escaped } , n : \ t $ { n : Raw } \ t ' , <nl> + format_schema_rows_between_delimiter = ' ; \ n ' ; <nl> + <nl> + DROP TABLE template ; <nl> new file mode 100644 <nl> index 00000000000 . . ce89532886d <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00938_template_input_format . reference <nl> <nl> + = = = = check escaping = = = = <nl> + " qwe , rty " , " as " " df ' gh " , " " , " zx <nl> + cv bn m " , 123 , " 2016 - 01 - 01 " <nl> + " as " " df ' gh " , " " , " zx <nl> + cv bn m " , " qwe , rty " , 456 , " 2016 - 01 - 02 " <nl> + " zx <nl> + cv bn m " , " qwe , rty " , " as " " df ' gh " , " " , 789 , " 2016 - 01 - 04 " <nl> + " " , " zx <nl> + cv bn m " , " qwe , rty " , " as " " df ' gh " , 9876543210 , " 2016 - 01 - 03 " <nl> + = = = = parse json ( sophisticated template ) = = = = <nl> + " qwe , rty " , " as " " df ' gh " , " " , " zx <nl> + cv bn m " , 123 , " 2016 - 01 - 01 " <nl> + " as " " df ' gh " , " " , " zx <nl> + cv bn m " , " qwe , rty " , 456 , " 2016 - 01 - 02 " <nl> + " zx <nl> + cv bn m " , " qwe , rty " , " as " " df ' gh " , " " , 789 , " 2016 - 01 - 04 " <nl> + " " , " zx <nl> + cv bn m " , " qwe , rty " , " as " " df ' gh " , 9876543210 , " 2016 - 01 - 03 " <nl> + = = = = parse json = = = = <nl> + " " , " " , " qwe , rty " , " " , 123 , " 2016 - 01 - 01 " <nl> + " zx <nl> + cv bn m " , " " , " as " " df ' gh " , " " , 456 , " 2016 - 01 - 02 " <nl> + " as " " df ' gh " , " " , " zx <nl> + cv bn m " , " " , 789 , " 2016 - 01 - 04 " <nl> + " qwe , rty " , " " , " " , " " , 9876543210 , " 2016 - 01 - 03 " <nl> new file mode 100755 <nl> index 00000000000 . . c33741543e9 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00938_template_input_format . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " DROP TABLE IF EXISTS template1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query = " DROP TABLE IF EXISTS template2 " ; <nl> + $ CLICKHOUSE_CLIENT - - query = " CREATE TABLE template1 ( s1 String , s2 String , s3 String , s4 String , n UInt64 , d Date ) ENGINE = Memory " ; <nl> + $ CLICKHOUSE_CLIENT - - query = " CREATE TABLE template2 ( s1 String , s2 String , s3 String , s4 String , n UInt64 , d Date ) ENGINE = Memory " ; <nl> + <nl> + echo " = = = = check escaping = = = = " <nl> + <nl> + echo " { prefix } <nl> + n : 123 , s1 : qwe , rty , s2 : ' as \ " df \ \ ' gh ' , s3 : \ " \ " , s4 : \ " zx <nl> + cv bn m \ " , d : 2016 - 01 - 01 ; <nl> + n : 456 , s1 : as \ " df \ \ ' gh , s2 : ' ' , s3 : \ " zx \ \ ncv \ \ tbn m \ " , s4 : \ " qwe , rty \ " , d : 2016 - 01 - 02 ; <nl> + n : 9876543210 , s1 : , s2 : ' zx \ \ ncv \ \ tbn m ' , s3 : \ " qwe , rty \ " , s4 : \ " as \ " \ " df ' gh \ " , d : 2016 - 01 - 03 ; <nl> + n : 789 , s1 : zx \ \ ncv \ \ tbn m , s2 : ' qwe , rty ' , s3 : \ " as \ \ \ " df ' gh \ " , s4 : \ " \ " , d : 2016 - 01 - 04 <nl> + $ suffix $ " | $ CLICKHOUSE_CLIENT - - query = " INSERT INTO template1 FORMAT Template SETTINGS \ <nl> + format_schema = ' { prefix } \ n \ $ { data } \ n \ $ \ $ suffix \ $ \ $ \ n ' , \ <nl> + format_schema_rows = ' n : \ t \ $ { n : Escaped } , s1 : \ t \ $ { s1 : Escaped } \ t , s2 : \ t \ $ { s2 : Quoted } , s3 : \ t \ $ { s3 : JSON } , s4 : \ t \ $ { s4 : CSV } , d : \ t \ $ { d : Escaped } \ t ' , \ <nl> + format_schema_rows_between_delimiter = ' ; \ n ' " ; <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT * FROM template1 ORDER BY n FORMAT CSV " ; <nl> + <nl> + echo " = = = = parse json ( sophisticated template ) = = = = " <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT * FROM template1 ORDER BY n FORMAT JSON " | $ CLICKHOUSE_CLIENT - - query = " INSERT INTO template2 FORMAT TemplateIgnoreSpaces SETTINGS \ <nl> + format_schema = ' { \ $ { : } \ " meta \ " \ $ { : } : \ $ { : } [ \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " s1 \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " String \ " \ $ { : } } \ $ { : } , \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " s2 \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " String \ " \ $ { : } } \ $ { : } , \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " s3 \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " String \ " \ $ { : } } \ $ { : } , \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " s4 \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " String \ " \ $ { : } } \ $ { : } , \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " n \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " UInt64 \ " \ $ { : } } \ $ { : } , \ $ { : } { \ $ { : } \ " name \ " \ $ { : } : \ $ { : } \ " d \ " \ $ { : } , \ $ { : } \ " type \ " \ $ { : } : \ $ { : } \ " Date \ " \ $ { : } } \ $ { : } ] \ $ { : } , \ $ { : } \ " data \ " \ $ { : } : \ $ { : } [ \ $ { data } ] \ $ { : } , \ $ { : } \ " rows \ " \ $ { : } : \ $ { : } \ $ { : CSV } \ $ { : } , \ $ { : } \ " statistics \ " \ $ { : } : \ $ { : } { \ $ { : } \ " elapsed \ " \ $ { : } : \ $ { : } \ $ { : CSV } \ $ { : } , \ $ { : } \ " rows_read \ " \ $ { : } : \ $ { : } \ $ { : CSV } \ $ { : } , \ $ { : } \ " bytes_read \ " \ $ { : } : \ $ { : } \ $ { : CSV } \ $ { : } } \ $ { : } } ' , \ <nl> + format_schema_rows = ' { \ $ { : } \ " s1 \ " \ $ { : } : \ $ { : } \ $ { s1 : JSON } \ $ { : } , \ $ { : } \ " s2 \ " \ $ { : } : \ $ { : } \ $ { s2 : JSON } \ $ { : } , \ $ { : } \ " s3 \ " \ $ { : } : \ $ { : } \ $ { s3 : JSON } \ $ { : } , \ $ { : } \ " s4 \ " \ $ { : } : \ $ { : } \ $ { s4 : JSON } \ $ { : } , \ $ { : } \ " n \ " \ $ { : } : \ $ { : } \ $ { n : JSON } \ $ { : } , \ $ { : } \ " d \ " \ $ { : } : \ $ { : } \ $ { d : JSON } \ $ { : } \ $ { : } } ' , \ <nl> + format_schema_rows_between_delimiter = ' , ' " ; <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT * FROM template2 ORDER BY n FORMAT CSV " ; <nl> + $ CLICKHOUSE_CLIENT - - query = " TRUNCATE TABLE template2 " ; <nl> + <nl> + echo " = = = = parse json = = = = " <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT * FROM template1 ORDER BY n FORMAT JSON " | $ CLICKHOUSE_CLIENT - - query = " INSERT INTO template2 FORMAT TemplateIgnoreSpaces SETTINGS \ <nl> + format_schema = ' { \ $ { : } \ " meta \ " \ $ { : } : \ $ { : JSON } , \ $ { : } \ " data \ " \ $ { : } : \ $ { : } [ \ $ { data } ] \ $ { : } , \ $ { : } \ " rows \ " \ $ { : } : \ $ { : JSON } , \ $ { : } \ " statistics \ " \ $ { : } : \ $ { : JSON } \ $ { : } } ' , \ <nl> + format_schema_rows = ' { \ $ { : } \ " s1 \ " \ $ { : } : \ $ { : } \ $ { s3 : JSON } \ $ { : } , \ $ { : } \ " s2 \ " \ $ { : } : \ $ { : } \ $ { : JSON } \ $ { : } , \ $ { : } \ " s3 \ " \ $ { : } : \ $ { : } \ $ { s1 : JSON } \ $ { : } , \ $ { : } \ " s4 \ " \ $ { : } : \ $ { : } \ $ { : JSON } \ $ { : } , \ $ { : } \ " n \ " \ $ { : } : \ $ { : } \ $ { n : JSON } \ $ { : } , \ $ { : } \ " d \ " \ $ { : } : \ $ { : } \ $ { d : JSON } \ $ { : } \ $ { : } } ' , \ <nl> + format_schema_rows_between_delimiter = ' , ' " ; <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " SELECT * FROM template2 ORDER BY n FORMAT CSV " ; <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query = " DROP TABLE template1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query = " DROP TABLE template2 " ; <nl> deleted file mode 100755 <nl> index 2095683720e . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00960_live_view_watch_events_live . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv EVENTS ' ) <nl> - client1 . expect ( ' 1 . * ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( ' 2 . * ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) <nl> - client1 . expect ( ' 3 . * ' + end_of_block ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100644 <nl> index 6fbbedf1b21 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00961_temporary_live_view_watch . reference <nl> ppp / dev / null <nl> <nl> - 0 1 <nl> - 6 2 <nl> - 21 3 <nl> deleted file mode 100644 <nl> index 7992da92f97 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00961_temporary_live_view_watch . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100755 <nl> index 3dbec01b29a . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00962_temporary_live_view_watch_live . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv ' ) <nl> - client1 . expect ( r ' 0 . * 1 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( r ' 6 . * 2 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) <nl> - client1 . expect ( r ' 21 . * 3 ' + end_of_block ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index b324c1b90cc . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00963_temporary_live_view_watch_live_timeout . py . disabled <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' SET temporary_live_view_timeout = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv ' ) <nl> - client1 . expect ( r ' 0 . * 1 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client2 . expect ( prompt ) <nl> - client1 . expect ( r ' 6 . * 2 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) <nl> - client2 . expect ( prompt ) <nl> - client1 . expect ( r ' 21 . * 3 ' + end_of_block ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' SELECT sleep ( 1 ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( ' Table test . lv doesn \ ' t exist ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index 528f18839bb . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00964_live_view_watch_events_heartbeat . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' SET live_view_heartbeat_interval = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv EVENTS ' ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( ' 2 . * ' + end_of_block ) <nl> - client1 . expect ( ' Progress : 2 . 00 rows . * \ ) ' ) <nl> - # wait for heartbeat <nl> - client1 . expect ( ' Progress : 2 . 00 rows . * \ ) ' ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index 2723936f876 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00965_live_view_watch_heartbeat . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' SET live_view_heartbeat_interval = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv ' ) <nl> - client1 . expect ( r ' 0 . * 1 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( r ' 6 . * 2 ' + end_of_block ) <nl> - client1 . expect ( ' Progress : 2 . 00 rows . * \ ) ' ) <nl> - # wait for heartbeat <nl> - client1 . expect ( ' Progress : 2 . 00 rows . * \ ) ' ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index 72ab3ea8818 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00966_live_view_watch_events_http . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - from httpclient import client as http_client <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 : <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - <nl> - with http_client ( { ' method ' : ' GET ' , ' url ' : ' / ? allow_experimental_live_view = 1 & query = WATCH % 20test . lv % 20EVENTS ' } , name = ' client2 > ' , log = log ) as client2 : <nl> - client2 . expect ( ' . * 1 \ n ' ) <nl> - client1 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( ' . * 2 \ n ' ) <nl> - <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index e2f33971c3d . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00967_live_view_watch_http . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - from httpclient import client as http_client <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 : <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - <nl> - with http_client ( { ' method ' : ' GET ' , ' url ' : ' / ? allow_experimental_live_view = 1 & query = WATCH % 20test . lv ' } , name = ' client2 > ' , log = log ) as client2 : <nl> - client2 . expect ( ' . * 0 \ t1 \ n ' ) <nl> - client1 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( ' . * 6 \ t2 \ n ' ) <nl> - <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100644 <nl> index 5ae423d90d1 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00968_live_view_select_format_jsoneachrowwithprogress . reference <nl> ppp / dev / null <nl> <nl> - { " row " : { " a " : 1 } } <nl> - { " row " : { " a " : 2 } } <nl> - { " row " : { " a " : 3 } } <nl> - { " progress " : { " read_rows " : " 3 " , " read_bytes " : " 36 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } <nl> deleted file mode 100644 <nl> index 1023cdf6b29 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00968_live_view_select_format_jsoneachrowwithprogress . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT * FROM test . mt ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - SELECT * FROM test . lv FORMAT JSONEachRowWithProgress ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 287a1ced92d . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00969_live_view_watch_format_jsoneachrowwithprogress . reference <nl> ppp / dev / null <nl> <nl> - { " row " : { " sum ( a ) " : " 0 " , " _version " : " 1 " } } <nl> - { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 16 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } <nl> - { " row " : { " sum ( a ) " : " 6 " , " _version " : " 2 " } } <nl> - { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 16 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } <nl> - { " row " : { " sum ( a ) " : " 21 " , " _version " : " 3 " } } <nl> - { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 16 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } <nl> deleted file mode 100644 <nl> index 3e46d55c014 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00969_live_view_watch_format_jsoneachrowwithprogress . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - WATCH test . lv LIMIT 0 FORMAT JSONEachRowWithProgress ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 FORMAT JSONEachRowWithProgress ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 FORMAT JSONEachRowWithProgress ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100755 <nl> index 8435cdc147a . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00970_live_view_watch_events_http_heartbeat . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - from httpclient import client as http_client <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 : <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - with http_client ( { ' method ' : ' GET ' , ' url ' : ' / ? allow_experimental_live_view = 1 & live_view_heartbeat_interval = 1 & query = WATCH % 20test . lv % 20EVENTS % 20FORMAT % 20JSONEachRowWithProgress ' } , name = ' client2 > ' , log = log ) as client2 : <nl> - client2 . expect ( ' { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 8 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } \ n ' , escape = True ) <nl> - client2 . expect ( ' { " row " : { " version " : " 1 " } ' , escape = True ) <nl> - client2 . expect ( ' { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 8 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } ' , escape = True ) <nl> - # heartbeat is provided by progress message <nl> - client2 . expect ( ' { " progress " : { " read_rows " : " 1 " , " read_bytes " : " 8 " , " written_rows " : " 0 " , " written_bytes " : " 0 " , " total_rows_to_read " : " 0 " } } ' , escape = True ) <nl> - <nl> - client1 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client2 . expect ( ' { " row " : { " version " : " 2 " } } \ n ' , escape = True ) <nl> - <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100755 <nl> index 2317d705efe . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00971_live_view_watch_http_heartbeat . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - from httpclient import client as http_client <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 : <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - with http_client ( { ' method ' : ' GET ' , ' url ' : ' / ? allow_experimental_live_view = 1 & live_view_heartbeat_interval = 1 & query = WATCH % 20test . lv % 20FORMAT % 20JSONEachRowWithProgress ' } , name = ' client2 > ' , log = log ) as client2 : <nl> - client2 . expect ( ' " progress " . * ' , ) <nl> - client2 . expect ( ' { " row " : { " sum ( a ) " : " 0 " , " _version " : " 1 " } } \ n ' , escape = True ) <nl> - client2 . expect ( ' " progress " . * \ n ' ) <nl> - # heartbeat is provided by progress message <nl> - client2 . expect ( ' " progress " . * \ n ' ) <nl> - <nl> - client1 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( prompt ) <nl> - <nl> - client2 . expect ( ' " progress " . * " read_rows " : " 2 " . * \ n ' ) <nl> - client2 . expect ( ' { " row " : { " sum ( a ) " : " 6 " , " _version " : " 2 " } } \ n ' , escape = True ) <nl> - <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100644 <nl> index 135516b0cd3 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00972_live_view_select_1 . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - <nl> - CREATE LIVE VIEW test . lv AS SELECT 1 ; <nl> - <nl> - SELECT * FROM test . lv ; <nl> - <nl> - DROP TABLE test . lv ; <nl> deleted file mode 100644 <nl> index 75236c0daf7 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00973_live_view_select . reference <nl> ppp / dev / null <nl> <nl> - 6 1 <nl> - 6 1 <nl> - 12 2 <nl> - 12 2 <nl> deleted file mode 100644 <nl> index 4b5ca0a2dd7 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00973_live_view_select . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - SELECT * , _version FROM test . lv ; <nl> - SELECT * , _version FROM test . lv ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - SELECT * , _version FROM test . lv ; <nl> - SELECT * , _version FROM test . lv ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 6d50f0e9c3a . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00974_live_view_select_with_aggregation . reference <nl> ppp / dev / null <nl> <nl> - 6 <nl> - 21 <nl> deleted file mode 100644 <nl> index 3faaec8f623 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00974_live_view_select_with_aggregation . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT * FROM test . mt ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - SELECT sum ( a ) FROM test . lv ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ; <nl> - <nl> - SELECT sum ( a ) FROM test . lv ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> mmm a / dbms / tests / queries / 0_stateless / 00974_text_log_table_not_empty . sh <nl> ppp b / dbms / tests / queries / 0_stateless / 00974_text_log_table_not_empty . sh <nl> do <nl> <nl> $ { CLICKHOUSE_CLIENT } - - query = " SYSTEM FLUSH LOGS " <nl> sleep 0 . 1 ; <nl> - if [ [ $ ( $ CLICKHOUSE_CURL - sS " $ CLICKHOUSE_URL " - d " SELECT count ( ) > 0 FROM system . text_log WHERE position ( system . text_log . message , ' SELECT 6103 ' ) > 0 " ) = = 1 ] ] ; then echo 1 ; exit ; fi ; <nl> + if [ [ $ ( $ CLICKHOUSE_CURL - sS " $ CLICKHOUSE_URL " - d " SELECT count ( ) > 0 FROM system . text_log WHERE position ( system . text_log . message , ' SELECT 6103 ' ) > 0 AND event_date > = yesterday ( ) " ) = = 1 ] ] ; then echo 1 ; exit ; fi ; <nl> <nl> done ; <nl> <nl> deleted file mode 100644 <nl> index e69de29bb2d . . 00000000000 <nl> deleted file mode 100644 <nl> index 02c1644d193 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00975_live_view_create . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT * FROM test . mt ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 453bd800469 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00976_live_view_select_version . reference <nl> ppp / dev / null <nl> <nl> - 1 1 <nl> - 2 1 <nl> - 3 1 <nl> deleted file mode 100644 <nl> index ae1c59a92d7 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00976_live_view_select_version . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT * FROM test . mt ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - SELECT * , _version FROM test . lv ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 01e79c32a8c . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00977_live_view_watch_events . reference <nl> ppp / dev / null <nl> <nl> - 1 <nl> - 2 <nl> - 3 <nl> deleted file mode 100644 <nl> index 3e0d066fb8d . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00977_live_view_watch_events . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - WATCH test . lv EVENTS LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - WATCH test . lv EVENTS LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ; <nl> - <nl> - WATCH test . lv EVENTS LIMIT 0 ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 6fbbedf1b21 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00978_live_view_watch . reference <nl> ppp / dev / null <nl> <nl> - 0 1 <nl> - 6 2 <nl> - 21 3 <nl> deleted file mode 100644 <nl> index b8d0d93ccab . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00978_live_view_watch . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ; <nl> - <nl> - WATCH test . lv LIMIT 0 ; <nl> - <nl> - DROP TABLE test . lv ; <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100755 <nl> index 8c5bc5b8eb2 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00979_live_view_watch_live . py <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - CURDIR = os . path . dirname ( os . path . realpath ( __file__ ) ) <nl> - sys . path . insert ( 0 , os . path . join ( CURDIR , ' helpers ' ) ) <nl> - <nl> - from client import client , prompt , end_of_block <nl> - <nl> - log = None <nl> - # uncomment the line below for debugging <nl> - # log = sys . stdout <nl> - <nl> - with client ( name = ' client1 > ' , log = log ) as client1 , client ( name = ' client2 > ' , log = log ) as client2 : <nl> - client1 . expect ( prompt ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client1 . expect ( prompt ) <nl> - client2 . send ( ' SET allow_experimental_live_view = 1 ' ) <nl> - client2 . expect ( prompt ) <nl> - <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE IF EXISTS test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' WATCH test . lv ' ) <nl> - client1 . expect ( r ' 0 . * 1 ' + end_of_block ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) <nl> - client1 . expect ( r ' 6 . * 2 ' + end_of_block ) <nl> - client2 . expect ( prompt ) <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) <nl> - client1 . expect ( r ' 21 . * 3 ' + end_of_block ) <nl> - client2 . expect ( prompt ) <nl> - for i in range ( 1 , 129 ) : <nl> - client2 . send ( ' INSERT INTO test . mt VALUES ( 1 ) ' ) <nl> - client1 . expect ( r ' % d . * % d ' % ( 21 + i , 3 + i ) + end_of_block ) <nl> - client2 . expect ( prompt ) <nl> - # send Ctrl - C <nl> - client1 . send ( ' \ x03 ' , eol = ' ' ) <nl> - match = client1 . expect ( ' ( % s ) | ( [ # \ $ ] ) ' % prompt ) <nl> - if match . groups ( ) [ 1 ] : <nl> - client1 . send ( client1 . command ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . lv ' ) <nl> - client1 . expect ( prompt ) <nl> - client1 . send ( ' DROP TABLE test . mt ' ) <nl> - client1 . expect ( prompt ) <nl> deleted file mode 100644 <nl> index e69de29bb2d . . 00000000000 <nl> deleted file mode 100644 <nl> index 7f9fcbb2e9c . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00980_create_temporary_live_view . reference <nl> ppp / dev / null <nl> <nl> - temporary_live_view_timeout 5 <nl> - live_view_heartbeat_interval 15 <nl> - 0 <nl> deleted file mode 100644 <nl> index 037c2a9e587 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00980_create_temporary_live_view . sql <nl> ppp / dev / null <nl> <nl> - SET allow_experimental_live_view = 1 ; <nl> - <nl> - DROP TABLE IF EXISTS test . lv ; <nl> - DROP TABLE IF EXISTS test . mt ; <nl> - <nl> - SELECT name , value from system . settings WHERE name = ' temporary_live_view_timeout ' ; <nl> - SELECT name , value from system . settings WHERE name = ' live_view_heartbeat_interval ' ; <nl> - <nl> - SET temporary_live_view_timeout = 1 ; <nl> - CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ; <nl> - CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ; <nl> - <nl> - SHOW TABLES LIKE ' lv ' ; <nl> - SELECT sleep ( 2 ) ; <nl> - SHOW TABLES LIKE ' lv ' ; <nl> - <nl> - DROP TABLE test . mt ; <nl> deleted file mode 100644 <nl> index 782671cdfaf . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_live_view_watch_event_live . python <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - <nl> - import subprocess <nl> - import threading <nl> - import Queue as queue <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - <nl> - CLICKHOUSE_CLIENT = os . environ . get ( ' CLICKHOUSE_CLIENT ' ) <nl> - CLICKHOUSE_CURL = os . environ . get ( ' CLICKHOUSE_CURL ' ) <nl> - CLICKHOUSE_URL = os . environ . get ( ' CLICKHOUSE_URL ' ) <nl> - <nl> - <nl> - def send_query ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout <nl> - <nl> - <nl> - def send_query_in_process_group ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , preexec_fn = os . setsid ) <nl> - <nl> - <nl> - def read_lines_and_push_to_queue ( pipe , queue ) : <nl> - try : <nl> - for line in iter ( pipe . readline , ' ' ) : <nl> - line = line . strip ( ) <nl> - print ( line ) <nl> - sys . stdout . flush ( ) <nl> - queue . put ( line ) <nl> - except KeyboardInterrupt : <nl> - pass <nl> - <nl> - queue . put ( None ) <nl> - <nl> - <nl> - def test ( ) : <nl> - send_query ( ' DROP TABLE IF EXISTS test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE IF EXISTS test . mt ' ) . read ( ) <nl> - send_query ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) . read ( ) <nl> - send_query ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) . read ( ) <nl> - <nl> - q = queue . Queue ( ) <nl> - p = send_query_in_process_group ( ' WATCH test . lv ' ) <nl> - thread = threading . Thread ( target = read_lines_and_push_to_queue , args = ( p . stdout , q ) ) <nl> - thread . start ( ) <nl> - <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 0 \ t1 ' ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 6 \ t2 ' ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 21 \ t3 ' ) <nl> - <nl> - # Send Ctrl + C to client . <nl> - os . killpg ( os . getpgid ( p . pid ) , signal . SIGINT ) <nl> - # This insert shouldn ' t affect lv . <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 7 ) , ( 8 ) , ( 9 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line is None ) <nl> - <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - <nl> - thread . join ( ) <nl> - <nl> - test ( ) <nl> deleted file mode 100644 <nl> index 1e94cdade41 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_live_view_watch_event_live . reference <nl> ppp / dev / null <nl> <nl> - 0 1 <nl> - 0 1 <nl> - 6 2 <nl> - 6 2 <nl> - 21 3 <nl> - 21 3 <nl> - None <nl> deleted file mode 100755 <nl> index 938547ca0cb . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_live_view_watch_http . python <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - <nl> - import subprocess <nl> - import threading <nl> - import Queue as queue <nl> - import os <nl> - import sys <nl> - <nl> - <nl> - CLICKHOUSE_CLIENT = os . environ . get ( ' CLICKHOUSE_CLIENT ' ) <nl> - CLICKHOUSE_CURL = os . environ . get ( ' CLICKHOUSE_CURL ' ) <nl> - CLICKHOUSE_URL = os . environ . get ( ' CLICKHOUSE_URL ' ) <nl> - <nl> - <nl> - def send_query ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout <nl> - <nl> - <nl> - def send_http_query ( query ) : <nl> - cmd = list ( CLICKHOUSE_CURL . split ( ) ) # list ( [ ' curl ' , ' - sSN ' , ' - - max - time ' , ' 10 ' ] ) <nl> - cmd + = [ ' - sSN ' , CLICKHOUSE_URL , ' - d ' , query ] <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout <nl> - <nl> - <nl> - def read_lines_and_push_to_queue ( pipe , queue ) : <nl> - for line in iter ( pipe . readline , ' ' ) : <nl> - line = line . strip ( ) <nl> - print ( line ) <nl> - sys . stdout . flush ( ) <nl> - queue . put ( line ) <nl> - <nl> - queue . put ( None ) <nl> - <nl> - <nl> - def test ( ) : <nl> - send_query ( ' DROP TABLE IF EXISTS test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE IF EXISTS test . mt ' ) . read ( ) <nl> - send_query ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) . read ( ) <nl> - send_query ( ' CREATE LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) . read ( ) <nl> - <nl> - q = queue . Queue ( ) <nl> - pipe = send_http_query ( ' WATCH test . lv ' ) <nl> - thread = threading . Thread ( target = read_lines_and_push_to_queue , args = ( pipe , q ) ) <nl> - thread . start ( ) <nl> - <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 0 \ t1 ' ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 6 \ t2 ' ) <nl> - <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - <nl> - thread . join ( ) <nl> - <nl> - test ( ) <nl> deleted file mode 100644 <nl> index 489457d751b . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_live_view_watch_http . reference <nl> ppp / dev / null <nl> <nl> - 0 1 <nl> - 0 1 <nl> - 6 2 <nl> - 6 2 <nl> deleted file mode 100644 <nl> index 70063adc6e3 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_temporary_live_view_watch_events_heartbeat . python <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - <nl> - import subprocess <nl> - import threading <nl> - import Queue as queue <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - <nl> - CLICKHOUSE_CLIENT = os . environ . get ( ' CLICKHOUSE_CLIENT ' ) <nl> - CLICKHOUSE_CURL = os . environ . get ( ' CLICKHOUSE_CURL ' ) <nl> - CLICKHOUSE_URL = os . environ . get ( ' CLICKHOUSE_URL ' ) <nl> - <nl> - <nl> - def send_query ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout <nl> - <nl> - <nl> - def send_query_in_process_group ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query , ' - - live_view_heartbeat_interval = 1 ' , ' - - progress ' ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , preexec_fn = os . setsid ) <nl> - <nl> - <nl> - def read_lines_and_push_to_queue ( pipe , queue ) : <nl> - try : <nl> - for line in iter ( pipe . readline , ' ' ) : <nl> - line = line . strip ( ) <nl> - # print ( line ) <nl> - sys . stdout . flush ( ) <nl> - queue . put ( line ) <nl> - except KeyboardInterrupt : <nl> - pass <nl> - <nl> - queue . put ( None ) <nl> - <nl> - <nl> - def test ( ) : <nl> - send_query ( ' DROP TABLE IF EXISTS test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE IF EXISTS test . mt ' ) . read ( ) <nl> - send_query ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) . read ( ) <nl> - send_query ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) . read ( ) <nl> - <nl> - q = queue . Queue ( ) <nl> - p = send_query_in_process_group ( ' WATCH test . lv ' ) <nl> - thread = threading . Thread ( target = read_lines_and_push_to_queue , args = ( p . stdout , q ) ) <nl> - thread . start ( ) <nl> - <nl> - line = q . get ( ) <nl> - # print ( line ) <nl> - assert ( line . endswith ( ' 0 \ t1 ' ) ) <nl> - assert ( ' Progress : 0 . 00 rows ' in line ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - assert ( line . endswith ( ' 6 \ t2 ' ) ) <nl> - assert ( ' Progress : 1 . 00 rows ' in line ) <nl> - <nl> - # send_query ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) . read ( ) <nl> - # line = q . get ( ) <nl> - # print ( line ) <nl> - # assert ( line . endswith ( ' 6 \ t2 ' ) ) <nl> - # assert ( ' Progress : 1 . 00 rows ' in line ) <nl> - <nl> - # Send Ctrl + C to client . <nl> - os . killpg ( os . getpgid ( p . pid ) , signal . SIGINT ) <nl> - # This insert shouldn ' t affect lv . <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 7 ) , ( 8 ) , ( 9 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - # print ( line ) <nl> - # assert ( line is None ) <nl> - <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - <nl> - thread . join ( ) <nl> - <nl> - test ( ) <nl> deleted file mode 100644 <nl> index e69de29bb2d . . 00000000000 <nl> deleted file mode 100644 <nl> index d290018a02c . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_temporary_live_view_watch_live . python <nl> ppp / dev / null <nl> <nl> - # ! / usr / bin / env python <nl> - <nl> - import subprocess <nl> - import threading <nl> - import Queue as queue <nl> - import os <nl> - import sys <nl> - import signal <nl> - <nl> - <nl> - CLICKHOUSE_CLIENT = os . environ . get ( ' CLICKHOUSE_CLIENT ' ) <nl> - CLICKHOUSE_CURL = os . environ . get ( ' CLICKHOUSE_CURL ' ) <nl> - CLICKHOUSE_URL = os . environ . get ( ' CLICKHOUSE_URL ' ) <nl> - <nl> - <nl> - def send_query ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) . stdout <nl> - <nl> - <nl> - def send_query_in_process_group ( query ) : <nl> - cmd = list ( CLICKHOUSE_CLIENT . split ( ) ) <nl> - cmd + = [ ' - - query ' , query ] <nl> - # print ( cmd ) <nl> - return subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , preexec_fn = os . setsid ) <nl> - <nl> - <nl> - def read_lines_and_push_to_queue ( pipe , queue ) : <nl> - try : <nl> - for line in iter ( pipe . readline , ' ' ) : <nl> - line = line . strip ( ) <nl> - print ( line ) <nl> - sys . stdout . flush ( ) <nl> - queue . put ( line ) <nl> - except KeyboardInterrupt : <nl> - pass <nl> - <nl> - queue . put ( None ) <nl> - <nl> - <nl> - def test ( ) : <nl> - send_query ( ' DROP TABLE IF EXISTS test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE IF EXISTS test . mt ' ) . read ( ) <nl> - send_query ( ' CREATE TABLE test . mt ( a Int32 ) Engine = MergeTree order by tuple ( ) ' ) . read ( ) <nl> - send_query ( ' CREATE TEMPORARY LIVE VIEW test . lv AS SELECT sum ( a ) FROM test . mt ' ) . read ( ) <nl> - <nl> - q = queue . Queue ( ) <nl> - p = send_query_in_process_group ( ' WATCH test . lv ' ) <nl> - thread = threading . Thread ( target = read_lines_and_push_to_queue , args = ( p . stdout , q ) ) <nl> - thread . start ( ) <nl> - <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 0 \ t1 ' ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 1 ) , ( 2 ) , ( 3 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 6 \ t2 ' ) <nl> - <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 4 ) , ( 5 ) , ( 6 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line = = ' 21 \ t3 ' ) <nl> - <nl> - # Send Ctrl + C to client . <nl> - os . killpg ( os . getpgid ( p . pid ) , signal . SIGINT ) <nl> - # This insert shouldn ' t affect lv . <nl> - send_query ( ' INSERT INTO test . mt VALUES ( 7 ) , ( 8 ) , ( 9 ) ' ) . read ( ) <nl> - line = q . get ( ) <nl> - print ( line ) <nl> - assert ( line is None ) <nl> - <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - send_query ( ' DROP TABLE if exists test . lv ' ) . read ( ) <nl> - <nl> - thread . join ( ) <nl> - <nl> - test ( ) <nl> deleted file mode 100644 <nl> index 1e94cdade41 . . 00000000000 <nl> mmm a / dbms / tests / queries / 0_stateless / 00991_temporary_live_view_watch_live . reference <nl> ppp / dev / null <nl> <nl> - 0 1 <nl> - 0 1 <nl> - 6 2 <nl> - 6 2 <nl> - 21 3 <nl> - 21 3 <nl> - None <nl> similarity index 50 % <nl> rename from dbms / tests / queries / 0_stateless / 00972_live_view_select_1 . reference <nl> rename to dbms / tests / queries / 0_stateless / 01000_bad_size_of_marks_skip_idx . reference <nl> mmm a / dbms / tests / queries / 0_stateless / 00972_live_view_select_1 . reference <nl> ppp b / dbms / tests / queries / 0_stateless / 01000_bad_size_of_marks_skip_idx . reference <nl> @ @ - 1 + 1 , 2 @ @ <nl> 1 <nl> + 1 <nl> new file mode 100644 <nl> index 00000000000 . . 7af19fec695 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01000_bad_size_of_marks_skip_idx . sql <nl> <nl> + SET allow_experimental_data_skipping_indices = 1 ; <nl> + <nl> + DROP TABLE IF EXISTS bad_skip_idx ; <nl> + <nl> + CREATE TABLE bad_skip_idx <nl> + ( <nl> + id UInt64 , <nl> + value String <nl> + ) ENGINE MergeTree ( ) <nl> + ORDER BY id SETTINGS index_granularity_bytes = 64 , vertical_merge_algorithm_min_rows_to_activate = 0 , vertical_merge_algorithm_min_columns_to_activate = 0 ; - - actually vertical merge is not required condition for this bug , but it ' s more easy to reproduce ( becuse we don ' t recalc granularities ) <nl> + <nl> + - - 7 rows per granule <nl> + INSERT INTO bad_skip_idx SELECT number , concat ( ' x ' , toString ( number ) ) FROM numbers ( 1000 ) ; <nl> + <nl> + - - 3 rows per granule <nl> + INSERT INTO bad_skip_idx SELECT number , concat ( ' xxxxxxxxxx ' , toString ( number ) ) FROM numbers ( 1000 , 1000 ) ; <nl> + <nl> + SELECT COUNT ( * ) from bad_skip_idx WHERE value = ' xxxxxxxxxx1015 ' ; - - check no exception <nl> + <nl> + INSERT INTO bad_skip_idx SELECT number , concat ( ' x ' , toString ( number ) ) FROM numbers ( 1000 ) ; <nl> + <nl> + ALTER TABLE bad_skip_idx ADD INDEX idx value TYPE bloom_filter ( 0 . 01 ) GRANULARITY 4 ; <nl> + <nl> + OPTIMIZE TABLE bad_skip_idx FINAL ; <nl> + <nl> + SELECT COUNT ( * ) from bad_skip_idx WHERE value = ' xxxxxxxxxx1015 ' ; - - check no exception <nl> + <nl> + DROP TABLE IF EXISTS bad_skip_idx ; <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00964_live_view_watch_events_heartbeat . reference <nl> rename to dbms / tests / queries / 0_stateless / 01001_rename_merge_race_condition . reference <nl> new file mode 100755 <nl> index 00000000000 . . b0f1dda7c45 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01001_rename_merge_race_condition . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test2 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE test1 ( x UInt64 ) ENGINE = Memory " ; <nl> + <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + seq 1 1000 | sed - r - e ' s / . + / RENAME TABLE test1 TO test2 ; RENAME TABLE test2 TO test1 ; / ' | $ CLICKHOUSE_CLIENT - n <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT * FROM merge ( currentDatabase ( ) , ' ^ test [ 12 ] $ ' ) " <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + wait <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test2 " ; <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00965_live_view_watch_heartbeat . reference <nl> rename to dbms / tests / queries / 0_stateless / 01002_alter_nullable_adaptive_granularity . reference <nl> new file mode 100755 <nl> index 00000000000 . . 85fc847f3f3 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01002_alter_nullable_adaptive_granularity . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test " ; <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE test ( x UInt8 , s String MATERIALIZED toString ( rand64 ( ) ) ) ENGINE = MergeTree ORDER BY s " ; <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " INSERT INTO test SELECT rand ( ) FROM numbers ( 1000 ) " ; <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - n - - query " ALTER TABLE test MODIFY COLUMN x Nullable ( UInt8 ) ; " ; <nl> + sleep 0 . 0 $ RANDOM <nl> + $ CLICKHOUSE_CLIENT - n - - query " ALTER TABLE test MODIFY COLUMN x UInt8 ; " ; <nl> + sleep 0 . 0 $ RANDOM <nl> + done <nl> + } <nl> + <nl> + function thread3 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - n - - query " SELECT count ( ) FROM test FORMAT Null " ; <nl> + done <nl> + } <nl> + <nl> + function thread4 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - n - - query " OPTIMIZE TABLE test FINAL " ; <nl> + sleep 0 . 1 $ RANDOM <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + export - f thread3 ; <nl> + export - f thread4 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread4 2 > / dev / null & <nl> + <nl> + wait <nl> + <nl> + $ CLICKHOUSE_CLIENT - q " DROP TABLE test " <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00966_live_view_watch_events_http . reference <nl> rename to dbms / tests / queries / 0_stateless / 01003_kill_query_race_condition . reference <nl> new file mode 100755 <nl> index 00000000000 . . d8a73ac24a4 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01003_kill_query_race_condition . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query_id = hello - - query " SELECT count ( ) FROM numbers ( 1000000000 ) " - - format Null ; <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " KILL QUERY WHERE query_id = ' hello ' " - - format Null ; <nl> + sleep 0 . $ RANDOM <nl> + done <nl> + } <nl> + <nl> + function thread3 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SHOW PROCESSLIST " - - format Null ; <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT * FROM system . processes " - - format Null ; <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + export - f thread3 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + <nl> + wait <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00967_live_view_watch_http . reference <nl> rename to dbms / tests / queries / 0_stateless / 01004_rename_deadlock . reference <nl> new file mode 100755 <nl> index 00000000000 . . 5d5726bb001 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01004_rename_deadlock . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test2 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE test1 ( x UInt8 ) ENGINE = MergeTree ORDER BY x " ; <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE test2 ( x UInt8 ) ENGINE = MergeTree ORDER BY x " ; <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " RENAME TABLE test1 TO test_tmp , test2 TO test1 , test_tmp TO test2 " <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT * FROM test1 UNION ALL SELECT * FROM test2 " - - format Null <nl> + done <nl> + } <nl> + <nl> + function thread3 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT * FROM system . tables " - - format Null <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + export - f thread3 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + <nl> + wait <nl> + <nl> + $ CLICKHOUSE_CLIENT - q " DROP TABLE test1 " <nl> + $ CLICKHOUSE_CLIENT - q " DROP TABLE test2 " <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00970_live_view_watch_events_http_heartbeat . reference <nl> rename to dbms / tests / queries / 0_stateless / 01005_rwr_shard_deadlock . reference <nl> new file mode 100755 <nl> index 00000000000 . . 1afd3acd324 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01005_rwr_shard_deadlock . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS test1 " ; <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE test1 ( x UInt8 ) ENGINE = MergeTree ORDER BY tuple ( ) " ; <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE test1 MODIFY COLUMN x Nullable ( UInt8 ) " <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE test1 MODIFY COLUMN x UInt8 " <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " SELECT x FROM test1 WHERE x IN ( SELECT x FROM remote ( ' 127 . 0 . 0 . 2 ' , currentDatabase ( ) , test1 ) ) " - - format Null <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + <nl> + wait <nl> + <nl> + $ CLICKHOUSE_CLIENT - q " DROP TABLE test1 " <nl> similarity index 100 % <nl> rename from dbms / tests / queries / 0_stateless / 00971_live_view_watch_http_heartbeat . reference <nl> rename to dbms / tests / queries / 0_stateless / 01007_r1r2_w_r2r1_deadlock . reference <nl> new file mode 100755 <nl> index 00000000000 . . e28cf5d9f7b <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01007_r1r2_w_r2r1_deadlock . sh <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + CURDIR = $ ( cd " $ ( dirname " $ { BASH_SOURCE [ 0 ] } " ) " & & pwd ) <nl> + . $ CURDIR / . . / shell_config . sh <nl> + <nl> + set - e <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS a " <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE IF EXISTS b " <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE a ( x UInt8 ) ENGINE = MergeTree ORDER BY tuple ( ) " <nl> + $ CLICKHOUSE_CLIENT - - query " CREATE TABLE b ( x UInt8 ) ENGINE = MergeTree ORDER BY tuple ( ) " <nl> + <nl> + <nl> + function thread1 ( ) <nl> + { <nl> + while true ; do <nl> + seq 1 100 | awk ' { print " SELECT x FROM a WHERE x IN ( SELECT toUInt8 ( count ( ) ) FROM system . tables ) ; " } ' | $ CLICKHOUSE_CLIENT - n <nl> + done <nl> + } <nl> + <nl> + function thread2 ( ) <nl> + { <nl> + while true ; do <nl> + seq 1 100 | awk ' { print " SELECT x FROM b WHERE x IN ( SELECT toUInt8 ( count ( ) ) FROM system . tables ) ; " } ' | $ CLICKHOUSE_CLIENT - n <nl> + done <nl> + } <nl> + <nl> + function thread3 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE a MODIFY COLUMN x Nullable ( UInt8 ) " <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE a MODIFY COLUMN x UInt8 " <nl> + done <nl> + } <nl> + <nl> + function thread4 ( ) <nl> + { <nl> + while true ; do <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE b MODIFY COLUMN x Nullable ( UInt8 ) " <nl> + $ CLICKHOUSE_CLIENT - - query " ALTER TABLE b MODIFY COLUMN x UInt8 " <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread1 ; <nl> + export - f thread2 ; <nl> + export - f thread3 ; <nl> + export - f thread4 ; <nl> + <nl> + TIMEOUT = 10 <nl> + <nl> + timeout $ TIMEOUT bash - c thread1 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread2 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread3 2 > / dev / null & <nl> + timeout $ TIMEOUT bash - c thread4 2 > / dev / null & <nl> + <nl> + wait <nl> + <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE a " <nl> + $ CLICKHOUSE_CLIENT - - query " DROP TABLE b " <nl> new file mode 100644 <nl> index 00000000000 . . 2f3b99134b8 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01008_materialized_view_henyihanwobushi . reference <nl> @ @ - 0 , 0 + 1 @ @ <nl> + 0000 - 00 - 00 1 bar_n_1 1 <nl> new file mode 100644 <nl> index 00000000000 . . 8deec159dca <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 01008_materialized_view_henyihanwobushi . sql <nl> <nl> + DROP TABLE IF EXISTS foo ; <nl> + DROP TABLE IF EXISTS bar ; <nl> + DROP TABLE IF EXISTS view_foo_bar ; <nl> + <nl> + create table foo ( ddate Date , id Int64 , n String ) ENGINE = ReplacingMergeTree ( ddate , ( id ) , 8192 ) ; <nl> + create table bar ( ddate Date , id Int64 , n String , foo_id Int64 ) ENGINE = ReplacingMergeTree ( ddate , ( id ) , 8192 ) ; <nl> + insert into bar ( id , n , foo_id ) values ( 1 , ' bar_n_1 ' , 1 ) ; <nl> + create MATERIALIZED view view_foo_bar ENGINE = ReplacingMergeTree ( ddate , ( bar_id ) , 8192 ) as select ddate , bar_id , bar_n , foo_id , foo_n from ( select ddate , id as bar_id , n as bar_n , foo_id from bar ) any left join ( select id as foo_id , n as foo_n from foo ) using foo_id ; <nl> + insert into bar ( id , n , foo_id ) values ( 1 , ' bar_n_1 ' , 1 ) ; <nl> + SELECT * FROM view_foo_bar ; <nl> + <nl> + DROP TABLE foo ; <nl> + DROP TABLE bar ; <nl> + DROP TABLE view_foo_bar ; <nl> new file mode 100755 <nl> index 00000000000 . . 4a6ad411298 <nl> mmm / dev / null <nl> ppp b / dbms / tests / stress <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + # https : / / stackoverflow . com / questions / 360201 / how - do - i - kill - background - processes - jobs - when - my - shell - script - exits <nl> + trap ' kill - 9 $ ( jobs - p ) ' EXIT <nl> + <nl> + function thread ( ) <nl> + { <nl> + while true ; do <nl> + . / clickhouse - test - - order random 2 > & 1 | awk ' / ^ \ w + : / { printf ( " \ 033 [ 0 ; % s % sm \ 033 [ 0m " , ( ' $ 1 ' % 2 ? " 4 " : " 10 " ) , ( int ( ' $ 1 ' / 2 ) % 8 ) ) } ' <nl> + done <nl> + } <nl> + <nl> + # https : / / stackoverflow . com / questions / 9954794 / execute - a - shell - function - with - timeout <nl> + export - f thread ; <nl> + <nl> + NUM_THREADS = $ { 1 : - " 16 " } <nl> + TIMEOUT = $ { 2 : - " 300 " } <nl> + <nl> + for i in $ ( seq 1 $ NUM_THREADS ) ; do <nl> + timeout $ TIMEOUT bash - c " thread $ i " 2 > / dev / null & <nl> + done <nl> + <nl> + wait <nl> mmm a / docker / packager / packager <nl> ppp b / docker / packager / packager <nl> def parse_env_variables ( build_type , compiler , sanitizer , package_type , cache , di <nl> result . append ( " ALIEN_PKGS = ' " + ' ' . join ( [ ' - - ' + pkg for pkg in alien_pkgs ] ) + " ' " ) <nl> <nl> if unbundled : <nl> - cmake_flags . append ( ' - DUNBUNDLED = 1 - DENABLE_MYSQL = 0 - DENABLE_POCO_ODBC = 0 - DENABLE_ODBC = 0 - DUSE_CAPNP = 0 ' ) <nl> + cmake_flags . append ( ' - DUNBUNDLED = 1 - DENABLE_MYSQL = 0 - DENABLE_POCO_ODBC = 0 - DENABLE_ODBC = 0 ' ) <nl> <nl> if split_binary : <nl> cmake_flags . append ( ' - DUSE_STATIC_LIBRARIES = 0 - DSPLIT_SHARED_LIBRARIES = 1 - DCLICKHOUSE_SPLIT_BINARY = 1 ' ) <nl> mmm a / docs / en / interfaces / formats . md <nl> ppp b / docs / en / interfaces / formats . md <nl> The supported formats are : <nl> | [ TabSeparatedRaw ] ( # tabseparatedraw ) | ✗ | ✔ | <nl> | [ TabSeparatedWithNames ] ( # tabseparatedwithnames ) | ✔ | ✔ | <nl> | [ TabSeparatedWithNamesAndTypes ] ( # tabseparatedwithnamesandtypes ) | ✔ | ✔ | <nl> + | [ Template ] ( # template ) | ✔ | ✔ | <nl> + | [ TemplateIgnoreSpaces ] ( # templateignorespaces ) | ✔ | ✗ | <nl> | [ CSV ] ( # csv ) | ✔ | ✔ | <nl> | [ CSVWithNames ] ( # csvwithnames ) | ✔ | ✔ | <nl> | [ Values ] ( # data - format - values ) | ✔ | ✔ | <nl> During parsing , the first and second rows are completely ignored . <nl> <nl> This format is also available under the name ` TSVWithNamesAndTypes ` . <nl> <nl> + # # Template { # template } <nl> + <nl> + This format allows to specify a custom format string with placeholders for values with specified escaping rule . <nl> + <nl> + It uses settings ` format_schema ` , ` format_schema_rows ` , ` format_schema_rows_between_delimiter ` and some settings of other formats ( e . g . ` output_format_json_quote_64bit_integers ` when using ` JSON ` escaping , see further ) <nl> + <nl> + Format string ` format_schema_rows ` specifies rows format with the following syntax : <nl> + <nl> + ` delimiter_1 $ { column_1 : serializeAs_1 } delimiter_2 $ { column_2 : serializeAs_2 } . . . delimiter_N ` , <nl> + <nl> + where ` delimiter_i ` is a delimiter between values ( ` $ ` symbol can be escaped as ` $ $ ` ) , <nl> + ` column_i ` is a name of a column whose values are to be selected or inserted ( if empty , then column will be skipped ) , <nl> + ` serializeAs_i ` is an escaping rule for the column values . The following escaping rules are supported : <nl> + <nl> + - ` CSV ` , ` JSON ` , ` XML ` ( similarly to the formats of the same names ) <nl> + - ` Escaped ` ( similarly to ` TSV ` ) <nl> + - ` Quoted ` ( similarly to ` Values ` ) <nl> + - ` Raw ` ( without escaping , similarly to ` TSVRaw ` ) <nl> + - ` None ` ( no escaping rule , see further ) <nl> + <nl> + If escaping rule is omitted , then ` None ` will be used . ` XML ` and ` Raw ` are suitable only for output . <nl> + <nl> + So , for the following format string : <nl> + <nl> + ` Search phrase : $ { SearchPhrase : Quoted } , count : $ { c : Escaped } , ad price : $ $ $ { price : JSON } ; ` <nl> + <nl> + the values of ` SearchPhrase ` , ` c ` and ` price ` columns , which are escaped as ` Quoted ` , ` Escaped ` and ` JSON ` will be printed ( for select ) or will be expected ( for insert ) between ` Search phrase : ` , ` , count : ` , ` , ad price : $ ` and ` ; ` delimiters respectively . For example : <nl> + <nl> + ` Search phrase : ' bathroom interior design ' , count : 2166 , ad price : $ 3 ; ` <nl> + <nl> + The ` format_schema_rows_between_delimiter ` setting specifies delimiter between rows , which is printed ( or expected ) after every row except the last one ( ` \ n ` by default ) <nl> + <nl> + Format string ` format_schema ` has the same syntax as ` format_schema_rows ` and allows to specify a prefix , a suffix and a way to print some additional information . It contains the following placeholders instead of column names : <nl> + <nl> + - ` data ` is the rows with data in ` format_schema_rows ` format , separated by ` format_schema_rows_between_delimiter ` . This placeholder must be the first placeholder in the format string . <nl> + - ` totals ` is the row with total values in ` format_schema_rows ` format ( when using WITH TOTALS ) <nl> + - ` min ` is the row with minimum values in ` format_schema_rows ` format ( when extremes is set to 1 ) <nl> + - ` max ` is the row with maximum values in ` format_schema_rows ` format ( when extremes is set to 1 ) <nl> + - ` rows ` is the total number of output rows <nl> + - ` rows_before_limit ` is the minimal number of rows there would have been without LIMIT . Output only if the query contains LIMIT . If the query contains GROUP BY , rows_before_limit_at_least is the exact number of rows there would have been without a LIMIT . <nl> + - ` time ` is the request execution time in seconds <nl> + - ` rows_read ` is the number of rows have been read <nl> + - ` bytes_read ` is the number of bytes ( uncompressed ) have been read <nl> + <nl> + The placeholders ` data ` , ` totals ` , ` min ` and ` max ` must not have escaping rule specified ( or ` None ` must be specified explicitly ) . The remaining placeholders may have any escaping rule specified . <nl> + If the ` format_schema ` setting is an empty string , ` $ { data } ` is used as default value . <nl> + For insert queries format allows to skip some columns or some fields if prefix or suffix ( see example ) . <nl> + <nl> + ` Select ` example : <nl> + ` ` ` sql <nl> + SELECT SearchPhrase , count ( ) AS c FROM test . hits GROUP BY SearchPhrase ORDER BY c DESC LIMIT 5 <nl> + FORMAT Template <nl> + SETTINGS format_schema = ' < ! DOCTYPE HTML > <nl> + < html > < head > < title > Search phrases < / title > < / head > <nl> + < body > <nl> + < table border = " 1 " > < caption > Search phrases < / caption > <nl> + < tr > < th > Search phrase < / th > < th > Count < / th > < / tr > <nl> + $ { data } <nl> + < / table > <nl> + < table border = " 1 " > < caption > Max < / caption > <nl> + $ { max } <nl> + < / table > <nl> + < b > Processed $ { rows_read : XML } rows in $ { time : XML } sec < / b > <nl> + < / body > <nl> + < / html > ' , <nl> + format_schema_rows = ' < tr > < td > $ { SearchPhrase : XML } < / td > < td > $ { с : XML } < / td > < / tr > ' , <nl> + format_schema_rows_between_delimiter = ' \ n ' <nl> + ` ` ` <nl> + ` ` ` html <nl> + < ! DOCTYPE HTML > <nl> + < html > < head > < title > Search phrases < / title > < / head > <nl> + < body > <nl> + < table border = " 1 " > < caption > Search phrases < / caption > <nl> + < tr > < th > Search phrase < / th > < th > Count < / th > < / tr > <nl> + < tr > < td > < / td > < td > 8267016 < / td > < / tr > <nl> + < tr > < td > bathroom interior design < / td > < td > 2166 < / td > < / tr > <nl> + < tr > < td > yandex < / td > < td > 1655 < / td > < / tr > <nl> + < tr > < td > spring 2014 fashion < / td > < td > 1549 < / td > < / tr > <nl> + < tr > < td > freeform photos < / td > < td > 1480 < / td > < / tr > <nl> + < / table > <nl> + < table border = " 1 " > < caption > Max < / caption > <nl> + < tr > < td > < / td > < td > 8873898 < / td > < / tr > <nl> + < / table > <nl> + < b > Processed 3095973 rows in 0 . 1569913 sec < / b > <nl> + < / body > <nl> + < / html > <nl> + ` ` ` <nl> + <nl> + ` Insert ` example : <nl> + ` ` ` <nl> + Some header <nl> + Page views : 5 , User id : 4324182021466249494 , Useless field : hello , Duration : 146 , Sign : - 1 <nl> + Page views : 6 , User id : 4324182021466249494 , Useless field : world , Duration : 185 , Sign : 1 <nl> + Total rows : 2 <nl> + ` ` ` <nl> + ` ` ` sql <nl> + INSERT INTO UserActivity FORMAT Template SETTINGS <nl> + format_schema = ' Some header \ n $ { data } \ nTotal rows : $ { : CSV } \ n ' , <nl> + format_schema_rows = ' Page views : $ { PageViews : CSV } , User id : $ { UserID : CSV } , Useless field : $ { : CSV } , Duration : $ { Duration : CSV } , Sign : $ { Sign : CSV } ' <nl> + ` ` ` <nl> + ` PageViews ` , ` UserID ` , ` Duration ` and ` Sign ` inside placeholders are names of columns in the table . Values after ` Useless field ` in rows and after ` \ nTotal rows : ` in suffix will be ignored . <nl> + All delimiters in the input data must be strictly equal to delimiters in specified format strings . <nl> + <nl> + # # TemplateIgnoreSpaces { # templateignorespaces } <nl> + <nl> + This format is suitable only for input . <nl> + Similar to ` Template ` , but skips whitespace characters between delimiters and values in the input stream . However , if format strings contain whitespace characters , these characters will be expected in the input stream . Also allows to specify empty placeholders ( ` $ { } ` or ` $ { : None } ` ) to split some delimiter into separate parts to ignore spaces between them . Such placeholders are used only for skipping whitespace characters . <nl> + It ' s possible to read ` JSON ` using this format , if values of columns have the same order in all rows . For example , the following request can be used for inserting data from output example of format [ JSON ] ( # json ) : <nl> + ` ` ` sql <nl> + INSERT INTO table_name FORMAT TemplateIgnoreSpaces SETTINGS <nl> + format_schema = ' { $ { } " meta " $ { } : $ { : JSON } , $ { } " data " $ { } : $ { } [ $ { data } ] $ { } , $ { } " totals " $ { } : $ { : JSON } , $ { } " extremes " $ { } : $ { : JSON } , $ { } " rows " $ { } : $ { : JSON } , $ { } " rows_before_limit_at_least " $ { } : $ { : JSON } $ { } } ' , <nl> + format_schema_rows = ' { $ { } " SearchPhrase " $ { } : $ { } $ { phrase : JSON } $ { } , $ { } " c " $ { } : $ { } $ { cnt : JSON } $ { } } ' , <nl> + format_schema_rows_between_delimiter = ' , ' <nl> + ` ` ` <nl> + <nl> # # TSKV { # tskv } <nl> <nl> Similar to TabSeparated , but outputs a value in name = value format . Names are escaped the same way as in TabSeparated format , and the = symbol is also escaped . <nl> mmm a / docs / en / operations / settings / settings . md <nl> ppp b / docs / en / operations / settings / settings . md <nl> Works with tables in the MergeTree family . <nl> <nl> If ` force_primary_key = 1 ` , ClickHouse checks to see if the query has a primary key condition that can be used for restricting data ranges . If there is no suitable condition , it throws an exception . However , it does not check whether the condition actually reduces the amount of data to read . For more information about data ranges in MergeTree tables , see " [ MergeTree ] ( . . / . . / operations / table_engines / mergetree . md ) " . <nl> <nl> + # # format_schema <nl> + <nl> + This parameter is useful when you are using formats that require a schema definition , such as [ Cap ' n Proto ] ( https : / / capnproto . org / ) , [ Protobuf ] ( https : / / developers . google . com / protocol - buffers / ) or [ Template ] ( https : / / clickhouse . yandex / docs / en / interfaces / formats / # template ) . The value depends on the format . <nl> <nl> # # fsync_metadata <nl> <nl> If a query from the same user with the same ' query_id ' already exists at this ti <nl> <nl> Yandex . Metrica uses this parameter set to 1 for implementing suggestions for segmentation conditions . After entering the next character , if the old query hasn ' t finished yet , it should be canceled . <nl> <nl> - # # schema <nl> - <nl> - This parameter is useful when you are using formats that require a schema definition , such as [ Cap ' n Proto ] ( https : / / capnproto . org / ) . The value depends on the format . <nl> - <nl> <nl> # # stream_flush_interval_ms <nl> <nl> mmm a / docs / en / operations / table_engines / collapsingmergetree . md <nl> ppp b / docs / en / operations / table_engines / collapsingmergetree . md <nl> SELECT * FROM UAct FINAL <nl> <nl> This way of selecting the data is very inefficient . Don ' t use it for big tables . <nl> <nl> + # # Example of another approach <nl> + <nl> + Example data : <nl> + <nl> + ` ` ` <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 5 │ 146 │ 1 │ <nl> + │ 4324182021466249494 │ - 5 │ - 146 │ - 1 │ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + ` ` ` <nl> + <nl> + The idea is that merges take into account only key fields . And in the " Cancel " line we can specify negative values that equalize the previous version of the row when summing without using the Sign column . For this approach , it is necessary to change the data type ` PageViews ` , ` Duration ` to store negative values of UInt8 - > Int16 . <nl> + <nl> + ` ` ` sql <nl> + CREATE TABLE UAct <nl> + ( <nl> + UserID UInt64 , <nl> + PageViews Int16 , <nl> + Duration Int16 , <nl> + Sign Int8 <nl> + ) <nl> + ENGINE = CollapsingMergeTree ( Sign ) <nl> + ORDER BY UserID <nl> + ` ` ` <nl> + <nl> + Let ' s test the approach : <nl> + ` ` ` sql <nl> + insert into UAct values ( 4324182021466249494 , 5 , 146 , 1 ) ; <nl> + insert into UAct values ( 4324182021466249494 , - 5 , - 146 , - 1 ) ; <nl> + insert into UAct values ( 4324182021466249494 , 6 , 185 , 1 ) ; <nl> + <nl> + select * from UAct final ; / / avoid using final in production ( just for a test or small tables ) <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + SELECT <nl> + UserID , <nl> + sum ( PageViews ) AS PageViews , <nl> + sum ( Duration ) AS Duration <nl> + FROM UAct <nl> + GROUP BY UserID <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + select count ( ) FROM UAct <nl> + ┌ ─ count ( ) ─ ┐ <nl> + │ 3 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + optimize table UAct final ; <nl> + <nl> + select * FROM UAct <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + ` ` ` <nl> + <nl> + <nl> + <nl> [ Original article ] ( https : / / clickhouse . yandex / docs / en / operations / table_engines / collapsingmergetree / ) < ! - - hide - - > <nl> mmm a / docs / ru / interfaces / formats . md <nl> ppp b / docs / ru / interfaces / formats . md <nl> ClickHouse может принимать ( ` INSERT ` ) и отдавать ( ` SELECT <nl> | [ TabSeparatedRaw ] ( # tabseparatedraw ) | ✗ | ✔ | <nl> | [ TabSeparatedWithNames ] ( # tabseparatedwithnames ) | ✔ | ✔ | <nl> | [ TabSeparatedWithNamesAndTypes ] ( # tabseparatedwithnamesandtypes ) | ✔ | ✔ | <nl> + | [ Template ] ( # template ) | ✔ | ✔ | <nl> + | [ TemplateIgnoreSpaces ] ( # templateignorespaces ) | ✔ | ✗ | <nl> | [ CSV ] ( # csv ) | ✔ | ✔ | <nl> | [ CSVWithNames ] ( # csvwithnames ) | ✔ | ✔ | <nl> | [ Values ] ( # data - format - values ) | ✔ | ✔ | <nl> world <nl> <nl> Этот формат также доступен под именем ` TSVWithNamesAndTypes ` . <nl> <nl> + # # Template { # template } <nl> + <nl> + Этот формат позволяет указать произвольную форматную строку , в которую подставляются значения , сериализованные выбранным способом . <nl> + <nl> + Для этого используются настройки ` format_schema ` , ` format_schema_rows ` , ` format_schema_rows_between_delimiter ` и настройки экранирования других форматов ( например , ` output_format_json_quote_64bit_integers ` при экранировании как в ` JSON ` , см . далее ) <nl> + <nl> + Форматная строка ` format_schema_rows ` задаёт формат для строк таблицы и должна иметь вид : <nl> + <nl> + ` delimiter_1 $ { column_1 : serializeAs_1 } delimiter_2 $ { column_2 : serializeAs_2 } . . . delimiter_N ` , <nl> + <nl> + где ` delimiter_i ` - разделители между значениями ( символ ` $ ` в разделителе экранируется как ` $ $ ` ) , <nl> + ` column_i ` - имена столбцов , значения которых должны быть выведены или считаны ( если имя не указано - столбец пропускается ) , <nl> + ` serializeAs_i ` - тип экранирования для значений соответствующего столбца . Поддерживаются следующие типы экранирования : <nl> + <nl> + - ` CSV ` , ` JSON ` , ` XML ` ( как в одноимённых форматах ) <nl> + - ` Escaped ` ( как в ` TSV ` ) <nl> + - ` Quoted ` ( как в ` Values ` ) <nl> + - ` Raw ` ( без экранирования , как в ` TSVRaw ` ) <nl> + - ` None ` ( тип экранирования отсутствует , см . далее ) <nl> + <nl> + Если для столбца не указан тип экранирования , используется ` None ` . ` XML ` и ` Raw ` поддерживаются только для вывода . <nl> + <nl> + Так , в форматной строке <nl> + <nl> + ` Search phrase : $ { SearchPhrase : Quoted } , count : $ { c : Escaped } , ad price : $ $ $ { price : JSON } ; ` <nl> + <nl> + между разделителями ` Search phrase : ` , ` , count : ` , ` , ad price : $ ` и ` ; ` при выводе будут подставлены ( при вводе - будут ожидаться ) значения столбцов ` SearchPhrase ` , ` c ` и ` price ` , сериализованные как ` Quoted ` , ` Escaped ` и ` JSON ` соответственно , например : <nl> + <nl> + ` Search phrase : ' bathroom interior design ' , count : 2166 , ad price : $ 3 ; ` <nl> + <nl> + Настройка ` format_schema_rows_between_delimiter ` задаёт разделитель между строками , который выводится ( или ожмдается при вводе ) после каждой строки , кроме последней . По умолчанию ` \ n ` . <nl> + <nl> + Форматная строка ` format_schema ` имеет аналогичный ` format_schema_rows ` синтаксис и позволяет указать префикс , суффикс и способ вывода дополнительной информации . Вместо имён столбцов в ней указываются следующие имена подстановок : <nl> + <nl> + - ` data ` - строки с данными в формате ` format_schema_rows ` , разделённые ` format_schema_rows_between_delimiter ` . Эта подстановка должна быть первой подстановкой в форматной строке . <nl> + - ` totals ` - строка с тотальными значениями в формате ` format_schema_rows ` ( при использовании WITH TOTALS ) <nl> + - ` min ` - строка с минимальными значениями в формате ` format_schema_rows ` ( при настройке extremes , выставленной в 1 ) <nl> + - ` max ` - строка с максимальными значениями в формате ` format_schema_rows ` ( при настройке extremes , выставленной в 1 ) <nl> + - ` rows ` - общее количество выведенных стрчек <nl> + - ` rows_before_limit ` - не менее скольких строчек получилось бы , если бы не было LIMIT - а . Выводится только если запрос содержит LIMIT . В случае , если запрос содержит GROUP BY , ` rows_before_limit ` - точное число строк , которое получилось бы , если бы не было LIMIT - а . <nl> + - ` time ` - время выполнения запроса в секундах <nl> + - ` rows_read ` - сколько строк было прочитано при выполнении запроса <nl> + - ` bytes_read ` - сколько байт ( несжатых ) было прочитано при выполнении запроса <nl> + <nl> + У подстановок ` data ` , ` totals ` , ` min ` и ` max ` не должны быть указаны типы экранирования ( или должен быть указан ` None ` ) . Остальные подстановки - это отдельные значения , для них может быть указан любой тип экранирования . <nl> + Если строка ` format_schema ` пустая , то по - умолчанию используется ` $ { data } ` . <nl> + Из всех перечисленных подстановок форматная строка ` format_schema ` для ввода может содержать только ` data ` . <nl> + Также при вводе формат поддерживает пропуск значений столбцов и пропуск значений в префиксе и суффиксе ( см . пример ) . <nl> + <nl> + Пример вывода : <nl> + ` ` ` sql <nl> + SELECT SearchPhrase , count ( ) AS c FROM test . hits GROUP BY SearchPhrase ORDER BY c DESC LIMIT 5 <nl> + FORMAT Template <nl> + SETTINGS format_schema = ' < ! DOCTYPE HTML > <nl> + < html > < head > < title > Search phrases < / title > < / head > <nl> + < body > <nl> + < table border = " 1 " > < caption > Search phrases < / caption > <nl> + < tr > < th > Search phrase < / th > < th > Count < / th > < / tr > <nl> + $ { data } <nl> + < / table > <nl> + < table border = " 1 " > < caption > Max < / caption > <nl> + $ { max } <nl> + < / table > <nl> + < b > Processed $ { rows_read : XML } rows in $ { time : XML } sec < / b > <nl> + < / body > <nl> + < / html > ' , <nl> + format_schema_rows = ' < tr > < td > $ { SearchPhrase : XML } < / td > < td > $ { с : XML } < / td > < / tr > ' , <nl> + format_schema_rows_between_delimiter = ' \ n ' <nl> + ` ` ` <nl> + ` ` ` html <nl> + < ! DOCTYPE HTML > <nl> + < html > < head > < title > Search phrases < / title > < / head > <nl> + < body > <nl> + < table border = " 1 " > < caption > Search phrases < / caption > <nl> + < tr > < th > Search phrase < / th > < th > Count < / th > < / tr > <nl> + < tr > < td > < / td > < td > 8267016 < / td > < / tr > <nl> + < tr > < td > bathroom interior design < / td > < td > 2166 < / td > < / tr > <nl> + < tr > < td > yandex < / td > < td > 1655 < / td > < / tr > <nl> + < tr > < td > spring 2014 fashion < / td > < td > 1549 < / td > < / tr > <nl> + < tr > < td > freeform photos < / td > < td > 1480 < / td > < / tr > <nl> + < / table > <nl> + < table border = " 1 " > < caption > Max < / caption > <nl> + < tr > < td > < / td > < td > 8873898 < / td > < / tr > <nl> + < / table > <nl> + < b > Processed 3095973 rows in 0 . 1569913 sec < / b > <nl> + < / body > <nl> + < / html > <nl> + ` ` ` <nl> + <nl> + Пример ввода : <nl> + ` ` ` <nl> + Some header <nl> + Page views : 5 , User id : 4324182021466249494 , Useless field : hello , Duration : 146 , Sign : - 1 <nl> + Page views : 6 , User id : 4324182021466249494 , Useless field : world , Duration : 185 , Sign : 1 <nl> + Total rows : 2 <nl> + ` ` ` <nl> + ` ` ` sql <nl> + INSERT INTO UserActivity FORMAT Template SETTINGS <nl> + format_schema = ' Some header \ n $ { data } \ nTotal rows : $ { : CSV } \ n ' , <nl> + format_schema_rows = ' Page views : $ { PageViews : CSV } , User id : $ { UserID : CSV } , Useless field : $ { : CSV } , Duration : $ { Duration : CSV } , Sign : $ { Sign : CSV } ' <nl> + ` ` ` <nl> + ` PageViews ` , ` UserID ` , ` Duration ` и ` Sign ` внутри подстановок - имена столбцов в таблице , в которую вставляются данные . Значения после ` Useless field ` в строках и значение после ` \ nTotal rows : ` в суффиксе будут проигнорированы . <nl> + Все разделители во входных данных должны строго соответствовать разделителям в форматных строках . <nl> + <nl> + # # TemplateIgnoreSpaces { # templateignorespaces } <nl> + <nl> + Подходит только для ввода . Отличается от формата ` Template ` тем , что пропускает пробельные символы между разделителями и значениями во входном потоке . Также в этом формате можно указать пустые подстановки с типом экранирования ` None ` ( ` $ { } ` или ` $ { : None } ` ) , чтобы разбить разделители на несколько частей , пробелы между которыми должны игнорироваться . Такие подстановки используются только для пропуска пробелов . С помощью этого формата можно считывать ` JSON ` , если значения столбцов в нём всегда идут в одном порядке в каждой строке . Например , для вставки данных из примера вывода формата [ JSON ] ( # json ) в таблицу со столбцами ` phrase ` и ` cnt ` можно использовать следующий запрос : <nl> + ` ` ` sql <nl> + INSERT INTO table_name FORMAT TemplateIgnoreSpaces SETTINGS <nl> + format_schema = ' { $ { } " meta " $ { } : $ { : JSON } , $ { } " data " $ { } : $ { } [ $ { data } ] $ { } , $ { } " totals " $ { } : $ { : JSON } , $ { } " extremes " $ { } : $ { : JSON } , $ { } " rows " $ { } : $ { : JSON } , $ { } " rows_before_limit_at_least " $ { } : $ { : JSON } $ { } } ' , <nl> + format_schema_rows = ' { $ { } " SearchPhrase " $ { } : $ { } $ { phrase : JSON } $ { } , $ { } " c " $ { } : $ { } $ { cnt : JSON } $ { } } ' , <nl> + format_schema_rows_between_delimiter = ' , ' <nl> + ` ` ` <nl> + <nl> # # TSKV { # tskv } <nl> <nl> Похож на TabSeparated , но выводит значения в формате name = value . Имена экранируются так же , как строки в формате TabSeparated и , дополнительно , экранируется также символ = . <nl> mmm a / docs / ru / operations / settings / settings . md <nl> ppp b / docs / ru / operations / settings / settings . md <nl> ClickHouse применяет настройку в тех случаях , ко <nl> <nl> При ` force_primary_key = 1 ` ClickHouse проверяет , есть ли в запросе условие на первичный ключ , которое может использоваться для отсечения диапазонов данных . Если подходящего условия нет - кидается исключение . При этом не проверяется , действительно ли условие уменьшает объём данных для чтения . Подробнее про диапазоны данных в таблицах MergeTree читайте в разделе " [ MergeTree ] ( . . / . . / operations / table_engines / mergetree . md ) " . <nl> <nl> + # # format_schema <nl> + <nl> + Параметр применяется в том случае , когда используются форматы , требующие определения схемы , например [ Cap ' n Proto ] ( https : / / capnproto . org / ) , [ Protobuf ] ( https : / / developers . google . com / protocol - buffers / ) или [ Template ] ( . . / . . / interfaces / formats . md # template ) . Значение параметра зависит от формата . <nl> + <nl> # # fsync_metadata <nl> <nl> Включает или отключает [ fsync ] ( http : / / pubs . opengroup . org / onlinepubs / 9699919799 / functions / fsync . html ) при записи ` . sql ` файлов . По умолчанию включено . <nl> ClickHouse использует этот параметр при чтении д <nl> <nl> Эта настройка , выставленная в 1 , используется в Яндекс . Метрике для реализации suggest - а значений для условий сегментации . После ввода очередного символа , если старый запрос ещё не выполнился , его следует отменить . <nl> <nl> - # # schema <nl> - <nl> - Параметр применяется в том случае , когда используются форматы , требующие определения схемы , например [ Cap ' n Proto ] ( https : / / capnproto . org / ) . Значение параметра зависит от формата . <nl> - <nl> # # stream_flush_interval_ms <nl> <nl> Работает для таблиц со стриммингом в случае тайм - аута , или когда поток генерирует [ max_insert_block_size ] ( # settings - max_insert_block_size ) строк . <nl> mmm a / docs / ru / operations / table_engines / collapsingmergetree . md <nl> ppp b / docs / ru / operations / table_engines / collapsingmergetree . md <nl> SELECT * FROM UAct FINAL <nl> <nl> Такой способ выбора данных очень неэффективен . Не используйте его для больших таблиц . <nl> <nl> + # # Пример другого подхода <nl> + <nl> + Исходные данные : <nl> + <nl> + ` ` ` <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 5 │ 146 │ 1 │ <nl> + │ 4324182021466249494 │ - 5 │ - 146 │ - 1 │ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + ` ` ` <nl> + Идея состоит в том , что слияния при сворачивании учитывают только ключевые поля , поэтому в отменяющей строке можно указать отрицательные значения , которые нивелируют предыдущую версию записи при суммировании без учета поля Sign . <nl> + Для этого подхода необходимо изменить тип данных ` PageViews ` , ` Duration ` для хранения отрицательных значений UInt8 - > Int16 . <nl> + <nl> + ` ` ` sql <nl> + CREATE TABLE UAct <nl> + ( <nl> + UserID UInt64 , <nl> + PageViews Int16 , <nl> + Duration Int16 , <nl> + Sign Int8 <nl> + ) <nl> + ENGINE = CollapsingMergeTree ( Sign ) <nl> + ORDER BY UserID <nl> + ` ` ` <nl> + <nl> + Тестируем подход : <nl> + ` ` ` sql <nl> + insert into UAct values ( 4324182021466249494 , 5 , 146 , 1 ) ; <nl> + insert into UAct values ( 4324182021466249494 , - 5 , - 146 , - 1 ) ; <nl> + insert into UAct values ( 4324182021466249494 , 6 , 185 , 1 ) ; <nl> + <nl> + select * from UAct final ; / / старайтесь не использовать final ( он подходит только для тестов и маленьких таблиц ) <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + SELECT <nl> + UserID , <nl> + sum ( PageViews ) AS PageViews , <nl> + sum ( Duration ) AS Duration <nl> + FROM UAct <nl> + GROUP BY UserID <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + select count ( ) FROM UAct <nl> + ┌ ─ count ( ) ─ ┐ <nl> + │ 3 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ <nl> + <nl> + optimize table UAct final ; <nl> + <nl> + select * FROM UAct <nl> + ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ UserID ─ ┬ ─ PageViews ─ ┬ ─ Duration ─ ┬ ─ Sign ─ ┐ <nl> + │ 4324182021466249494 │ 6 │ 185 │ 1 │ <nl> + └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ┘ <nl> + ` ` ` <nl> + <nl> [ Оригинальная статья ] ( https : / / clickhouse . yandex / docs / ru / operations / table_engines / collapsingmergetree / ) < ! - - hide - - > <nl> <nl> | Merge remote - tracking branch ' upstream / master ' into read - in - order - 2 | ClickHouse/ClickHouse | 973b533377bdea8daef4b491c86321b924a4c02f | 2019-09-02T21:59:51Z |
mmm a / modules / common / BUILD <nl> ppp b / modules / common / BUILD <nl> cc_library ( <nl> deps = [ <nl> " : log " , <nl> " : macro " , <nl> - " @ ros / / : ros_common " , <nl> + " / / framework : cybertron " , <nl> ] , <nl> ) <nl> <nl> cc_library ( <nl> " log . h " , <nl> ] , <nl> deps = [ <nl> - " @ glog " , <nl> + " / / framework : cybertron_common " , <nl> ] , <nl> ) <nl> <nl> - cc_library ( <nl> - name = " apollo_app " , <nl> - srcs = [ <nl> - " apollo_app . cc " , <nl> - ] , <nl> - hdrs = [ <nl> - " apollo_app . h " , <nl> - ] , <nl> - deps = [ <nl> - " : log " , <nl> - " / / modules / common / status " , <nl> - " / / modules / common / util : string_util " , <nl> - " @ ros / / : ros_common " , <nl> - ] , <nl> - ) <nl> + # cc_library ( <nl> + # name = " apollo_app " , <nl> + # srcs = [ <nl> + # " apollo_app . cc " , <nl> + # ] , <nl> + # hdrs = [ <nl> + # " apollo_app . h " , <nl> + # ] , <nl> + # deps = [ <nl> + # " : log " , <nl> + # " / / modules / common / status " , <nl> + # " / / modules / common / util : string_util " , <nl> + # " / / framework : cybertron " , <nl> + # ] , <nl> + # ) <nl> <nl> cpplint ( ) <nl> mmm a / modules / common / adapters / BUILD <nl> ppp b / modules / common / adapters / BUILD <nl> cc_library ( <nl> " / / modules / common " , <nl> " / / modules / common / adapters / proto : adapter_config_proto " , <nl> " / / modules / common / monitor_log / proto : monitor_log_proto " , <nl> - " / / modules / common / transform_listener " , <nl> + # " / / modules / common / transform_listener " , <nl> " / / modules / common / util " , <nl> " @ glog " , <nl> " @ ros / / : ros_common " , <nl> mmm a / modules / common / filters / BUILD <nl> ppp b / modules / common / filters / BUILD <nl> cc_test ( <nl> " : digital_filter_coefficients " , <nl> " / / modules / common " , <nl> " @ gtest / / : main " , <nl> - " @ ros / / : ros_common " , <nl> + " / / framework : cybertron " , <nl> ] , <nl> ) <nl> <nl> mmm a / modules / common / log . h <nl> ppp b / modules / common / log . h <nl> <nl> # ifndef MODULES_COMMON_LOG_H_ <nl> # define MODULES_COMMON_LOG_H_ <nl> <nl> - # include " glog / logging . h " <nl> - # include " glog / raw_logging . h " <nl> - <nl> - # define ADEBUG VLOG ( 4 ) < < " [ DEBUG ] " <nl> - # define AINFO LOG ( INFO ) <nl> - # define AWARN LOG ( WARNING ) <nl> - # define AERROR LOG ( ERROR ) <nl> - # define AFATAL LOG ( FATAL ) <nl> - <nl> - / / LOG_IF <nl> - # define AINFO_IF ( cond ) LOG_IF ( INFO , cond ) <nl> - # define AERROR_IF ( cond ) LOG_IF ( ERROR , cond ) <nl> - # define ACHECK ( cond ) CHECK ( cond ) <nl> - <nl> - / / LOG_EVERY_N <nl> - # define AINFO_EVERY ( freq ) LOG_EVERY_N ( INFO , freq ) <nl> - # define AWARN_EVERY ( freq ) LOG_EVERY_N ( WARNING , freq ) <nl> - # define AERROR_EVERY ( freq ) LOG_EVERY_N ( ERROR , freq ) <nl> - <nl> - # define RETURN_IF_NULL ( ptr ) \ <nl> - if ( ptr = = nullptr ) { \ <nl> - AWARN < < # ptr < < " is nullptr . " ; \ <nl> - return ; \ <nl> - } <nl> - <nl> - # define RETURN_VAL_IF_NULL ( ptr , val ) \ <nl> - if ( ptr = = nullptr ) { \ <nl> - AWARN < < # ptr < < " is nullptr . " ; \ <nl> - return val ; \ <nl> - } <nl> - <nl> - # define RETURN_IF ( condition ) \ <nl> - if ( condition ) { \ <nl> - AWARN < < # condition < < " is not met . " ; \ <nl> - return ; \ <nl> - } <nl> - <nl> - # define RETURN_VAL_IF ( condition , val ) \ <nl> - if ( condition ) { \ <nl> - AWARN < < # condition < < " is not met . " ; \ <nl> - return val ; \ <nl> - } <nl> + # include " cybertron / common / log . h " <nl> <nl> # endif / / MODULES_COMMON_LOG_H_ <nl> mmm a / modules / common / macro . h <nl> ppp b / modules / common / macro . h <nl> <nl> # include < iomanip > <nl> # include < iostream > <nl> <nl> + # ifndef DISALLOW_COPY_AND_ASSIGN <nl> # define DISALLOW_COPY_AND_ASSIGN ( classname ) \ <nl> private : \ <nl> classname ( const classname & ) ; \ <nl> classname & operator = ( const classname & ) ; <nl> + # endif <nl> <nl> # define DISALLOW_IMPLICIT_CONSTRUCTORS ( classname ) \ <nl> private : \ <nl> classname ( ) ; \ <nl> DISALLOW_COPY_AND_ASSIGN ( classname ) ; <nl> <nl> + # ifndef DECLARE_SINGLETON <nl> # define DECLARE_SINGLETON ( classname ) \ <nl> public : \ <nl> - static classname * instance ( ) { \ <nl> - static classname instance ; \ <nl> - return & instance ; \ <nl> + static classname * Instance ( ) { \ <nl> + static classname Instance ; \ <nl> + return & Instance ; \ <nl> } \ <nl> DISALLOW_IMPLICIT_CONSTRUCTORS ( classname ) \ <nl> private : <nl> + # endif <nl> # endif / / MODULES_COMMON_MACRO_H_ <nl> mmm a / modules / common / time / BUILD <nl> ppp b / modules / common / time / BUILD <nl> cc_library ( <nl> " / / modules / common : log " , <nl> " / / modules / common : macro " , <nl> " / / modules / common / configs : config_gflags " , <nl> - " @ ros / / : ros_common " , <nl> + " / / framework : cybertron " , <nl> ] , <nl> ) <nl> <nl> mmm a / modules / common / time / time . h <nl> ppp b / modules / common / time / time . h <nl> <nl> # include " modules / common / configs / config_gflags . h " <nl> # include " modules / common / log . h " <nl> # include " modules / common / macro . h " <nl> - # include " ros / include / ros / ros . h " <nl> + # include " cybertron / time / time . h " <nl> <nl> / * * <nl> * @ namespace apollo : : common : : time <nl> class Clock { <nl> enum ClockMode { <nl> SYSTEM = 0 , <nl> MOCK = 1 , <nl> - ROS = 2 , <nl> + CYBERTRON = 2 , <nl> } ; <nl> <nl> / * * <nl> class Clock { <nl> case ClockMode : : SYSTEM : <nl> return SystemNow ( ) ; <nl> case ClockMode : : MOCK : <nl> - return instance ( ) - > mock_now_ ; <nl> - case ClockMode : : ROS : <nl> - return From ( ros : : Time : : now ( ) . toSec ( ) ) ; <nl> + return Instance ( ) - > mock_now_ ; <nl> + case ClockMode : : CYBERTRON : <nl> + return From ( cybertron : : Time : : Now ( ) . ToSecond ( ) ) ; <nl> default : <nl> AFATAL < < " Unsupported clock mode : " < < mode ( ) ; <nl> } <nl> - return From ( ros : : Time : : now ( ) . toSec ( ) ) ; <nl> + return From ( cybertron : : Time : : Now ( ) . ToSecond ( ) ) ; <nl> } <nl> <nl> / * * <nl> class Clock { <nl> * @ brief Set the behavior of the \ class Clock . <nl> * @ param The new clock mode to be set . <nl> * / <nl> - static void SetMode ( ClockMode mode ) { instance ( ) - > mode_ = mode ; } <nl> + static void SetMode ( ClockMode mode ) { Instance ( ) - > mode_ = mode ; } <nl> <nl> / * * <nl> * @ brief Gets the current clock mode . <nl> * @ return The current clock mode . <nl> * / <nl> - static ClockMode mode ( ) { return instance ( ) - > mode_ ; } <nl> + static ClockMode mode ( ) { return Instance ( ) - > mode_ ; } <nl> <nl> / * * <nl> * @ brief This is for mock clock mode only . It will set the timestamp <nl> * for the mock clock . <nl> * / <nl> static void SetNow ( const Duration & duration ) { <nl> - Clock * clock = instance ( ) ; <nl> + auto clock = Instance ( ) ; <nl> if ( clock - > mode_ ! = ClockMode : : MOCK ) { <nl> AFATAL < < " Cannot set now when clock mode is not MOCK ! " ; <nl> } <nl> class Clock { <nl> * for the mock clock with UNIX timestamp in seconds . <nl> * / <nl> static void SetNowInSeconds ( double seconds ) { <nl> - Clock * clock = instance ( ) ; <nl> + auto clock = Instance ( ) ; <nl> if ( clock - > mode_ ! = ClockMode : : MOCK ) { <nl> AFATAL < < " Cannot set now when clock mode is not MOCK ! " ; <nl> } <nl> class Clock { <nl> * @ brief constructs the \ class Clock instance <nl> * @ param mode the desired clock mode <nl> * / <nl> - explicit Clock ( ClockMode mode ) : mode_ ( mode ) , mock_now_ ( Timestamp ( ) ) { <nl> - ros : : Time : : init ( ) ; <nl> - } <nl> + explicit Clock ( ClockMode mode ) : mode_ ( mode ) , mock_now_ ( Timestamp ( ) ) { } <nl> <nl> / * * <nl> * @ brief Returns the current timestamp based on the system clock . <nl> class Clock { <nl> } ; <nl> <nl> inline Clock : : Clock ( ) <nl> - : Clock ( FLAGS_use_ros_time ? ClockMode : : ROS : ClockMode : : SYSTEM ) { } <nl> + : Clock ( FLAGS_use_ros_time ? ClockMode : : CYBERTRON : ClockMode : : SYSTEM ) { } <nl> <nl> / / Measure run time of a code block , mostly for debugging purpose . <nl> / / Example usage : <nl> mmm a / modules / common / transform_listener / BUILD <nl> ppp b / modules / common / transform_listener / BUILD <nl> cc_library ( <nl> deps = [ <nl> " / / modules / common : log " , <nl> " / / modules / common / time " , <nl> - " @ ros / / : ros_common " , <nl> + " / / framework : cybertron " , <nl> ] , <nl> ) <nl> <nl> mmm a / modules / common / util / BUILD <nl> ppp b / modules / common / util / BUILD <nl> cc_library ( <nl> ] , <nl> ) <nl> <nl> + cc_library ( <nl> + name = " message_util " , <nl> + hdrs = [ <nl> + " message_util . h " , <nl> + ] , <nl> + deps = [ <nl> + " @ com_google_protobuf / / : protobuf " , <nl> + ] , <nl> + ) <nl> + <nl> cc_test ( <nl> name = " string_util_test " , <nl> size = " small " , <nl> new file mode 100644 <nl> index 00000000000 . . 4e6192ef2a2 <nl> mmm / dev / null <nl> ppp b / modules / common / util / message_util . h <nl> <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + * Copyright 2017 The Apollo Authors . All Rights Reserved . <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an " AS IS " BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + / * * <nl> + * @ file <nl> + * @ brief Some string util functions . <nl> + * / <nl> + <nl> + # ifndef MODULES_COMMON_UTIL_MESSAGE_UTIL_H_ <nl> + # define MODULES_COMMON_UTIL_MESSAGE_UTIL_H_ <nl> + <nl> + # include < string > <nl> + <nl> + # include " google / protobuf / message . h " <nl> + <nl> + / * * <nl> + * @ namespace apollo : : common : : util <nl> + * @ brief apollo : : common : : util <nl> + * / <nl> + namespace apollo { <nl> + namespace common { <nl> + namespace util { <nl> + <nl> + / / Expose some useful utils from protobuf . <nl> + using : : google : : protobuf : : Message ; <nl> + <nl> + template < typename T , typename std : : enable_if < <nl> + std : : is_base_of < Message , T > : : value , int > : : type = 0 > <nl> + static void FillHeader ( const std : : string & module_name , T * msg ) { <nl> + static std : : atomic < uint64_t > sequence_num = { 0 } ; <nl> + auto * header = msg - > mutable_header ( ) ; <nl> + double timestamp = apollo : : common : : time : : Clock : : NowInSeconds ( ) ; <nl> + header - > set_module_name ( module_name ) ; <nl> + header - > set_timestamp_sec ( timestamp ) ; <nl> + header - > set_sequence_num ( sequence_num . fetch_add ( 1 ) ) ; <nl> + } <nl> + <nl> + } / / namespace util <nl> + } / / namespace common <nl> + } / / namespace apollo <nl> + <nl> + # endif / / MODULES_COMMON_UTIL_MESSAGE_UTIL_H_ <nl> mmm a / modules / drivers / radar / conti_radar / BUILD <nl> ppp b / modules / drivers / radar / conti_radar / BUILD <nl> cc_library ( <nl> " conti_radar_message_manager . h " , <nl> ] , <nl> deps = [ <nl> - " / / modules / common / adapters : adapter_manager " , <nl> - " / / modules / drivers / canbus : sensor_gflags " , <nl> " / / modules / drivers / canbus / can_client : can_client_factory " , <nl> " / / modules / drivers / canbus / can_comm : can_sender " , <nl> " / / modules / drivers / canbus / can_comm : message_manager_base " , <nl> " / / modules / drivers / radar / conti_radar / protocol : drivers_conti_radar_protocol " , <nl> + " / / modules / common / util : message_util " <nl> ] , <nl> ) <nl> <nl> - # cc_test ( <nl> - # name = " conti_radar_message_manager_test " , <nl> - # size = " small " , <nl> - # srcs = [ <nl> - # " conti_radar_message_manager_test . cc " , <nl> - # ] , <nl> - # deps = [ <nl> - # " conti_radar_message_manager " , <nl> - # " @ gtest / / : main " , <nl> - # ] , <nl> - # ) <nl> - <nl> cc_library ( <nl> name = " conti_radar_canbus_lib " , <nl> srcs = [ <nl> - " conti_radar_canbus . cc " , <nl> + " conti_radar_canbus_component . cc " , <nl> ] , <nl> hdrs = [ <nl> - " conti_radar_canbus . h " , <nl> + " conti_radar_canbus_component . h " , <nl> ] , <nl> deps = [ <nl> " : conti_radar_message_manager " , <nl> " / / modules / common " , <nl> - " / / modules / common : apollo_app " , <nl> - " / / modules / common / adapters : adapter_manager " , <nl> - " / / modules / common / monitor_log " , <nl> - " / / modules / drivers / canbus : sensor_gflags " , <nl> + # " / / modules / common / monitor_log " , <nl> " / / modules / drivers / canbus / can_client : can_client_factory " , <nl> " / / modules / drivers / canbus / can_comm : can_receiver " , <nl> " / / modules / drivers / canbus / can_comm : message_manager_base " , <nl> cc_library ( <nl> ] , <nl> ) <nl> <nl> - # cc_test ( <nl> - # name = " conti_radar_canbus_test " , <nl> - # size = " small " , <nl> - # srcs = [ " conti_radar_canbus_test . cc " ] , <nl> - # deps = [ <nl> - # " : conti_radar_canbus_lib " , <nl> - # " : conti_radar_message_manager " , <nl> - # " / / modules / drivers / proto : sensor_proto " , <nl> - # " @ gtest / / : main " , <nl> - # ] , <nl> - # ) <nl> - <nl> cc_binary ( <nl> - name = " conti_radar " , <nl> - srcs = [ " main . cc " ] , <nl> - deps = [ <nl> - " : conti_radar_canbus_lib " , <nl> - " / / external : gflags " , <nl> - " / / modules / common : log " , <nl> - " / / modules / common / monitor_log " , <nl> - " / / modules / drivers / canbus / common : canbus_common " , <nl> - " @ ros / / : ros_common " , <nl> - ] , <nl> + name = " libconti_radar . so " , <nl> + deps = [ " : conti_radar_canbus_lib " ] , <nl> + linkopts = [ " - shared " ] , <nl> ) <nl> <nl> cpplint ( ) <nl> deleted file mode 100644 <nl> index d5e9d26bafb . . 00000000000 <nl> mmm a / modules / drivers / radar / conti_radar / conf / adapter . conf <nl> ppp / dev / null <nl> <nl> - config { <nl> - type : CONTI_RADAR <nl> - mode : PUBLISH_ONLY <nl> - } <nl> - config { <nl> - type : MONITOR <nl> - mode : PUBLISH_ONLY <nl> - } <nl> - is_ros : true <nl> deleted file mode 100644 <nl> index 1df12391cc3 . . 00000000000 <nl> mmm a / modules / drivers / radar / conti_radar / conf / conti_radar . conf <nl> ppp / dev / null <nl> <nl> mmmflagfile = modules / common / data / global_flagfile . txt <nl> mmmalsologtostderr = 1 <nl> mmmsensor_conf_file = modules / drivers / radar / conti_radar / conf / conti_radar_conf . pb . txt <nl> mmmadapter_config_filename = modules / drivers / radar / conti_radar / conf / adapter . conf <nl> mmmnode_namespace = / apollo / drivers / conti_radar <nl> mmmsensor_node_name = conti_radar <nl> mmmcanbus_driver_name = conti_radar <nl> similarity index 65 % <nl> rename from modules / drivers / radar / conti_radar / conti_radar_canbus . cc <nl> rename to modules / drivers / radar / conti_radar / conti_radar_canbus_component . cc <nl> mmm a / modules / drivers / radar / conti_radar / conti_radar_canbus . cc <nl> ppp b / modules / drivers / radar / conti_radar / conti_radar_canbus_component . cc <nl> <nl> * @ file <nl> * / <nl> <nl> - # include " modules / drivers / radar / conti_radar / conti_radar_canbus . h " <nl> - # include " modules / drivers / radar / conti_radar / conti_radar_message_manager . h " <nl> + # include " modules / drivers / radar / conti_radar / conti_radar_canbus_component . h " <nl> # include " modules / drivers / proto / conti_radar . pb . h " <nl> + # include " modules / drivers / radar / conti_radar / conti_radar_message_manager . h " <nl> <nl> / * * <nl> * @ namespace apollo : : drivers : : conti_radar <nl> namespace apollo { <nl> namespace drivers { <nl> namespace conti_radar { <nl> <nl> - std : : string ContiRadarCanbus : : Name ( ) const { <nl> - return FLAGS_canbus_driver_name ; <nl> - } <nl> + ContiRadarCanbusComponent : : ContiRadarCanbusComponent ( ) { } <nl> + ContiRadarCanbusComponent : : ~ ContiRadarCanbusComponent ( ) { Stop ( ) ; } <nl> + <nl> + / / std : : string ContiRadarCanbusComponent : : Name ( ) const { <nl> + / / return FLAGS_canbus_driver_name ; <nl> + / / } <nl> <nl> - apollo : : common : : Status ContiRadarCanbus : : Init ( ) { <nl> - AdapterManager : : Init ( FLAGS_adapter_config_filename ) ; <nl> - AINFO < < " The adapter manager is successfully initialized . " ; <nl> - if ( ! : : apollo : : common : : util : : GetProtoFromFile ( FLAGS_sensor_conf_file , <nl> - & conti_radar_conf_ ) ) { <nl> - return OnError ( " Unable to load canbus conf file : " + <nl> - FLAGS_sensor_conf_file ) ; <nl> + bool ContiRadarCanbusComponent : : Init ( ) { <nl> + if ( ! GetProtoConfig ( & conti_radar_conf_ ) ) { <nl> + return OnError ( " Unable to load canbus conf file : " + ConfigFilePath ( ) ) ; <nl> } <nl> <nl> - AINFO < < " The canbus conf file is loaded : " < < FLAGS_sensor_conf_file ; <nl> + AINFO < < " The canbus conf file is loaded : " < < ConfigFilePath ( ) ; <nl> ADEBUG < < " Canbus_conf : " < < conti_radar_conf_ . ShortDebugString ( ) ; <nl> <nl> / / Init can client <nl> - auto * can_factory = CanClientFactory : : instance ( ) ; <nl> + auto can_factory = CanClientFactory : : Instance ( ) ; <nl> can_factory - > RegisterCanClients ( ) ; <nl> can_client_ = can_factory - > CreateCANClient ( <nl> conti_radar_conf_ . can_conf ( ) . can_card_parameter ( ) ) ; <nl> apollo : : common : : Status ContiRadarCanbus : : Init ( ) { <nl> return OnError ( " Failed to create can client . " ) ; <nl> } <nl> AINFO < < " Can client is successfully created . " ; <nl> + conti_radar_writer_ = <nl> + node_ - > CreateWriter < ContiRadar > ( " / apollo / sensor / conti_radar " ) ; <nl> <nl> - sensor_message_manager_ = <nl> - std : : unique_ptr < ContiRadarMessageManager > ( new ContiRadarMessageManager ( ) ) ; <nl> + sensor_message_manager_ = std : : unique_ptr < ContiRadarMessageManager > ( <nl> + new ContiRadarMessageManager ( conti_radar_writer_ ) ) ; <nl> if ( sensor_message_manager_ = = nullptr ) { <nl> return OnError ( " Failed to create message manager . " ) ; <nl> } <nl> apollo : : common : : Status ContiRadarCanbus : : Init ( ) { <nl> } <nl> AINFO < < " The can receiver is successfully initialized . " ; <nl> <nl> - return Status : : OK ( ) ; <nl> + return Start ( ) ; <nl> } <nl> <nl> - apollo : : common : : ErrorCode ContiRadarCanbus : : ConfigureRadar ( ) { <nl> + apollo : : common : : ErrorCode ContiRadarCanbusComponent : : ConfigureRadar ( ) { <nl> RadarConfig200 radar_config ; <nl> radar_config . set_radar_conf ( conti_radar_conf_ . radar_conf ( ) ) ; <nl> SenderMessage < ContiRadar > sender_message ( RadarConfig200 : : ID , & radar_config ) ; <nl> apollo : : common : : ErrorCode ContiRadarCanbus : : ConfigureRadar ( ) { <nl> return can_client_ - > SendSingleFrame ( { sender_message . CanFrame ( ) } ) ; <nl> } <nl> <nl> - apollo : : common : : Status ContiRadarCanbus : : Start ( ) { <nl> + bool ContiRadarCanbusComponent : : Start ( ) { <nl> / / 1 . init and start the can card hardware <nl> if ( can_client_ - > Start ( ) ! = ErrorCode : : OK ) { <nl> return OnError ( " Failed to start can client " ) ; <nl> apollo : : common : : Status ContiRadarCanbus : : Start ( ) { <nl> AINFO < < " Can receiver is started . " ; <nl> <nl> / / last step : publish monitor messages <nl> - apollo : : common : : monitor : : MonitorLogBuffer buffer ( & monitor_logger_ ) ; <nl> - buffer . INFO ( " Canbus is started . " ) ; <nl> + / / apollo : : common : : monitor : : MonitorLogBuffer buffer ( & monitor_logger_ ) ; <nl> + / / buffer . INFO ( " Canbus is started . " ) ; <nl> <nl> - return Status : : OK ( ) ; <nl> + return true ; <nl> } <nl> <nl> - void ContiRadarCanbus : : Stop ( ) { <nl> + void ContiRadarCanbusComponent : : Stop ( ) { <nl> can_receiver_ . Stop ( ) ; <nl> can_client_ - > Stop ( ) ; <nl> } <nl> <nl> - void ContiRadarCanbus : : PublishSensorData ( ) { <nl> - ContiRadar conti_radar ; <nl> - sensor_message_manager_ - > GetSensorData ( & conti_radar ) ; <nl> - ADEBUG < < conti_radar . ShortDebugString ( ) ; <nl> - <nl> - AdapterManager : : FillContiRadarHeader ( FLAGS_sensor_node_name , & conti_radar ) ; <nl> - AdapterManager : : PublishContiRadar ( conti_radar ) ; <nl> - } <nl> - <nl> / / Send the error to monitor and return it <nl> - Status ContiRadarCanbus : : OnError ( const std : : string & error_msg ) { <nl> - apollo : : common : : monitor : : MonitorLogBuffer buffer ( & monitor_logger_ ) ; <nl> - buffer . ERROR ( error_msg ) ; <nl> - return Status ( ErrorCode : : CANBUS_ERROR , error_msg ) ; <nl> + bool ContiRadarCanbusComponent : : OnError ( const std : : string & error_msg ) { <nl> + / / apollo : : common : : monitor : : MonitorLogBuffer buffer ( & monitor_logger_ ) ; <nl> + / / buffer . ERROR ( error_msg ) ; <nl> + / / return Status ( ErrorCode : : CANBUS_ERROR , error_msg ) ; <nl> + AERROR < < error_msg ; <nl> + return false ; <nl> } <nl> <nl> } / / namespace conti_radar <nl> similarity index 60 % <nl> rename from modules / drivers / radar / conti_radar / conti_radar_canbus . h <nl> rename to modules / drivers / radar / conti_radar / conti_radar_canbus_component . h <nl> mmm a / modules / drivers / radar / conti_radar / conti_radar_canbus . h <nl> ppp b / modules / drivers / radar / conti_radar / conti_radar_canbus_component . h <nl> <nl> * @ file <nl> * / <nl> <nl> - # ifndef MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_H_ <nl> - # define MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_H_ <nl> + # ifndef MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_COMPONENT_H_ <nl> + # define MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_COMPONENT_H_ <nl> <nl> # include < memory > <nl> # include < string > <nl> # include < utility > <nl> # include < vector > <nl> <nl> - # include " ros / include / ros / ros . h " <nl> + # include " cybertron / cybertron . h " <nl> <nl> - # include " modules / common / adapters / adapter_manager . h " <nl> - # include " modules / common / adapters / proto / adapter_config . pb . h " <nl> - # include " modules / common / apollo_app . h " <nl> # include " modules / common / macro . h " <nl> - # include " modules / common / monitor_log / monitor_log_buffer . h " <nl> - # include " modules / common / time / time . h " <nl> + / / # include " modules / common / monitor_log / monitor_log_buffer . h " <nl> # include " modules / common / util / util . h " <nl> - # include " modules / control / proto / control_cmd . pb . h " <nl> # include " modules / drivers / canbus / can_client / can_client . h " <nl> # include " modules / drivers / canbus / can_client / can_client_factory . h " <nl> # include " modules / drivers / canbus / can_comm / can_receiver . h " <nl> <nl> # include " modules / drivers / canbus / can_comm / message_manager . h " <nl> # include " modules / drivers / canbus / proto / can_card_parameter . pb . h " <nl> # include " modules / drivers / canbus / proto / sensor_canbus_conf . pb . h " <nl> - # include " modules / drivers / canbus / sensor_gflags . h " <nl> + # include " modules / drivers / proto / conti_radar . pb . h " <nl> # include " modules / drivers / radar / conti_radar / conti_radar_message_manager . h " <nl> # include " modules / drivers / radar / conti_radar / protocol / radar_config_200 . h " <nl> - # include " modules / drivers / proto / conti_radar . pb . h " <nl> <nl> / * * <nl> * @ namespace apollo : : drivers <nl> namespace drivers { <nl> namespace conti_radar { <nl> <nl> / * * <nl> - * @ class ContiRadarCanbus <nl> - * <nl> - * @ brief template of canbus - based sensor module main class ( e . g . , conti_radar ) . <nl> - * / <nl> + * @ class ContiRadarCanbus <nl> + * <nl> + * @ brief template of canbus - based sensor module main class ( e . g . , conti_radar ) . <nl> + * / <nl> <nl> - using apollo : : common : : adapter : : AdapterConfig ; <nl> - using apollo : : common : : adapter : : AdapterManager ; <nl> - using apollo : : common : : monitor : : MonitorMessageItem ; <nl> - using apollo : : common : : Status ; <nl> using apollo : : common : : ErrorCode ; <nl> + / / using apollo : : common : : monitor : : MonitorMessageItem ; <nl> using apollo : : common : : time : : Clock ; <nl> - using apollo : : drivers : : canbus : : CanClientFactory ; <nl> using apollo : : drivers : : canbus : : CanClient ; <nl> + using apollo : : drivers : : canbus : : CanClientFactory ; <nl> using apollo : : drivers : : canbus : : CanReceiver ; <nl> using apollo : : drivers : : canbus : : SenderMessage ; <nl> using apollo : : drivers : : canbus : : SensorCanbusConf ; <nl> + template < typename T > <nl> + using Writer = apollo : : cybertron : : Writer < T > ; <nl> <nl> - class ContiRadarCanbus : public apollo : : common : : ApolloApp { <nl> + class ContiRadarCanbusComponent : public apollo : : cybertron : : Component < > { <nl> public : <nl> - / / TODO ( lizh ) : check whether we need a new msg item , say <nl> - / / MonitorMessageItem : : SENSORCANBUS <nl> - ContiRadarCanbus ( ) <nl> - : monitor_logger_ ( apollo : : common : : monitor : : MonitorMessageItem : : CANBUS ) { } <nl> - <nl> - / * * <nl> - * @ brief obtain module name <nl> - * @ return module name <nl> - * / <nl> - std : : string Name ( ) const override ; <nl> - <nl> - / * * <nl> - * @ brief module initialization function <nl> - * @ return initialization status <nl> - * / <nl> - apollo : : common : : Status Init ( ) override ; <nl> - <nl> - / * * <nl> - * @ brief module start function <nl> - * @ return start status <nl> - * / <nl> - apollo : : common : : Status Start ( ) override ; <nl> - <nl> - / * * <nl> - * @ brief module stop function <nl> - * / <nl> - void Stop ( ) override ; <nl> + ContiRadarCanbusComponent ( ) ; <nl> + ~ ContiRadarCanbusComponent ( ) ; <nl> + bool Init ( ) override ; <nl> <nl> private : <nl> - void PublishSensorData ( ) ; <nl> - Status OnError ( const std : : string & error_msg ) ; <nl> + bool OnError ( const std : : string & error_msg ) ; <nl> void RegisterCanClients ( ) ; <nl> apollo : : common : : ErrorCode ConfigureRadar ( ) ; <nl> + bool Start ( ) ; <nl> + void Stop ( ) ; <nl> <nl> ContiRadarConf conti_radar_conf_ ; <nl> std : : shared_ptr < CanClient > can_client_ ; <nl> CanReceiver < ContiRadar > can_receiver_ ; <nl> std : : unique_ptr < ContiRadarMessageManager > sensor_message_manager_ ; <nl> + std : : shared_ptr < Writer < ContiRadar > > conti_radar_writer_ ; <nl> <nl> int64_t last_timestamp_ = 0 ; <nl> - apollo : : common : : monitor : : MonitorLogger monitor_logger_ ; <nl> + / / apollo : : common : : monitor : : MonitorLogger monitor_logger_ ; <nl> } ; <nl> <nl> } / / namespace conti_radar <nl> } / / namespace drivers <nl> } / / namespace apollo <nl> - <nl> - # endif / / MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_H_ <nl> + CYBERTRON_REGISTER_COMPONENT ( apollo : : drivers : : conti_radar : : ContiRadarCanbusComponent ) <nl> + # endif / / MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_CANBUS_COMPONENT_H_ <nl> mmm a / modules / drivers / radar / conti_radar / conti_radar_message_manager . cc <nl> ppp b / modules / drivers / radar / conti_radar / conti_radar_message_manager . cc <nl> <nl> <nl> # include " modules / drivers / radar / conti_radar / conti_radar_message_manager . h " <nl> <nl> + # include " modules / common / util / message_util . h " <nl> # include " modules / drivers / radar / conti_radar / protocol / cluster_general_info_701 . h " <nl> # include " modules / drivers / radar / conti_radar / protocol / cluster_list_status_600 . h " <nl> # include " modules / drivers / radar / conti_radar / protocol / cluster_quality_info_702 . h " <nl> namespace apollo { <nl> namespace drivers { <nl> namespace conti_radar { <nl> <nl> - using : : apollo : : common : : adapter : : AdapterManager ; <nl> - <nl> - ContiRadarMessageManager : : ContiRadarMessageManager ( ) { <nl> + ContiRadarMessageManager : : ContiRadarMessageManager ( <nl> + const std : : shared_ptr < Writer < ContiRadar > > & writer ) <nl> + : conti_radar_writer_ ( writer ) { <nl> AddRecvProtocolData < RadarState201 , true > ( ) ; <nl> AddRecvProtocolData < ClusterListStatus600 , true > ( ) ; <nl> AddRecvProtocolData < ClusterGeneralInfo701 , true > ( ) ; <nl> void ContiRadarMessageManager : : Parse ( const uint32_t message_id , <nl> if ( sensor_data_ . contiobs_size ( ) < = <nl> sensor_data_ . object_list_status ( ) . nof_objects ( ) ) { <nl> / / maybe lost a object_list_status msg <nl> - AdapterManager : : PublishContiRadar ( sensor_data_ ) ; <nl> + conti_radar_writer_ - > Write ( std : : make_shared < ContiRadar > ( sensor_data_ ) ) ; <nl> } <nl> sensor_data_ . Clear ( ) ; <nl> / / fill header when recieve the general info message <nl> - AdapterManager : : FillContiRadarHeader ( FLAGS_sensor_node_name , & sensor_data_ ) ; <nl> + common : : util : : FillHeader ( " conti_radar " , & sensor_data_ ) ; <nl> } <nl> <nl> sensor_protocol_data - > Parse ( data , length , & sensor_data_ ) ; <nl> mmm a / modules / drivers / radar / conti_radar / conti_radar_message_manager . h <nl> ppp b / modules / drivers / radar / conti_radar / conti_radar_message_manager . h <nl> <nl> # define MODULES_DRIVERS_RADAR_CONTI_RADAR_CONTI_RADAR_MESSAGE_MANAGER_H_ <nl> <nl> # include < memory > <nl> + # include " cybertron / cybertron . h " <nl> # include " modules / drivers / canbus / can_client / can_client_factory . h " <nl> # include " modules / drivers / canbus / can_comm / can_sender . h " <nl> # include " modules / drivers / canbus / can_comm / message_manager . h " <nl> - # include " modules / drivers / radar / conti_radar / protocol / radar_config_200 . h " <nl> # include " modules / drivers / proto / conti_radar . pb . h " <nl> + # include " modules / drivers / radar / conti_radar / protocol / radar_config_200 . h " <nl> <nl> - # include " modules / common / adapters / adapter_manager . h " <nl> - # include " modules / drivers / canbus / sensor_gflags . h " <nl> <nl> namespace apollo { <nl> namespace drivers { <nl> namespace conti_radar { <nl> <nl> - using : : apollo : : drivers : : canbus : : ProtocolData ; <nl> - using : : apollo : : common : : adapter : : AdapterManager ; <nl> using : : apollo : : drivers : : canbus : : MessageManager ; <nl> + using : : apollo : : drivers : : canbus : : ProtocolData ; <nl> using Clock = : : apollo : : common : : time : : Clock ; <nl> using micros = std : : chrono : : microseconds ; <nl> using : : apollo : : common : : ErrorCode ; <nl> using apollo : : drivers : : canbus : : CanClient ; <nl> using apollo : : drivers : : canbus : : SenderMessage ; <nl> using apollo : : drivers : : conti_radar : : RadarConfig200 ; <nl> + template < typename T > <nl> + using Writer = apollo : : cybertron : : Writer < T > ; <nl> <nl> class ContiRadarMessageManager : public MessageManager < ContiRadar > { <nl> public : <nl> - ContiRadarMessageManager ( ) ; <nl> + explicit ContiRadarMessageManager ( <nl> + const std : : shared_ptr < Writer < ContiRadar > > & writer ) ; <nl> virtual ~ ContiRadarMessageManager ( ) { } <nl> void set_radar_conf ( RadarConf radar_conf ) ; <nl> ProtocolData < ContiRadar > * GetMutableProtocolDataById ( <nl> class ContiRadarMessageManager : public MessageManager < ContiRadar > { <nl> bool is_configured_ = false ; <nl> RadarConfig200 radar_config_ ; <nl> std : : shared_ptr < CanClient > can_client_ ; <nl> + std : : shared_ptr < Writer < ContiRadar > > conti_radar_writer_ ; <nl> } ; <nl> <nl> } / / namespace conti_radar <nl> new file mode 100644 <nl> index 00000000000 . . 1d0fd1d965e <nl> mmm / dev / null <nl> ppp b / modules / drivers / radar / conti_radar / dag / conti_radar . dag <nl> <nl> + module_config { <nl> + module_library : " / apollo / bazel - bin / modules / drivers / radar / conti_radar / libconti_radar . so " <nl> + components { <nl> + class_name : " ContiRadarCanbusComponent " <nl> + config { <nl> + name : " driver " <nl> + config_file_path : " / apollo / modules / drivers / radar / conti_radar / conf / conti_radar_conf . pb . txt " <nl> + } <nl> + } <nl> + } <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 00000000000 . . df2704149dd <nl> mmm / dev / null <nl> ppp b / modules / drivers / radar / conti_radar / launch / conti_radar . launch <nl> <nl> + < cybertron > <nl> + < module > <nl> + < name > conti_radar < / name > <nl> + < dag_conf > / apollo / modules / drivers / radar / conti_radar / dag / conti_radar . dag < / dag_conf > <nl> + < process_name > conti_radar < / process_name > <nl> + < / module > <nl> + < / cybertron > <nl> deleted file mode 100644 <nl> index 343f86ea422 . . 00000000000 <nl> mmm a / modules / drivers / radar / conti_radar / main . cc <nl> ppp / dev / null <nl> <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - * Copyright 2017 The Apollo Authors . All Rights Reserved . <nl> - * <nl> - * Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - * you may not use this file except in compliance with the License . <nl> - * You may obtain a copy of the License at <nl> - * <nl> - * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - * <nl> - * Unless required by applicable law or agreed to in writing , software <nl> - * distributed under the License is distributed on an " AS IS " BASIS , <nl> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - * See the License for the specific language governing permissions and <nl> - * limitations under the License . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - # include " modules / common / apollo_app . h " <nl> - # include " modules / drivers / radar / conti_radar / conti_radar_canbus . h " <nl> - <nl> - using : : apollo : : drivers : : conti_radar : : ContiRadarCanbus ; <nl> - APOLLO_MAIN ( ContiRadarCanbus ) ; <nl> | conti_radar : first migration version | ApolloAuto/apollo | 6073da4e5abd64667acb5a0aba68abbd0941b44d | 2018-09-10T22:30:16Z |
mmm a / validation - test / stdlib / NewArray . swift . gyb <nl> ppp b / validation - test / stdlib / NewArray . swift . gyb <nl> func testInoutViolation ( ) { <nl> % for A in arrayTypes : <nl> if true { <nl> var b = $ { A } ( a ) <nl> - b . sorted { x , y in <nl> + _ = b . sorted { x , y in <nl> b . removeAll ( ) <nl> return x < y <nl> } <nl> func testInoutViolation ( ) { <nl> <nl> / / An overload of sorted for Arrays uses withUnsafeMutableBufferPointer , <nl> / / which disables bounds checks . <nl> - a . sorted { x , y in <nl> + _ = a . sorted { x , y in <nl> a = [ ] / / Invalidate the whole array during sorting <nl> return x < y <nl> } <nl> | Silence warnings in NewArray . swift . gyb | apple/swift | 8ef59b187dd30eb233298181575041677153e939 | 2016-03-20T01:07:58Z |
mmm a / dbms / src / AggregateFunctions / AggregateFunctionForEach . h <nl> ppp b / dbms / src / AggregateFunctions / AggregateFunctionForEach . h <nl> class AggregateFunctionForEach final : public IAggregateFunctionDataHelper < Aggre <nl> nested_state + = nested_size_of_data ; <nl> } <nl> <nl> - offsets_to . push_back ( offsets_to . empty ( ) ? state . dynamic_array_size : offsets_to . back ( ) + state . dynamic_array_size ) ; <nl> + offsets_to . push_back ( offsets_to . back ( ) + state . dynamic_array_size ) ; <nl> } <nl> <nl> bool allocatesMemoryInArena ( ) const override <nl> mmm a / dbms / src / AggregateFunctions / AggregateFunctionGroupArrayInsertAt . h <nl> ppp b / dbms / src / AggregateFunctions / AggregateFunctionGroupArrayInsertAt . h <nl> class AggregateFunctionGroupArrayInsertAtGeneric final <nl> for ( size_t i = arr . size ( ) ; i < result_array_size ; + + i ) <nl> to_data . insert ( default_value ) ; <nl> <nl> - to_offsets . push_back ( ( to_offsets . empty ( ) ? 0 : to_offsets . back ( ) ) + result_array_size ) ; <nl> + to_offsets . push_back ( to_offsets . back ( ) + result_array_size ) ; <nl> } <nl> <nl> const char * getHeaderFilePath ( ) const override { return __FILE__ ; } <nl> | Addition to Amos Bird changes | ClickHouse/ClickHouse | a594293b50667ecff057be266a21445894d51048 | 2019-01-08T14:55:37Z |
mmm a / tensorflow / compiler / xla / python_api / xla_literal . py <nl> ppp b / tensorflow / compiler / xla / python_api / xla_literal . py <nl> def _ConvertNumpyArrayToLiteral ( ndarray ) : <nl> <nl> if ndarray . ndim = = 0 : <nl> getattr ( literal , type_record . literal_field_name ) . append ( <nl> - _np . asscalar ( ndarray . astype ( type_record . literal_field_type ) ) ) <nl> + ndarray . astype ( type_record . literal_field_type ) . item ( ) ) <nl> else : <nl> # Ndarrays with boolean dtypes need special type conversion with protobufs <nl> if ndarray . dtype in { _np . bool_ , _np . dtype ( ' bool ' ) } : <nl> mmm a / tensorflow / python / framework / fast_tensor_util . pyx <nl> ppp b / tensorflow / python / framework / fast_tensor_util . pyx <nl> def AppendBoolArrayToTensorProto ( tensor_proto , nparray ) : <nl> cdef long i , n <nl> n = nparray . size <nl> for i in range ( n ) : <nl> - tensor_proto . bool_val . append ( np . asscalar ( nparray [ i ] ) ) <nl> + tensor_proto . bool_val . append ( nparray . item ( i ) ) <nl> mmm a / tensorflow / python / framework / tensor_util . py <nl> ppp b / tensorflow / python / framework / tensor_util . py <nl> <nl> <nl> <nl> def ExtractBitsFromFloat16 ( x ) : <nl> - return np . asscalar ( np . asarray ( x , dtype = np . float16 ) . view ( np . uint16 ) ) <nl> + return np . asarray ( x , dtype = np . float16 ) . view ( np . uint16 ) . item ( ) <nl> <nl> <nl> def SlowAppendFloat16ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> def _MediumAppendFloat16ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> <nl> <nl> def ExtractBitsFromBFloat16 ( x ) : <nl> - return np . asscalar ( <nl> - np . asarray ( x , dtype = dtypes . bfloat16 . as_numpy_dtype ) . view ( np . uint16 ) ) <nl> + return np . asarray ( <nl> + x , dtype = dtypes . bfloat16 . as_numpy_dtype ) . view ( np . uint16 ) . item ( ) <nl> <nl> <nl> def SlowAppendBFloat16ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> def FastAppendBFloat16ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> else : <nl> <nl> def SlowAppendFloat32ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . float_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . float_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendFloat64ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . double_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . double_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendIntArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . int_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . int_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendInt64ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . int64_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . int64_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendQIntArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . int_val . extend ( [ np . asscalar ( x [ 0 ] ) for x in proto_values ] ) <nl> + tensor_proto . int_val . extend ( [ x . item ( 0 ) for x in proto_values ] ) <nl> <nl> def SlowAppendUInt32ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . uint32_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . uint32_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendUInt64ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . uint64_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . uint64_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> def SlowAppendComplex64ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> tensor_proto . scomplex_val . extend ( <nl> - [ np . asscalar ( v ) for x in proto_values for v in [ x . real , x . imag ] ] ) <nl> + [ v . item ( ) for x in proto_values for v in [ x . real , x . imag ] ] ) <nl> <nl> def SlowAppendComplex128ArrayToTensorProto ( tensor_proto , proto_values ) : <nl> tensor_proto . dcomplex_val . extend ( <nl> - [ np . asscalar ( v ) for x in proto_values for v in [ x . real , x . imag ] ] ) <nl> + [ v . item ( ) for x in proto_values for v in [ x . real , x . imag ] ] ) <nl> <nl> def SlowAppendObjectArrayToTensorProto ( tensor_proto , proto_values ) : <nl> tensor_proto . string_val . extend ( [ compat . as_bytes ( x ) for x in proto_values ] ) <nl> <nl> def SlowAppendBoolArrayToTensorProto ( tensor_proto , proto_values ) : <nl> - tensor_proto . bool_val . extend ( [ np . asscalar ( x ) for x in proto_values ] ) <nl> + tensor_proto . bool_val . extend ( [ x . item ( ) for x in proto_values ] ) <nl> <nl> _NP_TO_APPEND_FN = { <nl> dtypes . bfloat16 . as_numpy_dtype : SlowAppendBFloat16ArrayToTensorProto , <nl> mmm a / tensorflow / python / kernel_tests / cwise_ops_test . py <nl> ppp b / tensorflow / python / kernel_tests / cwise_ops_test . py <nl> def testDifferentShapes ( self ) : <nl> <nl> def testScalar ( self ) : <nl> x = np . random . rand ( 1 , 3 , 2 ) * 100 . <nl> - y = np . asscalar ( np . random . rand ( 1 ) * 100 . ) # should broadcast <nl> + y = np . random . rand ( 1 ) . item ( ) * 100 . # should broadcast <nl> # dropped np . float64 , int64 because TF automatically converts to 32 bit <nl> for t in [ np . float32 , np . int32 ] : <nl> self . _compare ( x . astype ( t ) , t ( y ) , use_gpu = False ) <nl> mmm a / tensorflow / python / ops / nn_ops . py <nl> ppp b / tensorflow / python / ops / nn_ops . py <nl> def leaky_relu ( features , alpha = 0 . 2 , name = None ) : <nl> features = math_ops . to_float ( features ) <nl> if compat . forward_compatible ( 2018 , 11 , 1 ) : <nl> if isinstance ( alpha , np . ndarray ) : <nl> - alpha = np . asscalar ( alpha ) <nl> + alpha = alpha . item ( ) <nl> return gen_nn_ops . leaky_relu ( features , alpha = alpha , name = name ) <nl> alpha = ops . convert_to_tensor ( alpha , dtype = features . dtype , name = " alpha " ) <nl> return math_ops . maximum ( alpha * features , features , name = name ) <nl> | Replace deprecated usage of np . asscalar with np . ndarray . item ( ) | tensorflow/tensorflow | ae1418f9180c53687ce716bbf19a0a15827db567 | 2019-01-24T12:59:46Z |
mmm a / src / preferences / options . ui <nl> ppp b / src / preferences / options . ui <nl> <nl> < / property > <nl> < item > <nl> < property name = " text " > <nl> - < string > Start / Stop < / string > <nl> + < string > Start / Stop Torrent < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> <nl> < widget class = " QComboBox " name = " actionTorrentFnOnDblClBox " > <nl> < item > <nl> < property name = " text " > <nl> - < string > Start / Stop < / string > <nl> + < string > Start / Stop Torrent < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> QGroupBox { <nl> < property name = " geometry " > <nl> < rect > <nl> < x > 0 < / x > <nl> - < y > 0 < / y > <nl> + < y > - 25 < / y > <nl> < width > 570 < / width > <nl> < height > 422 < / height > <nl> < / rect > <nl> QGroupBox { <nl> < item > <nl> < widget class = " QGroupBox " name = " AddBTFeaturesBox " > <nl> < property name = " title " > <nl> - < string > BitTorrent features < / string > <nl> + < string > Privacy < / string > <nl> < / property > <nl> < layout class = " QVBoxLayout " name = " verticalLayout_14 " > <nl> < item > <nl> QGroupBox { <nl> < item > <nl> < widget class = " QLabel " name = " lbl_encryption " > <nl> < property name = " text " > <nl> - < string > Protocol encryption : < / string > <nl> + < string > Encryption mode : < / string > <nl> < / property > <nl> < / widget > <nl> < / item > <nl> QGroupBox { <nl> < widget class = " QComboBox " name = " comboEncryption " > <nl> < item > <nl> < property name = " text " > <nl> - < string > Enabled < / string > <nl> + < string > Prefer encryption < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> < property name = " text " > <nl> - < string > Forced < / string > <nl> + < string > Require encryption < / string > <nl> < / property > <nl> < / item > <nl> < item > <nl> < property name = " text " > <nl> - < string > Disabled < / string > <nl> + < string > Disable encryption < / string > <nl> < / property > <nl> < / item > <nl> < / widget > <nl> QGroupBox { <nl> < rect > <nl> < x > 0 < / x > <nl> < y > 0 < / y > <nl> - < width > 396 < / width > <nl> - < height > 229 < / height > <nl> + < width > 524 < / width > <nl> + < height > 414 < / height > <nl> < / rect > <nl> < / property > <nl> < layout class = " QVBoxLayout " name = " verticalLayout_23 " > <nl> QGroupBox { <nl> < rect > <nl> < x > 0 < / x > <nl> < y > 0 < / y > <nl> - < width > 98 < / width > <nl> - < height > 28 < / height > <nl> + < width > 524 < / width > <nl> + < height > 414 < / height > <nl> < / rect > <nl> < / property > <nl> < layout class = " QVBoxLayout " name = " verticalLayout_36 " / > <nl> | Improve program preferences | qbittorrent/qBittorrent | dff1e6563426e9d547bbc530aa4e2bdf1df79ee4 | 2010-12-05T17:27:42Z |
mmm a / include / swift / ABI / ValueWitness . def <nl> ppp b / include / swift / ABI / ValueWitness . def <nl> <nl> / / / TYPE_TYPE - a pointer to type metadata <nl> / / / SIZE_TYPE - size_t <nl> / / / INT_TYPE - int <nl> - / / / UINT_TYPE - unsigned int <nl> / / / VOID_TYPE - void <nl> / / / Defaults to VALUE_WITNESS . <nl> / / / FIXME : The ' copy ' witnesses should be using immutable types but aren ' t . <nl> FUNCTION_VALUE_WITNESS ( initializeBufferWithTakeOfBuffer , <nl> MUTABLE_VALUE_TYPE , <nl> ( MUTABLE_BUFFER_TYPE , MUTABLE_BUFFER_TYPE , TYPE_TYPE ) ) <nl> <nl> - / / / int ( * getEnumTagSinglePayload ) ( const T * enum , UINT_TYPE emptyCases ) <nl> - / / / Given an instance of valid single payload enum with a payload of this <nl> - / / / witness table ' s type ( e . g Optional < ThisType > ) , get the tag of the enum . <nl> - FUNCTION_VALUE_WITNESS ( getEnumTagSinglePayload , <nl> - GetEnumTagSinglePayload , <nl> - INT_TYPE , <nl> - ( IMMUTABLE_VALUE_TYPE , UINT_TYPE , TYPE_TYPE ) ) <nl> - <nl> - / / / void ( * storeEnumTagSinglePayload ) ( T * enum , INT_TYPE whichCase , <nl> - / / / UINT_TYPE emptyCases ) <nl> - / / / Given uninitialized memory for an instance of a single payload enum with a <nl> - / / / payload of this witness table ' s type ( e . g Optional < ThisType > ) , store the <nl> - / / / tag . <nl> - FUNCTION_VALUE_WITNESS ( storeEnumTagSinglePayload , <nl> - StoreEnumTagSinglePayload , <nl> - VOID_TYPE , <nl> - ( MUTABLE_VALUE_TYPE , INT_TYPE , UINT_TYPE , TYPE_TYPE ) ) <nl> - <nl> END_VALUE_WITNESS_RANGE ( RequiredValueWitnessFunction , <nl> - StoreEnumTagSinglePayload ) <nl> + InitializeBufferWithTakeOfBuffer ) <nl> <nl> / / / size_t size ; <nl> / / / <nl> mmm a / include / swift / Demangling / ValueWitnessMangling . def <nl> ppp b / include / swift / Demangling / ValueWitnessMangling . def <nl> VALUE_WITNESS ( xg , GetExtraInhabitantIndex ) <nl> VALUE_WITNESS ( ug , GetEnumTag ) <nl> VALUE_WITNESS ( up , DestructiveProjectEnumData ) <nl> VALUE_WITNESS ( ui , DestructiveInjectEnumTag ) <nl> - VALUE_WITNESS ( et , GetEnumTagSinglePayload ) <nl> - VALUE_WITNESS ( st , StoreEnumTagSinglePayload ) <nl> <nl> # undef VALUE_WITNESS <nl> mmm a / include / swift / Runtime / Metadata . h <nl> ppp b / include / swift / Runtime / Metadata . h <nl> namespace value_witness_types { <nl> # define TYPE_TYPE const Metadata * <nl> # define SIZE_TYPE size_t <nl> # define INT_TYPE int <nl> - # define UINT_TYPE unsigned <nl> # define VOID_TYPE void <nl> # include " swift / ABI / ValueWitness . def " <nl> <nl> mmm a / lib / Demangling / NodePrinter . cpp <nl> ppp b / lib / Demangling / NodePrinter . cpp <nl> static StringRef toString ( ValueWitnessKind k ) { <nl> return " destructiveProjectEnumData " ; <nl> case ValueWitnessKind : : DestructiveInjectEnumTag : <nl> return " destructiveInjectEnumTag " ; <nl> - case ValueWitnessKind : : GetEnumTagSinglePayload : <nl> - return " getEnumTagSinglePayload " ; <nl> - case ValueWitnessKind : : StoreEnumTagSinglePayload : <nl> - return " storeEnumTagSinglePayload " ; <nl> } <nl> printer_unreachable ( " bad value witness kind " ) ; <nl> } <nl> mmm a / lib / IRGen / FixedTypeInfo . h <nl> ppp b / lib / IRGen / FixedTypeInfo . h <nl> class FixedTypeInfo : public TypeInfo { <nl> llvm : : Value * metadata , <nl> llvm : : Value * vwtable , <nl> SILType T ) const override { } <nl> - <nl> - llvm : : Value * getEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const override ; <nl> - <nl> - void storeEnumTagSinglePayload ( IRGenFunction & IGF , llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , Address enumAddr , <nl> - SILType T ) const override ; <nl> - <nl> + <nl> static bool classof ( const FixedTypeInfo * type ) { return true ; } <nl> static bool classof ( const TypeInfo * type ) { return type - > isFixedSize ( ) ; } <nl> } ; <nl> mmm a / lib / IRGen / GenEnum . cpp <nl> ppp b / lib / IRGen / GenEnum . cpp <nl> namespace { <nl> / / / Emit a call into the runtime to get the current enum payload tag . <nl> / / / This returns a tag index in the range <nl> / / / [ - ElementsWithPayload . . ElementsWithNoPayload - 1 ] . <nl> - llvm : : Value * emitGetEnumTag ( IRGenFunction & IGF , SILType T , <nl> - Address enumAddr ) const override { <nl> - auto numEmptyCases = <nl> - llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , ElementsWithNoPayload . size ( ) ) ; <nl> + llvm : : Value * <nl> + emitGetEnumTag ( IRGenFunction & IGF , SILType T , Address enumAddr ) <nl> + const override { <nl> + auto payloadMetadata = emitPayloadMetadataForLayout ( IGF , T ) ; <nl> + auto numEmptyCases = llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , <nl> + ElementsWithNoPayload . size ( ) ) ; <nl> <nl> - auto PayloadT = getPayloadType ( IGF . IGM , T ) ; <nl> - auto opaqueAddr = Address ( <nl> - IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , IGF . IGM . OpaquePtrTy ) , <nl> - enumAddr . getAlignment ( ) ) ; <nl> - return emitGetEnumTagSinglePayloadCall ( IGF , PayloadT , numEmptyCases , <nl> - opaqueAddr ) ; <nl> + auto opaqueAddr = IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , <nl> + IGF . IGM . OpaquePtrTy ) ; <nl> + <nl> + return IGF . Builder . CreateCall ( <nl> + IGF . IGM . getGetEnumCaseSinglePayloadFn ( ) , <nl> + { opaqueAddr , payloadMetadata , numEmptyCases } ) ; <nl> } <nl> <nl> / / / The payload for a single - payload enum is always placed in front and <nl> namespace { <nl> } <nl> return ; <nl> } <nl> - llvm : : Value * opaqueAddr = <nl> - IGF . Builder . CreateBitCast ( dest . getAddress ( ) , IGF . IGM . OpaquePtrTy ) ; <nl> <nl> - auto PayloadT = getPayloadType ( IGF . IGM , T ) ; <nl> - auto Addr = Address ( opaqueAddr , dest . getAlignment ( ) ) ; <nl> - auto * whichCase = llvm : : ConstantInt : : getSigned ( IGF . IGM . Int32Ty , - 1 ) ; <nl> - auto * numEmptyCases = <nl> - llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , ElementsWithNoPayload . size ( ) ) ; <nl> - emitStoreEnumTagSinglePayloadCall ( IGF , PayloadT , whichCase , numEmptyCases , <nl> - Addr ) ; <nl> + / / Ask the runtime to store the tag . <nl> + llvm : : Value * opaqueAddr = IGF . Builder . CreateBitCast ( dest . getAddress ( ) , <nl> + IGF . IGM . OpaquePtrTy ) ; <nl> + llvm : : Value * metadata = emitPayloadMetadataForLayout ( IGF , T ) ; <nl> + IGF . Builder . CreateCall ( IGF . IGM . getStoreEnumTagSinglePayloadFn ( ) , <nl> + { opaqueAddr , metadata , <nl> + llvm : : ConstantInt : : getSigned ( IGF . IGM . Int32Ty , - 1 ) , <nl> + llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , <nl> + ElementsWithNoPayload . size ( ) ) } ) ; <nl> } <nl> <nl> / / / Emit a reassignment sequence from an enum at one address to another . <nl> namespace { <nl> EnumElementDecl * Case ) const override { <nl> if ( TIK < Fixed ) { <nl> / / If the enum isn ' t fixed - layout , get the runtime to do this for us . <nl> + llvm : : Value * payload = emitPayloadMetadataForLayout ( IGF , T ) ; <nl> llvm : : Value * caseIndex ; <nl> if ( Case = = getPayloadElement ( ) ) { <nl> caseIndex = llvm : : ConstantInt : : getSigned ( IGF . IGM . Int32Ty , - 1 ) ; <nl> namespace { <nl> llvm : : Value * opaqueAddr <nl> = IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , <nl> IGF . IGM . OpaquePtrTy ) ; <nl> - auto PayloadT = getPayloadType ( IGF . IGM , T ) ; <nl> - auto Addr = Address ( opaqueAddr , enumAddr . getAlignment ( ) ) ; <nl> - emitStoreEnumTagSinglePayloadCall ( IGF , PayloadT , caseIndex , <nl> - numEmptyCases , Addr ) ; <nl> + <nl> + IGF . Builder . CreateCall ( IGF . IGM . getStoreEnumTagSinglePayloadFn ( ) , <nl> + { opaqueAddr , payload , caseIndex , numEmptyCases } ) ; <nl> + <nl> return ; <nl> } <nl> <nl> namespace { <nl> <nl> / / / Constructs an enum value using a tag index in the range <nl> / / / [ - ElementsWithPayload . . ElementsWithNoPayload - 1 ] . <nl> - void emitStoreTag ( IRGenFunction & IGF , SILType T , Address enumAddr , <nl> + void emitStoreTag ( IRGenFunction & IGF , <nl> + SILType T , <nl> + Address enumAddr , <nl> llvm : : Value * tag ) const override { <nl> - auto PayloadT = getPayloadType ( IGF . IGM , T ) ; <nl> + llvm : : Value * payload = emitPayloadMetadataForLayout ( IGF , T ) ; <nl> + llvm : : Value * numEmptyCases = llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , <nl> + ElementsWithNoPayload . size ( ) ) ; <nl> + <nl> llvm : : Value * opaqueAddr <nl> = IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , <nl> - IGF . IGM . OpaquePtrTy ) ; <nl> + IGF . IGM . OpaquePtrTy ) ; <nl> <nl> - llvm : : Value * numEmptyCases = llvm : : ConstantInt : : get ( IGF . IGM . Int32Ty , <nl> - ElementsWithNoPayload . size ( ) ) ; <nl> - auto Addr = Address ( opaqueAddr , enumAddr . getAlignment ( ) ) ; <nl> - emitStoreEnumTagSinglePayloadCall ( IGF , PayloadT , tag , numEmptyCases , <nl> - Addr ) ; <nl> + IGF . Builder . CreateCall ( IGF . IGM . getStoreEnumTagSinglePayloadFn ( ) , <nl> + { opaqueAddr , payload , tag , numEmptyCases } ) ; <nl> } <nl> <nl> void initializeMetadata ( IRGenFunction & IGF , <nl> mmm a / lib / IRGen / GenOpaque . cpp <nl> ppp b / lib / IRGen / GenOpaque . cpp <nl> <nl> # include " llvm / ADT / SmallString . h " <nl> # include " llvm / Support / raw_ostream . h " <nl> # include " llvm / IR / DerivedTypes . h " <nl> - # include " swift / AST / IRGenOptions . h " <nl> # include " swift / IRGen / ValueWitness . h " <nl> <nl> # include " Callee . h " <nl> static llvm : : Type * createWitnessType ( IRGenModule & IGM , ValueWitness index ) { <nl> return llvm : : FunctionType : : get ( voidTy , args , / * isVarArg * / false ) ; <nl> } <nl> <nl> - / / / int ( * getEnumTagSinglePayload ) ( const T * enum , UINT_TYPE emptyCases , <nl> - / / / M * self ) <nl> - case ValueWitness : : GetEnumTagSinglePayload : { <nl> - llvm : : Type * ptrTy = IGM . OpaquePtrTy ; <nl> - llvm : : Type * indexTy = IGM . Int32Ty ; <nl> - llvm : : Type * metaTy = IGM . TypeMetadataPtrTy ; <nl> - <nl> - llvm : : Type * args [ ] = { ptrTy , indexTy , metaTy } ; <nl> - return llvm : : FunctionType : : get ( indexTy , args , false ) ; <nl> - } <nl> - <nl> - / / / void ( * storeEnumTagSinglePayload ) ( T * enum , INT_TYPE whichCase , <nl> - / / / UINT_TYPE emptyCases , <nl> - / / / M * self ) <nl> - case ValueWitness : : StoreEnumTagSinglePayload : { <nl> - llvm : : Type * voidTy = IGM . VoidTy ; <nl> - llvm : : Type * ptrTy = IGM . OpaquePtrTy ; <nl> - llvm : : Type * indexTy = IGM . Int32Ty ; <nl> - llvm : : Type * metaTy = IGM . TypeMetadataPtrTy ; <nl> - <nl> - llvm : : Type * args [ ] = { ptrTy , indexTy , indexTy , metaTy } ; <nl> - return llvm : : FunctionType : : get ( voidTy , args , false ) ; <nl> - } <nl> - <nl> case ValueWitness : : Size : <nl> case ValueWitness : : Flags : <nl> case ValueWitness : : Stride : <nl> static llvm : : Type * createWitnessType ( IRGenModule & IGM , ValueWitness index ) { <nl> / / Non - function witnesses all have type size_t . <nl> return IGM . SizeTy ; <nl> } <nl> - <nl> llvm_unreachable ( " bad value witness ! " ) ; <nl> } <nl> <nl> static llvm : : AttributeList getValueWitnessAttrs ( IRGenModule & IGM , <nl> case ValueWitness : : GetEnumTag : <nl> case ValueWitness : : GetExtraInhabitantIndex : <nl> case ValueWitness : : StoreExtraInhabitant : <nl> - case ValueWitness : : StoreEnumTagSinglePayload : <nl> return attrs . addAttribute ( ctx , 1 , llvm : : Attribute : : NoAlias ) ; <nl> <nl> - case ValueWitness : : GetEnumTagSinglePayload : <nl> - return attrs <nl> - . addAttribute ( ctx , llvm : : AttributeList : : FunctionIndex , <nl> - llvm : : Attribute : : ReadOnly ) <nl> - . addAttribute ( ctx , 1 , llvm : : Attribute : : NoAlias ) ; <nl> - <nl> / / These have two arguments and they don ' t alias each other . <nl> case ValueWitness : : AssignWithTake : <nl> case ValueWitness : : InitializeBufferWithCopyOfBuffer : <nl> static StringRef getValueWitnessLabel ( ValueWitness index ) { <nl> return " destructiveProjectEnumData " ; <nl> case ValueWitness : : DestructiveInjectEnumTag : <nl> return " destructiveInjectEnumTag " ; <nl> - case ValueWitness : : GetEnumTagSinglePayload : <nl> - return " getEnumTagSinglePayload " ; <nl> - case ValueWitness : : StoreEnumTagSinglePayload : <nl> - return " storeEnumTagSinglePayload " ; <nl> } <nl> llvm_unreachable ( " bad value witness index " ) ; <nl> } <nl> llvm : : Value * irgen : : emitStoreExtraInhabitantCall ( IRGenFunction & IGF , <nl> return call ; <nl> } <nl> <nl> - / / / Emit a trampoline to call the getEnumTagSinglePayload witness . API : <nl> - / / / INT_TYPE ( const T * enum , UINT_TYPE emptyCases , M * self ) <nl> - static llvm : : Constant * <nl> - getGetEnumTagSinglePayloadTrampolineFn ( IRGenModule & IGM ) { <nl> - <nl> - llvm : : Type * argTys [ ] = { IGM . OpaquePtrTy , IGM . Int32Ty , IGM . TypeMetadataPtrTy } ; <nl> - <nl> - llvm : : SmallString < 40 > fnName ( " __swift_getEnumTagSinglePayload " ) ; <nl> - <nl> - auto func = IGM . getOrCreateHelperFunction ( <nl> - fnName , IGM . Int32Ty , argTys , <nl> - [ & ] ( IRGenFunction & IGF ) { <nl> - auto it = IGF . CurFn - > arg_begin ( ) ; <nl> - auto * enumAddr = & * ( it + + ) ; <nl> - auto * numEmptyCases = & * ( it + + ) ; <nl> - auto * metadata = & * ( it + + ) ; <nl> - auto & Builder = IGF . Builder ; <nl> - auto witnessFunc = emitLoadOfValueWitnessFunctionFromMetadata ( <nl> - IGF , metadata , ValueWitness : : GetEnumTagSinglePayload ) ; <nl> - auto * result = Builder . CreateCall ( witnessFunc , <nl> - { enumAddr , numEmptyCases , metadata } ) ; <nl> - Builder . CreateRet ( result ) ; <nl> - } , <nl> - true / * noinline * / ) ; <nl> - <nl> - / / This function is readonly . <nl> - cast < llvm : : Function > ( func ) - > addFnAttr ( llvm : : Attribute : : ReadOnly ) ; <nl> - return func ; <nl> - } <nl> - <nl> - / / / Emit a trampoline to call the storeEnumTagSinglePayload witness . API : <nl> - / / / VOID_TYPE ( const T * enum , INT_TYPE whichCase , UINT_TYPE emptyCases , <nl> - / / / M * self ) <nl> - static llvm : : Constant * <nl> - getStoreEnumTagSinglePayloadTrampolineFn ( IRGenModule & IGM ) { <nl> - <nl> - llvm : : Type * argTys [ ] = { IGM . OpaquePtrTy , IGM . Int32Ty , IGM . Int32Ty , <nl> - IGM . TypeMetadataPtrTy } ; <nl> - <nl> - llvm : : SmallString < 40 > fnName ( " __swift_storeEnumTagSinglePayload " ) ; <nl> - <nl> - return IGM . getOrCreateHelperFunction ( <nl> - fnName , IGM . VoidTy , argTys , <nl> - [ & ] ( IRGenFunction & IGF ) { <nl> - auto it = IGF . CurFn - > arg_begin ( ) ; <nl> - auto * enumAddr = & * ( it + + ) ; <nl> - auto * whichCase = & * ( it + + ) ; <nl> - auto * numEmptyCases = & * ( it + + ) ; <nl> - auto * metadata = & * ( it + + ) ; <nl> - auto & Builder = IGF . Builder ; <nl> - auto witnessFunc = emitLoadOfValueWitnessFunctionFromMetadata ( <nl> - IGF , metadata , ValueWitness : : StoreEnumTagSinglePayload ) ; <nl> - Builder . CreateCall ( witnessFunc , <nl> - { enumAddr , whichCase , numEmptyCases , metadata } ) ; <nl> - Builder . CreateRetVoid ( ) ; <nl> - } , <nl> - true / * noinline * / ) ; <nl> - } <nl> - <nl> - llvm : : Value * irgen : : emitGetEnumTagSinglePayloadCall ( IRGenFunction & IGF , <nl> - SILType T , <nl> - llvm : : Value * numEmptyCases , <nl> - Address destObject ) { <nl> - if ( ! IGF . IGM . getOptions ( ) . OptimizeForSize ) { <nl> - llvm : : Value * metadata ; <nl> - auto fn = IGF . emitValueWitnessFunctionRef ( <nl> - T , metadata , ValueWitness : : GetEnumTagSinglePayload ) ; <nl> - llvm : : CallInst * call = IGF . Builder . CreateCall ( <nl> - fn , { destObject . getAddress ( ) , numEmptyCases , metadata } ) ; <nl> - return call ; <nl> - } <nl> - auto * metadata = IGF . emitTypeMetadataRefForLayout ( T ) ; <nl> - auto * func = getGetEnumTagSinglePayloadTrampolineFn ( IGF . IGM ) ; <nl> - auto * result = IGF . Builder . CreateCall ( <nl> - func , <nl> - { IGF . Builder . CreateBitCast ( destObject . getAddress ( ) , IGF . IGM . OpaquePtrTy ) , <nl> - numEmptyCases , metadata } ) ; <nl> - return result ; <nl> - } <nl> - <nl> - llvm : : Value * irgen : : emitStoreEnumTagSinglePayloadCall ( <nl> - IRGenFunction & IGF , SILType T , llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , Address destObject ) { <nl> - if ( ! IGF . IGM . getOptions ( ) . OptimizeForSize ) { <nl> - llvm : : Value * metadata ; <nl> - auto fn = IGF . emitValueWitnessFunctionRef ( <nl> - T , metadata , ValueWitness : : StoreEnumTagSinglePayload ) ; <nl> - llvm : : CallInst * call = IGF . Builder . CreateCall ( <nl> - fn , { destObject . getAddress ( ) , whichCase , numEmptyCases , metadata } ) ; <nl> - return call ; <nl> - } <nl> - <nl> - auto * metadata = IGF . emitTypeMetadataRefForLayout ( T ) ; <nl> - auto * func = getStoreEnumTagSinglePayloadTrampolineFn ( IGF . IGM ) ; <nl> - auto * result = IGF . Builder . CreateCall ( <nl> - func , <nl> - { IGF . Builder . CreateBitCast ( destObject . getAddress ( ) , IGF . IGM . OpaquePtrTy ) , <nl> - whichCase , numEmptyCases , metadata } ) ; <nl> - return result ; <nl> - } <nl> - <nl> / / / Emit a call to the ' getEnumTag ' operation . <nl> llvm : : Value * irgen : : emitGetEnumTagCall ( IRGenFunction & IGF , <nl> SILType T , <nl> mmm a / lib / IRGen / GenOpaque . h <nl> ppp b / lib / IRGen / GenOpaque . h <nl> namespace irgen { <nl> llvm : : Value * index , <nl> Address destObject ) ; <nl> <nl> - / / / Emit a call to the ' getEnumTagSinglePayload ' operation . <nl> - llvm : : Value * emitGetEnumTagSinglePayloadCall ( IRGenFunction & IGF , SILType T , <nl> - llvm : : Value * numEmptyCases , <nl> - Address destObject ) ; <nl> - <nl> - / / / Emit a call to the ' storeEnumTagSinglePayload ' operation . <nl> - llvm : : Value * emitStoreEnumTagSinglePayloadCall ( IRGenFunction & IGF , SILType T , <nl> - llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , <nl> - Address destObject ) ; <nl> - <nl> / / / Emit a call to the ' getEnumTag ' operation . <nl> llvm : : Value * emitGetEnumTagCall ( IRGenFunction & IGF , <nl> SILType T , <nl> mmm a / lib / IRGen / GenType . cpp <nl> ppp b / lib / IRGen / GenType . cpp <nl> <nl> # include " WeakTypeInfo . h " <nl> # include " NativeConventionSchema . h " <nl> # include " IRGenMangler . h " <nl> - # include " NonFixedTypeInfo . h " <nl> <nl> using namespace swift ; <nl> using namespace irgen ; <nl> FixedTypeInfo : : getSpareBitExtraInhabitantIndex ( IRGenFunction & IGF , <nl> return phi ; <nl> } <nl> <nl> - static llvm : : Value * computeExtraTagBytes ( IRGenFunction & IGF , IRBuilder & Builder , <nl> - size_t fixedSize , <nl> - llvm : : Value * numEmptyCases ) { <nl> - / / We can use the payload area with a tag bit set somewhere outside of the <nl> - / / payload area to represent cases . See how many bytes we need to cover <nl> - / / all the empty cases . <nl> - <nl> - / / Algorithm : <nl> - / / unsigned numTags = 1 ; <nl> - / / if ( size > = 4 ) <nl> - / / / / Assume that one tag bit is enough if the precise calculation overflows <nl> - / / / / an int32 . <nl> - / / numTags + = 1 ; <nl> - / / else { <nl> - / / unsigned bits = size * 8U ; <nl> - / / unsigned casesPerTagBitValue = 1U < < bits ; <nl> - / / numTags + = ( ( emptyCases + ( casesPerTagBitValue - 1U ) ) > > bits ) ; <nl> - / / } <nl> - / / return ( numTags < 256 ? 1 : <nl> - / / numTags < 65536 ? 2 : 4 ) ; <nl> - <nl> - auto & IGM = IGF . IGM ; <nl> - auto & Ctx = Builder . getContext ( ) ; <nl> - auto * int32Ty = IGM . Int32Ty ; <nl> - <nl> - auto * one = llvm : : ConstantInt : : get ( int32Ty , 1U ) ; <nl> - if ( fixedSize > = 4 ) { <nl> - return one ; <nl> - } <nl> - <nl> - auto * entryBB = Builder . GetInsertBlock ( ) ; <nl> - llvm : : Value * size = asSizeConstant ( IGM , Size ( fixedSize ) ) ; <nl> - auto * returnBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - size = Builder . CreateTrunc ( size , int32Ty ) ; / / We know size < 4 . <nl> - <nl> - auto * two = llvm : : ConstantInt : : get ( int32Ty , 2U ) ; <nl> - auto * four = llvm : : ConstantInt : : get ( int32Ty , 4U ) ; <nl> - <nl> - auto * bits = Builder . CreateMul ( size , llvm : : ConstantInt : : get ( int32Ty , 8U ) ) ; <nl> - auto * casesPerTagBitValue = Builder . CreateShl ( one , bits ) ; <nl> - <nl> - auto * numTags = Builder . CreateSub ( casesPerTagBitValue , one ) ; <nl> - numTags = Builder . CreateAdd ( numTags , numEmptyCases ) ; <nl> - numTags = Builder . CreateLShr ( numTags , bits ) ; <nl> - numTags = Builder . CreateAdd ( numTags , one ) ; <nl> - <nl> - auto * notLT256BB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isLT256 = <nl> - Builder . CreateICmpULT ( numTags , llvm : : ConstantInt : : get ( int32Ty , 256U ) ) ; <nl> - Builder . CreateCondBr ( isLT256 , returnBB , notLT256BB ) ; <nl> - <nl> - Builder . emitBlock ( notLT256BB ) ; <nl> - auto * isLT65536 = <nl> - Builder . CreateICmpULT ( numTags , llvm : : ConstantInt : : get ( int32Ty , 65536U ) ) ; <nl> - numTags = Builder . CreateSelect ( isLT65536 , two , four ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - Builder . emitBlock ( returnBB ) ; <nl> - auto * phi = Builder . CreatePHI ( int32Ty , 3 ) ; <nl> - phi - > addIncoming ( one , entryBB ) ; <nl> - phi - > addIncoming ( numTags , notLT256BB ) ; <nl> - return phi ; <nl> - } <nl> - <nl> - llvm : : Value * FixedTypeInfo : : getEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const { <nl> - auto & IGM = IGF . IGM ; <nl> - auto & Ctx = IGF . IGM . getLLVMContext ( ) ; <nl> - auto & Builder = IGF . Builder ; <nl> - <nl> - auto * size = getSize ( IGF , T ) ; <nl> - auto fixedSize = getFixedSize ( ) . getValue ( ) ; <nl> - auto * numExtraInhabitants = <nl> - llvm : : ConstantInt : : get ( IGM . Int32Ty , getFixedExtraInhabitantCount ( IGM ) ) ; <nl> - <nl> - auto * zero = llvm : : ConstantInt : : get ( IGM . Int32Ty , 0U ) ; <nl> - auto * one = llvm : : ConstantInt : : get ( IGM . Int32Ty , 1U ) ; <nl> - auto * four = llvm : : ConstantInt : : get ( IGM . Int32Ty , 4U ) ; <nl> - auto * eight = llvm : : ConstantInt : : get ( IGM . Int32Ty , 8U ) ; <nl> - <nl> - auto * extraTagBitsBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * noExtraTagBitsBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * hasEmptyCasesBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * singleCaseEnumBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - <nl> - / / No empty cases so we must be the payload . <nl> - auto * hasNoEmptyCases = Builder . CreateICmpEQ ( zero , numEmptyCases ) ; <nl> - Builder . CreateCondBr ( hasNoEmptyCases , singleCaseEnumBB , hasEmptyCasesBB ) ; <nl> - <nl> - / / Otherwise , check whether we need extra tag bits . <nl> - Builder . emitBlock ( hasEmptyCasesBB ) ; <nl> - auto * hasExtraTagBits = <nl> - Builder . CreateICmpUGT ( numEmptyCases , numExtraInhabitants ) ; <nl> - Builder . CreateCondBr ( hasExtraTagBits , extraTagBitsBB , noExtraTagBitsBB ) ; <nl> - <nl> - / / There are extra tag bits to check . <nl> - Builder . emitBlock ( extraTagBitsBB ) ; <nl> - llvm : : Value * extraTagBits = Builder . CreateAlloca ( IGM . Int32Ty , nullptr ) ; <nl> - Builder . CreateStore ( zero , extraTagBits , Alignment ( 0 ) ) ; <nl> - <nl> - / / Compute the number of extra tag bytes . <nl> - auto * emptyCases = Builder . CreateSub ( numEmptyCases , numExtraInhabitants ) ; <nl> - auto * numExtraTagBytes = <nl> - computeExtraTagBytes ( IGF , Builder , fixedSize , emptyCases ) ; <nl> - <nl> - / / Read the extra tag bytes . <nl> - auto * valueAddr = <nl> - Builder . CreateBitOrPointerCast ( enumAddr . getAddress ( ) , IGM . Int8PtrTy ) ; <nl> - auto * extraTagBitsAddr = <nl> - Builder . CreateConstInBoundsGEP1_32 ( IGM . Int8Ty , valueAddr , fixedSize ) ; <nl> - <nl> - / / TODO : big endian . <nl> - Builder . CreateMemCpy ( <nl> - Builder . CreateBitOrPointerCast ( extraTagBits , IGM . Int8PtrTy ) , <nl> - extraTagBitsAddr , numExtraTagBytes , 1 ) ; <nl> - extraTagBits = Builder . CreateLoad ( extraTagBits , Alignment ( 0 ) ) ; <nl> - <nl> - extraTagBitsBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - Builder . CreateCondBr ( Builder . CreateICmpEQ ( extraTagBits , zero ) , <nl> - noExtraTagBitsBB , extraTagBitsBB ) ; <nl> - <nl> - auto * resultBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - <nl> - Builder . emitBlock ( extraTagBitsBB ) ; <nl> - <nl> - auto * truncSize = Builder . CreateTrunc ( size , IGM . Int32Ty ) ; <nl> - llvm : : Value * caseIndexFromValue = Builder . CreateAlloca ( IGM . Int32Ty , nullptr ) ; <nl> - Builder . CreateStore ( zero , caseIndexFromValue , Alignment ( 0 ) ) ; <nl> - <nl> - auto * caseIndexFromExtraTagBits = Builder . CreateSelect ( <nl> - Builder . CreateICmpUGE ( truncSize , four ) , zero , <nl> - Builder . CreateShl ( Builder . CreateSub ( extraTagBits , one ) , <nl> - Builder . CreateMul ( eight , truncSize ) ) ) ; <nl> - <nl> - / / TODO : big endian . <nl> - Builder . CreateMemCpy ( <nl> - Builder . CreateBitOrPointerCast ( caseIndexFromValue , IGM . Int8PtrTy ) , <nl> - valueAddr , std : : min ( Size ( 4U ) . getValue ( ) , fixedSize ) , 1 ) ; <nl> - caseIndexFromValue = Builder . CreateLoad ( caseIndexFromValue , Alignment ( 0 ) ) ; <nl> - <nl> - auto * result1 = Builder . CreateAdd ( <nl> - numExtraInhabitants , <nl> - Builder . CreateOr ( caseIndexFromValue , caseIndexFromExtraTagBits ) ) ; <nl> - Builder . CreateBr ( resultBB ) ; <nl> - <nl> - / / Extra tag bits were considered and zero or there are not extra tag <nl> - / / bits . <nl> - Builder . emitBlock ( noExtraTagBitsBB ) ; <nl> - / / If there are extra inhabitants , see whether the payload is valid . <nl> - llvm : : Value * result0 ; <nl> - if ( mayHaveExtraInhabitants ( IGM ) ) { <nl> - result0 = getExtraInhabitantIndex ( IGF , enumAddr , T ) ; <nl> - noExtraTagBitsBB = Builder . GetInsertBlock ( ) ; <nl> - } else { <nl> - result0 = llvm : : ConstantInt : : getSigned ( IGM . Int32Ty , - 1 ) ; <nl> - } <nl> - Builder . CreateBr ( resultBB ) ; <nl> - <nl> - Builder . emitBlock ( singleCaseEnumBB ) ; <nl> - / / Otherwise , we have a valid payload . <nl> - auto * result2 = llvm : : ConstantInt : : getSigned ( IGM . Int32Ty , - 1 ) ; <nl> - Builder . CreateBr ( resultBB ) ; <nl> - <nl> - Builder . emitBlock ( resultBB ) ; <nl> - auto * result = Builder . CreatePHI ( IGM . Int32Ty , 3 ) ; <nl> - result - > addIncoming ( result0 , noExtraTagBitsBB ) ; <nl> - result - > addIncoming ( result1 , extraTagBitsBB ) ; <nl> - result - > addIncoming ( result2 , singleCaseEnumBB ) ; <nl> - return result ; <nl> - } <nl> - <nl> - / / / Emit a speciaize memory operation for a \ p size of 0 to 4 bytes . <nl> - static void emitSpecializedMemOperation ( <nl> - IRGenFunction & IGF , <nl> - llvm : : function_ref < void ( IRBuilder & , uint64_t ) > emitMemOpFn , <nl> - llvm : : Value * size ) { <nl> - auto & IGM = IGF . IGM ; <nl> - auto & Ctx = IGF . IGM . getLLVMContext ( ) ; <nl> - auto & Builder = IGF . Builder ; <nl> - auto * returnBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * oneBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * twoBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * fourBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * int32Ty = IGM . Int32Ty ; <nl> - auto * zero = llvm : : ConstantInt : : get ( int32Ty , 0U ) ; <nl> - auto * one = llvm : : ConstantInt : : get ( int32Ty , 1U ) ; <nl> - auto * two = llvm : : ConstantInt : : get ( int32Ty , 2U ) ; <nl> - <nl> - auto * continueBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isZero = Builder . CreateICmpEQ ( size , zero ) ; <nl> - Builder . CreateCondBr ( isZero , returnBB , continueBB ) ; <nl> - <nl> - Builder . emitBlock ( continueBB ) ; <nl> - continueBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isOne = Builder . CreateICmpEQ ( size , one ) ; <nl> - Builder . CreateCondBr ( isOne , oneBB , continueBB ) ; <nl> - <nl> - Builder . emitBlock ( continueBB ) ; <nl> - auto * isTwo = Builder . CreateICmpEQ ( size , two ) ; <nl> - Builder . CreateCondBr ( isTwo , twoBB , fourBB ) ; <nl> - <nl> - Builder . emitBlock ( oneBB ) ; <nl> - emitMemOpFn ( Builder , 1 ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - Builder . emitBlock ( twoBB ) ; <nl> - emitMemOpFn ( Builder , 2 ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - Builder . emitBlock ( fourBB ) ; <nl> - emitMemOpFn ( Builder , 4 ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - Builder . emitBlock ( returnBB ) ; <nl> - } <nl> - <nl> - / / / Emit a memset of zero operation for a \ p size of 0 to 4 bytes . <nl> - static void emitMemZero ( IRGenFunction & IGF , llvm : : Value * addr , <nl> - llvm : : Value * size ) { <nl> - auto * zeroByte = llvm : : ConstantInt : : get ( IGF . IGM . Int8Ty , 0U ) ; <nl> - emitSpecializedMemOperation ( IGF , <nl> - [ = ] ( IRBuilder & B , uint64_t numBytes ) { <nl> - B . CreateMemSet ( addr , zeroByte , numBytes , 1 ) ; <nl> - } , <nl> - size ) ; <nl> - } <nl> - <nl> - / / / Emit a memcpy operation for a \ p size of 0 to 4 bytes . <nl> - static void emitMemCpy ( IRGenFunction & IGF , llvm : : Value * to , llvm : : Value * from , <nl> - llvm : : Value * size ) { <nl> - emitSpecializedMemOperation ( IGF , <nl> - [ = ] ( IRBuilder & B , uint64_t numBytes ) { <nl> - B . CreateMemCpy ( to , from , numBytes , 1 ) ; <nl> - } , <nl> - size ) ; <nl> - } <nl> - <nl> - void FixedTypeInfo : : storeEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const { <nl> - auto & IGM = IGF . IGM ; <nl> - auto & Ctx = IGF . IGM . getLLVMContext ( ) ; <nl> - auto & Builder = IGF . Builder ; <nl> - auto & int32Ty = IGM . Int32Ty ; <nl> - <nl> - auto * zero = llvm : : ConstantInt : : get ( int32Ty , 0U ) ; <nl> - auto * one = llvm : : ConstantInt : : get ( int32Ty , 1U ) ; <nl> - auto * four = llvm : : ConstantInt : : get ( int32Ty , 4U ) ; <nl> - auto * eight = llvm : : ConstantInt : : get ( int32Ty , 8U ) ; <nl> - <nl> - auto fixedSize = getFixedSize ( ) . getValue ( ) ; <nl> - <nl> - auto * valueAddr = <nl> - Builder . CreateBitOrPointerCast ( enumAddr . getAddress ( ) , IGM . Int8PtrTy ) ; <nl> - auto * extraTagBitsAddr = <nl> - Builder . CreateConstInBoundsGEP1_32 ( IGM . Int8Ty , valueAddr , fixedSize ) ; <nl> - <nl> - auto * numExtraInhabitants = <nl> - llvm : : ConstantInt : : get ( IGM . Int32Ty , getFixedExtraInhabitantCount ( IGM ) ) ; <nl> - auto * size = getSize ( IGF , T ) ; <nl> - <nl> - / / Do we need extra tag bytes . <nl> - auto * entryBB = Builder . GetInsertBlock ( ) ; <nl> - auto * continueBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * computeExtraTagBytesBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * hasExtraTagBits = <nl> - Builder . CreateICmpUGT ( numEmptyCases , numExtraInhabitants ) ; <nl> - Builder . CreateCondBr ( hasExtraTagBits , computeExtraTagBytesBB , continueBB ) ; <nl> - <nl> - Builder . emitBlock ( computeExtraTagBytesBB ) ; <nl> - / / Compute the number of extra tag bytes . <nl> - auto * emptyCases = Builder . CreateSub ( numEmptyCases , numExtraInhabitants ) ; <nl> - auto * numExtraTagBytes0 = <nl> - computeExtraTagBytes ( IGF , Builder , fixedSize , emptyCases ) ; <nl> - computeExtraTagBytesBB = Builder . GetInsertBlock ( ) ; <nl> - Builder . CreateBr ( continueBB ) ; <nl> - <nl> - Builder . emitBlock ( continueBB ) ; <nl> - auto * numExtraTagBytes = Builder . CreatePHI ( int32Ty , 2 ) ; <nl> - numExtraTagBytes - > addIncoming ( zero , entryBB ) ; <nl> - numExtraTagBytes - > addIncoming ( numExtraTagBytes0 , computeExtraTagBytesBB ) ; <nl> - <nl> - / / Check whether we need to set the extra tag bits to non zero . <nl> - auto * isExtraTagBitsCaseBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isPayloadOrInhabitantCaseBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isPayloadOrExtraInhabitant = <nl> - Builder . CreateICmpSLT ( whichCase , numExtraInhabitants ) ; <nl> - Builder . CreateCondBr ( isPayloadOrExtraInhabitant , isPayloadOrInhabitantCaseBB , <nl> - isExtraTagBitsCaseBB ) ; <nl> - <nl> - / / We are the payload or fit within the extra inhabitants . <nl> - Builder . emitBlock ( isPayloadOrInhabitantCaseBB ) ; <nl> - / / Zero the tag bits . <nl> - emitMemZero ( IGF , extraTagBitsAddr , numExtraTagBytes ) ; <nl> - isPayloadOrInhabitantCaseBB = Builder . GetInsertBlock ( ) ; <nl> - auto * storeInhabitantBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * returnBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - auto * isPayload = Builder . CreateICmpEQ ( <nl> - whichCase , llvm : : ConstantInt : : getSigned ( int32Ty , - 1 ) ) ; <nl> - Builder . CreateCondBr ( isPayload , returnBB , storeInhabitantBB ) ; <nl> - <nl> - Builder . emitBlock ( storeInhabitantBB ) ; <nl> - if ( mayHaveExtraInhabitants ( IGM ) ) <nl> - storeExtraInhabitant ( IGF , whichCase , enumAddr , T ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - / / There are extra tag bits to consider . <nl> - Builder . emitBlock ( isExtraTagBitsCaseBB ) ; <nl> - <nl> - / / Write the extra tag bytes . <nl> - auto * caseIndex = Builder . CreateSub ( whichCase , numExtraInhabitants ) ; <nl> - auto * truncSize = Builder . CreateTrunc ( size , IGM . Int32Ty ) ; <nl> - auto * isFourBytesPayload = Builder . CreateICmpUGE ( truncSize , four ) ; <nl> - auto * payloadGE4BB = Builder . GetInsertBlock ( ) ; <nl> - auto * payloadLT4BB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - continueBB = llvm : : BasicBlock : : Create ( Ctx ) ; <nl> - Builder . CreateCondBr ( isFourBytesPayload , continueBB , payloadLT4BB ) ; <nl> - <nl> - Builder . emitBlock ( payloadLT4BB ) ; <nl> - auto * payloadBits = Builder . CreateMul ( truncSize , eight ) ; <nl> - auto * extraTagIndex0 = Builder . CreateLShr ( caseIndex , payloadBits ) ; <nl> - extraTagIndex0 = Builder . CreateAdd ( one , extraTagIndex0 ) ; <nl> - auto * payloadIndex0 = Builder . CreateShl ( one , payloadBits ) ; <nl> - payloadIndex0 = Builder . CreateSub ( payloadIndex0 , one ) ; <nl> - payloadIndex0 = Builder . CreateAnd ( payloadIndex0 , caseIndex ) ; <nl> - Builder . CreateBr ( continueBB ) ; <nl> - <nl> - Builder . emitBlock ( continueBB ) ; <nl> - auto * extraTagIndex = Builder . CreatePHI ( int32Ty , 2 ) ; <nl> - extraTagIndex - > addIncoming ( llvm : : ConstantInt : : get ( int32Ty , 1 ) , payloadGE4BB ) ; <nl> - extraTagIndex - > addIncoming ( extraTagIndex0 , payloadLT4BB ) ; <nl> - <nl> - auto * payloadIndex = Builder . CreatePHI ( int32Ty , 2 ) ; <nl> - payloadIndex - > addIncoming ( caseIndex , payloadGE4BB ) ; <nl> - payloadIndex - > addIncoming ( payloadIndex0 , payloadLT4BB ) ; <nl> - <nl> - auto * payloadIndexAddr = Builder . CreateAlloca ( int32Ty , nullptr ) ; <nl> - Builder . CreateStore ( payloadIndex , payloadIndexAddr , Alignment ( 0 ) ) ; <nl> - auto * extraTagIndexAddr = Builder . CreateAlloca ( int32Ty , nullptr ) ; <nl> - Builder . CreateStore ( extraTagIndex , extraTagIndexAddr , Alignment ( 0 ) ) ; <nl> - / / TODO : big endian <nl> - Builder . CreateMemCpy ( <nl> - valueAddr , <nl> - Builder . CreateBitOrPointerCast ( payloadIndexAddr , IGM . Int8PtrTy ) , <nl> - std : : min ( Size ( 4U ) . getValue ( ) , fixedSize ) , 1 ) ; <nl> - emitMemCpy ( IGF , extraTagBitsAddr , extraTagIndexAddr , numExtraTagBytes ) ; <nl> - Builder . CreateBr ( returnBB ) ; <nl> - <nl> - Builder . emitBlock ( returnBB ) ; <nl> - } <nl> - <nl> - llvm : : Value * irgen : : emitGetEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , SILType T ) { <nl> - auto metadata = IGF . emitTypeMetadataRefForLayout ( T ) ; <nl> - auto opaqueAddr = <nl> - IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , IGF . IGM . OpaquePtrTy ) ; <nl> - <nl> - return IGF . Builder . CreateCall ( IGF . IGM . getGetEnumCaseSinglePayloadFn ( ) , <nl> - { opaqueAddr , metadata , numEmptyCases } ) ; <nl> - } <nl> - <nl> - void irgen : : emitStoreEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) { <nl> - auto metadata = IGF . emitTypeMetadataRefForLayout ( T ) ; <nl> - auto opaqueAddr = <nl> - IGF . Builder . CreateBitCast ( enumAddr . getAddress ( ) , IGF . IGM . OpaquePtrTy ) ; <nl> - <nl> - IGF . Builder . CreateCall ( IGF . IGM . getStoreEnumTagSinglePayloadFn ( ) , <nl> - { opaqueAddr , metadata , whichCase , numEmptyCases } ) ; <nl> - } <nl> - <nl> void <nl> FixedTypeInfo : : storeSpareBitExtraInhabitant ( IRGenFunction & IGF , <nl> llvm : : Value * index , <nl> mmm a / lib / IRGen / GenValueWitness . cpp <nl> ppp b / lib / IRGen / GenValueWitness . cpp <nl> const char * irgen : : getValueWitnessName ( ValueWitness witness ) { <nl> CASE ( Flags ) <nl> CASE ( Stride ) <nl> CASE ( ExtraInhabitantFlags ) <nl> - CASE ( GetEnumTagSinglePayload ) <nl> - CASE ( StoreEnumTagSinglePayload ) <nl> # undef CASE <nl> } <nl> llvm_unreachable ( " bad value witness kind " ) ; <nl> static void buildValueWitnessFunction ( IRGenModule & IGM , <nl> return ; <nl> } <nl> <nl> - case ValueWitness : : GetEnumTagSinglePayload : { <nl> - llvm : : Value * value = getArg ( argv , " value " ) ; <nl> - auto enumTy = type . getStorageType ( ) - > getPointerTo ( ) ; <nl> - value = IGF . Builder . CreateBitCast ( value , enumTy ) ; <nl> - <nl> - llvm : : Value * numEmptyCases = getArg ( argv , " numEmptyCases " ) ; <nl> - <nl> - getArgAsLocalSelfTypeMetadata ( IGF , argv , abstractType ) ; <nl> - <nl> - llvm : : Value * idx = type . getEnumTagSinglePayload ( <nl> - IGF , numEmptyCases , Address ( value , type . getBestKnownAlignment ( ) ) , <nl> - concreteType ) ; <nl> - IGF . Builder . CreateRet ( idx ) ; <nl> - return ; <nl> - } <nl> - <nl> - case ValueWitness : : StoreEnumTagSinglePayload : { <nl> - llvm : : Value * value = getArg ( argv , " value " ) ; <nl> - auto enumTy = type . getStorageType ( ) - > getPointerTo ( ) ; <nl> - value = IGF . Builder . CreateBitCast ( value , enumTy ) ; <nl> - <nl> - llvm : : Value * whichCase = getArg ( argv , " whichCase " ) ; <nl> - llvm : : Value * numEmptyCases = getArg ( argv , " numEmptyCases " ) ; <nl> - <nl> - getArgAsLocalSelfTypeMetadata ( IGF , argv , abstractType ) ; <nl> - <nl> - type . storeEnumTagSinglePayload ( IGF , whichCase , numEmptyCases , <nl> - Address ( value , type . getBestKnownAlignment ( ) ) , <nl> - concreteType ) ; <nl> - IGF . Builder . CreateRetVoid ( ) ; <nl> - return ; <nl> - } <nl> - <nl> case ValueWitness : : Size : <nl> case ValueWitness : : Flags : <nl> case ValueWitness : : Stride : <nl> static void addValueWitness ( IRGenModule & IGM , <nl> return B . add ( llvm : : ConstantPointerNull : : get ( IGM . Int8PtrTy ) ) ; <nl> } <nl> <nl> - case ValueWitness : : GetEnumTagSinglePayload : <nl> - case ValueWitness : : StoreEnumTagSinglePayload : { <nl> - goto standard ; <nl> - } <nl> - <nl> case ValueWitness : : GetEnumTag : <nl> case ValueWitness : : DestructiveProjectEnumData : <nl> case ValueWitness : : DestructiveInjectEnumTag : <nl> mmm a / lib / IRGen / IRGenMangler . cpp <nl> ppp b / lib / IRGen / IRGenMangler . cpp <nl> std : : string IRGenMangler : : mangleValueWitness ( Type type , ValueWitness witness ) { <nl> GET_MANGLING ( InitializeWithTake ) \ <nl> GET_MANGLING ( AssignWithTake ) \ <nl> GET_MANGLING ( InitializeBufferWithTakeOfBuffer ) \ <nl> - GET_MANGLING ( GetEnumTagSinglePayload ) \ <nl> - GET_MANGLING ( StoreEnumTagSinglePayload ) \ <nl> GET_MANGLING ( StoreExtraInhabitant ) \ <nl> GET_MANGLING ( GetExtraInhabitantIndex ) \ <nl> GET_MANGLING ( GetEnumTag ) \ <nl> mmm a / lib / IRGen / NonFixedTypeInfo . h <nl> ppp b / lib / IRGen / NonFixedTypeInfo . h <nl> <nl> namespace swift { <nl> namespace irgen { <nl> <nl> - / / / Emits the generic implementation for getEnumTagSinglePayload . <nl> - llvm : : Value * emitGetEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , SILType T ) ; <nl> - <nl> - / / / Emits the generic implementation for storeEnumTagSinglePayload . <nl> - void emitStoreEnumTagSinglePayload ( IRGenFunction & IGF , llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , Address enumAddr , <nl> - SILType T ) ; <nl> - <nl> / / / An abstract CRTP class designed for types whose storage size , <nl> / / / alignment , and stride need to be fetched from the value witness <nl> / / / table for the type . <nl> class WitnessSizedTypeInfo : public IndirectTypeInfo < Impl , TypeInfo > { <nl> llvm : : Constant * getStaticStride ( IRGenModule & IGM ) const override { <nl> return nullptr ; <nl> } <nl> - <nl> - llvm : : Value * getEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const override { <nl> - return emitGetEnumTagSinglePayload ( IGF , numEmptyCases , enumAddr , T ) ; <nl> - } <nl> - <nl> - void storeEnumTagSinglePayload ( IRGenFunction & IGF , llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , Address enumAddr , <nl> - SILType T ) const override { <nl> - emitStoreEnumTagSinglePayload ( IGF , whichCase , numEmptyCases , enumAddr , T ) ; <nl> - } <nl> } ; <nl> + <nl> } <nl> } <nl> <nl> mmm a / lib / IRGen / ResilientTypeInfo . h <nl> ppp b / lib / IRGen / ResilientTypeInfo . h <nl> class ResilientTypeInfo : public WitnessSizedTypeInfo < Impl > { <nl> llvm_unreachable ( " initializing value witness table for opaque type ? ! " ) ; <nl> } <nl> <nl> - llvm : : Value * getEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const override { <nl> - return emitGetEnumTagSinglePayloadCall ( IGF , T , numEmptyCases , enumAddr ) ; <nl> - } <nl> - <nl> - void storeEnumTagSinglePayload ( IRGenFunction & IGF , llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , Address enumAddr , <nl> - SILType T ) const override { <nl> - emitStoreEnumTagSinglePayloadCall ( IGF , T , whichCase , numEmptyCases , enumAddr ) ; <nl> - } <nl> - <nl> } ; <nl> <nl> } <nl> mmm a / lib / IRGen / TypeInfo . h <nl> ppp b / lib / IRGen / TypeInfo . h <nl> class TypeInfo { <nl> llvm : : Value * metadata , <nl> llvm : : Value * vwtable , <nl> SILType T ) const = 0 ; <nl> - <nl> - / / / Get the tag of a single payload enum with a payload of this type ( \ p T ) e . g <nl> - / / / Optional < T > . <nl> - virtual llvm : : Value * getEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const = 0 ; <nl> - <nl> - / / / Store the tag of a single payload enum with a payload of this type . <nl> - virtual void storeEnumTagSinglePayload ( IRGenFunction & IGF , <nl> - llvm : : Value * whichCase , <nl> - llvm : : Value * numEmptyCases , <nl> - Address enumAddr , <nl> - SILType T ) const = 0 ; <nl> <nl> / / / Compute the packing of values of this type into a fixed - size buffer . <nl> FixedPacking getFixedPacking ( IRGenModule & IGM ) const ; <nl> mmm a / stdlib / public / runtime / Enum . cpp <nl> ppp b / stdlib / public / runtime / Enum . cpp <nl> <nl> # include " swift / Runtime / Enum . h " <nl> # include " swift / Runtime / Debug . h " <nl> # include " Private . h " <nl> - # include " EnumImpl . h " <nl> # include < cstring > <nl> # include < algorithm > <nl> <nl> using namespace swift ; <nl> <nl> + static unsigned getNumTagBytes ( size_t size , unsigned emptyCases , <nl> + unsigned payloadCases ) { <nl> + / / We can use the payload area with a tag bit set somewhere outside of the <nl> + / / payload area to represent cases . See how many bytes we need to cover <nl> + / / all the empty cases . <nl> + <nl> + unsigned numTags = payloadCases ; <nl> + if ( emptyCases > 0 ) { <nl> + if ( size > = 4 ) <nl> + / / Assume that one tag bit is enough if the precise calculation overflows <nl> + / / an int32 . <nl> + numTags + = 1 ; <nl> + else { <nl> + unsigned bits = size * 8U ; <nl> + unsigned casesPerTagBitValue = 1U < < bits ; <nl> + numTags + = ( ( emptyCases + ( casesPerTagBitValue - 1U ) ) > > bits ) ; <nl> + } <nl> + } <nl> + return ( numTags < = 1 ? 0 : <nl> + numTags < 256 ? 1 : <nl> + numTags < 65536 ? 2 : 4 ) ; <nl> + } <nl> + <nl> + / / / This is a small and fast implementation of memcpy with a constant count . It <nl> + / / / should be a performance win for small constant values where the function <nl> + / / / can be inlined , the loop unrolled and the memory accesses merged . <nl> + template < unsigned count > static void small_memcpy ( void * dest , const void * src ) { <nl> + uint8_t * d8 = ( uint8_t * ) dest ; <nl> + const uint8_t * s8 = ( const uint8_t * ) src ; <nl> + for ( unsigned i = 0 ; i < count ; i + + ) { <nl> + * d8 + + = * s8 + + ; <nl> + } <nl> + } <nl> + <nl> + static inline void small_memcpy ( void * dest , const void * src , unsigned count ) { <nl> + / / This is specialization of the memcpy line below with <nl> + / / specialization for values of 1 , 2 and 4 . <nl> + / / memcpy ( dst , src , count ) <nl> + if ( count = = 1 ) { <nl> + small_memcpy < 1 > ( dest , src ) ; <nl> + } else if ( count = = 2 ) { <nl> + small_memcpy < 2 > ( dest , src ) ; <nl> + } else if ( count = = 4 ) { <nl> + small_memcpy < 4 > ( dest , src ) ; <nl> + } else { <nl> + crash ( " Tagbyte values should be 1 , 2 or 4 . " ) ; <nl> + } <nl> + } <nl> + <nl> void <nl> swift : : swift_initEnumValueWitnessTableSinglePayload ( ValueWitnessTable * vwtable , <nl> const TypeLayout * payloadLayout , <nl> int swift : : swift_getEnumCaseSinglePayload ( const OpaqueValue * value , <nl> const Metadata * payload , <nl> unsigned emptyCases ) <nl> SWIFT_CC ( RegisterPreservingCC_IMPL ) { <nl> - <nl> auto * payloadWitnesses = payload - > getValueWitnesses ( ) ; <nl> - auto size = payloadWitnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = payloadWitnesses - > getNumExtraInhabitants ( ) ; <nl> - auto getExtraInhabitantIndex = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( payloadWitnesses ) <nl> - - > getExtraInhabitantIndex ) ; <nl> - <nl> - return getEnumTagSinglePayloadImpl ( value , emptyCases , payload , size , <nl> - numExtraInhabitants , <nl> - getExtraInhabitantIndex ) ; <nl> + auto payloadSize = payloadWitnesses - > getSize ( ) ; <nl> + auto payloadNumExtraInhabitants = payloadWitnesses - > getNumExtraInhabitants ( ) ; <nl> + <nl> + / / If there are extra tag bits , check them . <nl> + if ( emptyCases > payloadNumExtraInhabitants ) { <nl> + auto * valueAddr = reinterpret_cast < const uint8_t * > ( value ) ; <nl> + auto * extraTagBitAddr = valueAddr + payloadSize ; <nl> + unsigned extraTagBits = 0 ; <nl> + unsigned numBytes = getNumTagBytes ( payloadSize , <nl> + emptyCases - payloadNumExtraInhabitants , <nl> + 1 / * payload case * / ) ; <nl> + <nl> + # if defined ( __BIG_ENDIAN__ ) <nl> + small_memcpy ( reinterpret_cast < uint8_t * > ( & extraTagBits ) + 4 - numBytes , <nl> + extraTagBitAddr , numBytes ) ; <nl> + # else <nl> + small_memcpy ( & extraTagBits , extraTagBitAddr , numBytes ) ; <nl> + # endif <nl> + <nl> + / / If the extra tag bits are zero , we have a valid payload or <nl> + / / extra inhabitant ( checked below ) . If nonzero , form the case index from <nl> + / / the extra tag value and the value stored in the payload . <nl> + if ( extraTagBits > 0 ) { <nl> + unsigned caseIndexFromExtraTagBits = payloadSize > = 4 <nl> + ? 0 : ( extraTagBits - 1U ) < < ( payloadSize * 8U ) ; <nl> + <nl> + / / In practice we should need no more than four bytes from the payload <nl> + / / area . <nl> + unsigned caseIndexFromValue = 0 ; <nl> + # if defined ( __BIG_ENDIAN__ ) <nl> + unsigned numPayloadTagBytes = std : : min ( size_t ( 4 ) , payloadSize ) ; <nl> + memcpy ( reinterpret_cast < uint8_t * > ( & caseIndexFromValue ) + 4 - <nl> + numPayloadTagBytes , valueAddr , numPayloadTagBytes ) ; <nl> + # else <nl> + memcpy ( & caseIndexFromValue , valueAddr , <nl> + std : : min ( size_t ( 4 ) , payloadSize ) ) ; <nl> + # endif <nl> + return ( caseIndexFromExtraTagBits | caseIndexFromValue ) <nl> + + payloadNumExtraInhabitants ; <nl> + } <nl> + } <nl> + <nl> + / / If there are extra inhabitants , see whether the payload is valid . <nl> + if ( payloadNumExtraInhabitants > 0 ) { <nl> + return <nl> + static_cast < const ExtraInhabitantsValueWitnessTable * > ( payloadWitnesses ) <nl> + - > getExtraInhabitantIndex ( value , payload ) ; <nl> + } <nl> + <nl> + / / Otherwise , we have always have a valid payload . <nl> + return - 1 ; <nl> } <nl> <nl> void swift : : swift_storeEnumTagSinglePayload ( OpaqueValue * value , <nl> const Metadata * payload , <nl> int whichCase , unsigned emptyCases ) <nl> SWIFT_CC ( RegisterPreservingCC_IMPL ) { <nl> - <nl> auto * payloadWitnesses = payload - > getValueWitnesses ( ) ; <nl> - auto size = payloadWitnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = payloadWitnesses - > getNumExtraInhabitants ( ) ; <nl> - auto storeExtraInhabitant = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( payloadWitnesses ) <nl> - - > storeExtraInhabitant ) ; <nl> - <nl> - storeEnumTagSinglePayloadImpl ( value , whichCase , emptyCases , payload , size , <nl> - numExtraInhabitants , storeExtraInhabitant ) ; <nl> + auto payloadSize = payloadWitnesses - > getSize ( ) ; <nl> + unsigned payloadNumExtraInhabitants <nl> + = payloadWitnesses - > getNumExtraInhabitants ( ) ; <nl> + <nl> + auto * valueAddr = reinterpret_cast < uint8_t * > ( value ) ; <nl> + auto * extraTagBitAddr = valueAddr + payloadSize ; <nl> + unsigned numExtraTagBytes = emptyCases > payloadNumExtraInhabitants <nl> + ? getNumTagBytes ( payloadSize , emptyCases - payloadNumExtraInhabitants , <nl> + 1 / * payload case * / ) <nl> + : 0 ; <nl> + <nl> + / / For payload or extra inhabitant cases , zero - initialize the extra tag bits , <nl> + / / if any . <nl> + if ( whichCase < ( int ) payloadNumExtraInhabitants ) { <nl> + / / The two most common values for numExtraTagBytes are zero and one . <nl> + / / Try to avoid calling bzero by specializing for these values . <nl> + if ( numExtraTagBytes ! = 0 ) { <nl> + if ( numExtraTagBytes = = 1 ) { <nl> + / / Zero a single byte . <nl> + * ( ( char * ) ( extraTagBitAddr ) ) = 0 ; <nl> + } else { <nl> + / / Zero the buffer . <nl> + memset ( extraTagBitAddr , 0 , numExtraTagBytes ) ; <nl> + } <nl> + } <nl> + <nl> + / / If this is the payload case , we ' re done . <nl> + if ( whichCase = = - 1 ) <nl> + return ; <nl> + <nl> + / / Store the extra inhabitant . <nl> + static_cast < const ExtraInhabitantsValueWitnessTable * > ( payloadWitnesses ) <nl> + - > storeExtraInhabitant ( value , whichCase , payload ) ; <nl> + return ; <nl> + } <nl> + <nl> + / / Factor the case index into payload and extra tag parts . <nl> + unsigned caseIndex = whichCase - payloadNumExtraInhabitants ; <nl> + unsigned payloadIndex , extraTagIndex ; <nl> + if ( payloadSize > = 4 ) { <nl> + extraTagIndex = 1 ; <nl> + payloadIndex = caseIndex ; <nl> + } else { <nl> + unsigned payloadBits = payloadSize * 8U ; <nl> + extraTagIndex = 1U + ( caseIndex > > payloadBits ) ; <nl> + payloadIndex = caseIndex & ( ( 1U < < payloadBits ) - 1U ) ; <nl> + } <nl> + <nl> + / / Store into the value . <nl> + # if defined ( __BIG_ENDIAN__ ) <nl> + unsigned numPayloadTagBytes = std : : min ( size_t ( 4 ) , payloadSize ) ; <nl> + memcpy ( valueAddr , <nl> + reinterpret_cast < uint8_t * > ( & payloadIndex ) + 4 - numPayloadTagBytes , <nl> + numPayloadTagBytes ) ; <nl> + if ( payloadSize > 4 ) <nl> + memset ( valueAddr + 4 , 0 , payloadSize - 4 ) ; <nl> + memcpy ( extraTagBitAddr , <nl> + reinterpret_cast < uint8_t * > ( & extraTagIndex ) + 4 - numExtraTagBytes , <nl> + numExtraTagBytes ) ; <nl> + # else <nl> + memcpy ( valueAddr , & payloadIndex , std : : min ( size_t ( 4 ) , payloadSize ) ) ; <nl> + if ( payloadSize > 4 ) <nl> + memset ( valueAddr + 4 , 0 , payloadSize - 4 ) ; <nl> + memcpy ( extraTagBitAddr , & extraTagIndex , numExtraTagBytes ) ; <nl> + # endif <nl> } <nl> <nl> void <nl> deleted file mode 100644 <nl> index bbc6bbec0c03 . . 000000000000 <nl> mmm a / stdlib / public / runtime / EnumImpl . h <nl> ppp / dev / null <nl> <nl> - / / = = = mmm EnumImpl . h - Enum implementation runtime declarations - - * - C + + - * - = = = / / <nl> - / / <nl> - / / This source file is part of the Swift . org open source project <nl> - / / <nl> - / / Copyright ( c ) 2014 - 2017 Apple Inc . and the Swift project authors <nl> - / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> - / / <nl> - / / See https : / / swift . org / LICENSE . txt for license information <nl> - / / See https : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> - / / <nl> - / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> - / / <nl> - / / Enum implementation details declarations of the Swift runtime . <nl> - / / <nl> - / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> - # ifndef SWIFT_RUNTIME_ENUMIMPL_H <nl> - # define SWIFT_RUNTIME_ENUMIMPL_H <nl> - <nl> - namespace swift { <nl> - <nl> - / / / This is a small and fast implementation of memcpy with a constant count . It <nl> - / / / should be a performance win for small constant values where the function <nl> - / / / can be inlined , the loop unrolled and the memory accesses merged . <nl> - template < unsigned count > static void small_memcpy ( void * dest , const void * src ) { <nl> - uint8_t * d8 = ( uint8_t * ) dest ; <nl> - const uint8_t * s8 = ( const uint8_t * ) src ; <nl> - for ( unsigned i = 0 ; i < count ; i + + ) { <nl> - * d8 + + = * s8 + + ; <nl> - } <nl> - } <nl> - <nl> - static inline void small_memcpy ( void * dest , const void * src , unsigned count , <nl> - bool countMaybeThree = false ) { <nl> - / / This is specialization of the memcpy line below with <nl> - / / specialization for values of 1 , 2 and 4 . <nl> - / / memcpy ( dst , src , count ) <nl> - if ( count = = 1 ) { <nl> - small_memcpy < 1 > ( dest , src ) ; <nl> - } else if ( count = = 2 ) { <nl> - small_memcpy < 2 > ( dest , src ) ; <nl> - } else if ( countMaybeThree & & count = = 3 ) { <nl> - small_memcpy < 3 > ( dest , src ) ; <nl> - } else if ( count = = 4 ) { <nl> - small_memcpy < 4 > ( dest , src ) ; <nl> - } else { <nl> - swift : : crash ( " Tagbyte values should be 1 , 2 or 4 . " ) ; <nl> - } <nl> - } <nl> - <nl> - static inline void small_memset ( void * dest , uint8_t value , unsigned count ) { <nl> - if ( count = = 1 ) { <nl> - memset ( dest , value , 1 ) ; <nl> - } else if ( count = = 2 ) { <nl> - memset ( dest , value , 2 ) ; <nl> - } else if ( count = = 4 ) { <nl> - memset ( dest , value , 4 ) ; <nl> - } else { <nl> - swift : : crash ( " Tagbyte values should be 1 , 2 or 4 . " ) ; <nl> - } <nl> - } <nl> - <nl> - inline unsigned getNumTagBytes ( size_t size , unsigned emptyCases , <nl> - unsigned payloadCases ) { <nl> - / / We can use the payload area with a tag bit set somewhere outside of the <nl> - / / payload area to represent cases . See how many bytes we need to cover <nl> - / / all the empty cases . <nl> - <nl> - unsigned numTags = payloadCases ; <nl> - if ( emptyCases > 0 ) { <nl> - if ( size > = 4 ) <nl> - / / Assume that one tag bit is enough if the precise calculation overflows <nl> - / / an int32 . <nl> - numTags + = 1 ; <nl> - else { <nl> - unsigned bits = size * 8U ; <nl> - unsigned casesPerTagBitValue = 1U < < bits ; <nl> - numTags + = ( ( emptyCases + ( casesPerTagBitValue - 1U ) ) > > bits ) ; <nl> - } <nl> - } <nl> - return ( numTags < = 1 ? 0 : <nl> - numTags < 256 ? 1 : <nl> - numTags < 65536 ? 2 : 4 ) ; <nl> - } <nl> - <nl> - inline int getEnumTagSinglePayloadImpl ( <nl> - const OpaqueValue * enumAddr , unsigned emptyCases , const Metadata * payload , <nl> - size_t payloadSize , size_t payloadNumExtraInhabitants , <nl> - int ( * getExtraInhabitantIndex ) ( const OpaqueValue * , const Metadata * ) ) { <nl> - <nl> - / / If there are extra tag bits , check them . <nl> - if ( emptyCases > payloadNumExtraInhabitants ) { <nl> - auto * valueAddr = reinterpret_cast < const uint8_t * > ( enumAddr ) ; <nl> - auto * extraTagBitAddr = valueAddr + payloadSize ; <nl> - unsigned extraTagBits = 0 ; <nl> - unsigned numBytes = <nl> - getNumTagBytes ( payloadSize , emptyCases - payloadNumExtraInhabitants , <nl> - 1 / * payload case * / ) ; <nl> - <nl> - # if defined ( __BIG_ENDIAN__ ) <nl> - small_memcpy ( reinterpret_cast < uint8_t * > ( & extraTagBits ) + 4 - numBytes , <nl> - extraTagBitAddr , numBytes ) ; <nl> - # else <nl> - small_memcpy ( & extraTagBits , extraTagBitAddr , numBytes ) ; <nl> - # endif <nl> - <nl> - / / If the extra tag bits are zero , we have a valid payload or <nl> - / / extra inhabitant ( checked below ) . If nonzero , form the case index from <nl> - / / the extra tag value and the value stored in the payload . <nl> - if ( extraTagBits > 0 ) { <nl> - unsigned caseIndexFromExtraTagBits = <nl> - payloadSize > = 4 ? 0 : ( extraTagBits - 1U ) < < ( payloadSize * 8U ) ; <nl> - <nl> - / / In practice we should need no more than four bytes from the payload <nl> - / / area . <nl> - unsigned caseIndexFromValue = 0 ; <nl> - unsigned numPayloadTagBytes = std : : min ( size_t ( 4 ) , payloadSize ) ; <nl> - # if defined ( __BIG_ENDIAN__ ) <nl> - if ( numPayloadTagBytes ) <nl> - small_memcpy ( reinterpret_cast < uint8_t * > ( & caseIndexFromValue ) + 4 - <nl> - numPayloadTagBytes , <nl> - valueAddr , numPayloadTagBytes , true ) ; <nl> - # else <nl> - if ( numPayloadTagBytes ) <nl> - small_memcpy ( & caseIndexFromValue , valueAddr , <nl> - numPayloadTagBytes , true ) ; <nl> - # endif <nl> - return ( caseIndexFromExtraTagBits | caseIndexFromValue ) + <nl> - payloadNumExtraInhabitants ; <nl> - } <nl> - } <nl> - <nl> - / / If there are extra inhabitants , see whether the payload is valid . <nl> - if ( payloadNumExtraInhabitants > 0 ) { <nl> - return getExtraInhabitantIndex ( enumAddr , payload ) ; <nl> - } <nl> - <nl> - / / Otherwise , we have always have a valid payload . <nl> - return - 1 ; <nl> - } <nl> - <nl> - inline void storeEnumTagSinglePayloadImpl ( <nl> - OpaqueValue * value , int whichCase , unsigned emptyCases , <nl> - const Metadata * payload , size_t payloadSize , <nl> - size_t payloadNumExtraInhabitants , <nl> - void ( * storeExtraInhabitant ) ( OpaqueValue * , int whichCase , <nl> - const Metadata * ) ) { <nl> - <nl> - auto * valueAddr = reinterpret_cast < uint8_t * > ( value ) ; <nl> - auto * extraTagBitAddr = valueAddr + payloadSize ; <nl> - unsigned numExtraTagBytes = <nl> - emptyCases > payloadNumExtraInhabitants <nl> - ? getNumTagBytes ( payloadSize , emptyCases - payloadNumExtraInhabitants , <nl> - 1 / * payload case * / ) <nl> - : 0 ; <nl> - <nl> - / / For payload or extra inhabitant cases , zero - initialize the extra tag bits , <nl> - / / if any . <nl> - if ( whichCase < ( int ) payloadNumExtraInhabitants ) { <nl> - if ( numExtraTagBytes ! = 0 ) <nl> - small_memset ( extraTagBitAddr , 0 , numExtraTagBytes ) ; <nl> - <nl> - / / If this is the payload case , we ' re done . <nl> - if ( whichCase = = - 1 ) <nl> - return ; <nl> - <nl> - / / Store the extra inhabitant . <nl> - storeExtraInhabitant ( value , whichCase , payload ) ; <nl> - return ; <nl> - } <nl> - <nl> - / / Factor the case index into payload and extra tag parts . <nl> - unsigned caseIndex = whichCase - payloadNumExtraInhabitants ; <nl> - unsigned payloadIndex , extraTagIndex ; <nl> - if ( payloadSize > = 4 ) { <nl> - extraTagIndex = 1 ; <nl> - payloadIndex = caseIndex ; <nl> - } else { <nl> - unsigned payloadBits = payloadSize * 8U ; <nl> - extraTagIndex = 1U + ( caseIndex > > payloadBits ) ; <nl> - payloadIndex = caseIndex & ( ( 1U < < payloadBits ) - 1U ) ; <nl> - } <nl> - <nl> - / / Store into the value . <nl> - # if defined ( __BIG_ENDIAN__ ) <nl> - unsigned numPayloadTagBytes = std : : min ( size_t ( 4 ) , payloadSize ) ; <nl> - if ( numPayloadTagBytes ) <nl> - small_memcpy ( valueAddr , <nl> - reinterpret_cast < uint8_t * > ( & payloadIndex ) + 4 - <nl> - numPayloadTagBytes , <nl> - numPayloadTagBytes , true ) ; <nl> - if ( numExtraTagBytes ) <nl> - small_memcpy ( extraTagBitAddr , <nl> - reinterpret_cast < uint8_t * > ( & extraTagIndex ) + 4 - <nl> - numExtraTagBytes , <nl> - numExtraTagBytes ) ; <nl> - # else <nl> - unsigned numPayloadTagBytes = std : : min ( size_t ( 4 ) , payloadSize ) ; <nl> - if ( numPayloadTagBytes ) <nl> - small_memcpy ( valueAddr , & payloadIndex , numPayloadTagBytes , true ) ; <nl> - if ( numExtraTagBytes ) <nl> - small_memcpy ( extraTagBitAddr , & extraTagIndex , numExtraTagBytes ) ; <nl> - # endif <nl> - } <nl> - <nl> - } / * end namespace swift * / <nl> - <nl> - # endif / * SWIFT_RUNTIME_ENUMIMPL_H * / <nl> mmm a / stdlib / public / runtime / Metadata . cpp <nl> ppp b / stdlib / public / runtime / Metadata . cpp <nl> static OpaqueValue * tuple_initializeBufferWithTakeOfBuffer ( ValueBuffer * dest , <nl> return tuple_projectBuffer < IsPOD , IsInline > ( dest , metatype ) ; <nl> } <nl> <nl> - template < bool IsPOD , bool IsInline > <nl> - static int tuple_getEnumTagSinglePayload ( const OpaqueValue * enumAddr , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - auto * witnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = witnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = witnesses - > getNumExtraInhabitants ( ) ; <nl> - auto getExtraInhabitantIndex = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( witnesses ) <nl> - - > getExtraInhabitantIndex ) ; <nl> - <nl> - return getEnumTagSinglePayloadImpl ( enumAddr , numEmptyCases , self , size , <nl> - numExtraInhabitants , <nl> - getExtraInhabitantIndex ) ; <nl> - } <nl> - <nl> - template < bool IsPOD , bool IsInline > <nl> - static void <nl> - tuple_storeEnumTagSinglePayload ( OpaqueValue * enumAddr , int whichCase , <nl> - unsigned numEmptyCases , const Metadata * self ) { <nl> - auto * witnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = witnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = witnesses - > getNumExtraInhabitants ( ) ; <nl> - auto storeExtraInhabitant = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( witnesses ) <nl> - - > storeExtraInhabitant ) ; <nl> - <nl> - storeEnumTagSinglePayloadImpl ( enumAddr , whichCase , numEmptyCases , self , size , <nl> - numExtraInhabitants , storeExtraInhabitant ) ; <nl> - } <nl> - <nl> static void tuple_storeExtraInhabitant ( OpaqueValue * tuple , <nl> int index , <nl> const Metadata * _metatype ) { <nl> static OpaqueValue * pod_direct_initializeWithCopy ( OpaqueValue * dest , <nl> # define pod_direct_assignWithTake pod_direct_initializeWithCopy <nl> # define pod_indirect_assignWithTake pod_direct_initializeWithCopy <nl> <nl> - static int pod_direct_getEnumTagSinglePayload ( const OpaqueValue * enumAddr , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - auto * witnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = witnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = witnesses - > getNumExtraInhabitants ( ) ; <nl> - auto getExtraInhabitantIndex = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( witnesses ) <nl> - - > getExtraInhabitantIndex ) ; <nl> - <nl> - return getEnumTagSinglePayloadImpl ( enumAddr , numEmptyCases , self , size , <nl> - numExtraInhabitants , <nl> - getExtraInhabitantIndex ) ; <nl> - } <nl> - <nl> - static void pod_direct_storeEnumTagSinglePayload ( OpaqueValue * enumAddr , <nl> - int whichCase , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - auto * witnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = witnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = witnesses - > getNumExtraInhabitants ( ) ; <nl> - auto storeExtraInhabitant = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( witnesses ) <nl> - - > storeExtraInhabitant ) ; <nl> - <nl> - storeEnumTagSinglePayloadImpl ( enumAddr , whichCase , numEmptyCases , self , size , <nl> - numExtraInhabitants , storeExtraInhabitant ) ; <nl> - } <nl> - <nl> - # define pod_indirect_getEnumTagSinglePayload pod_direct_getEnumTagSinglePayload <nl> - # define pod_indirect_storeEnumTagSinglePayload \ <nl> - pod_direct_storeEnumTagSinglePayload <nl> <nl> static constexpr uint64_t sizeWithAlignmentMask ( uint64_t size , <nl> - uint64_t alignmentMask , <nl> - uint64_t hasExtraInhabitants ) { <nl> - return ( hasExtraInhabitants < < 48 ) | ( size < < 16 ) | alignmentMask ; <nl> + uint64_t alignmentMask ) { <nl> + return ( size < < 16 ) | alignmentMask ; <nl> } <nl> <nl> void swift : : installCommonValueWitnesses ( ValueWitnessTable * vwtable ) { <nl> void swift : : installCommonValueWitnesses ( ValueWitnessTable * vwtable ) { <nl> / / If the value has a common size and alignment , use specialized value <nl> / / witnesses we already have lying around for the builtin types . <nl> const ValueWitnessTable * commonVWT ; <nl> - bool hasExtraInhabitants = flags . hasExtraInhabitants ( ) ; <nl> - switch ( sizeWithAlignmentMask ( vwtable - > size , vwtable - > getAlignmentMask ( ) , <nl> - hasExtraInhabitants ) ) { <nl> + switch ( sizeWithAlignmentMask ( vwtable - > size , vwtable - > getAlignmentMask ( ) ) ) { <nl> default : <nl> / / For uncommon layouts , use value witnesses that work with an arbitrary <nl> / / size and alignment . <nl> void swift : : installCommonValueWitnesses ( ValueWitnessTable * vwtable ) { <nl> } <nl> return ; <nl> <nl> - case sizeWithAlignmentMask ( 1 , 0 , 0 ) : <nl> + case sizeWithAlignmentMask ( 1 , 0 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi8_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 2 , 1 , 0 ) : <nl> + case sizeWithAlignmentMask ( 2 , 1 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi16_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 4 , 3 , 0 ) : <nl> + case sizeWithAlignmentMask ( 4 , 3 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi32_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 8 , 7 , 0 ) : <nl> + case sizeWithAlignmentMask ( 8 , 7 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi64_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 16 , 15 , 0 ) : <nl> + case sizeWithAlignmentMask ( 16 , 15 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi128_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 32 , 31 , 0 ) : <nl> + case sizeWithAlignmentMask ( 32 , 31 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi256_ ) ; <nl> break ; <nl> - case sizeWithAlignmentMask ( 64 , 63 , 0 ) : <nl> + case sizeWithAlignmentMask ( 64 , 63 ) : <nl> commonVWT = & VALUE_WITNESS_SYM ( Bi512_ ) ; <nl> break ; <nl> } <nl> void swift : : swift_initStructMetadata_UniversalStrategy ( size_t numFields , <nl> vwtable - > flags = layout . flags ; <nl> vwtable - > stride = layout . stride ; <nl> <nl> + / / Substitute in better value witnesses if we have them . <nl> + installCommonValueWitnesses ( vwtable ) ; <nl> + <nl> / / We have extra inhabitants if the first element does . <nl> / / FIXME : generalize this . <nl> if ( fieldTypes [ 0 ] - > flags . hasExtraInhabitants ( ) ) { <nl> void swift : : swift_initStructMetadata_UniversalStrategy ( size_t numFields , <nl> assert ( xiVWT - > storeExtraInhabitant ) ; <nl> assert ( xiVWT - > getExtraInhabitantIndex ) ; <nl> } <nl> - <nl> - / / Substitute in better value witnesses if we have them . <nl> - installCommonValueWitnesses ( vwtable ) ; <nl> } <nl> <nl> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> mmm a / stdlib / public / runtime / MetadataImpl . h <nl> ppp b / stdlib / public / runtime / MetadataImpl . h <nl> <nl> # endif <nl> <nl> # include " WeakReference . h " <nl> - # include " EnumImpl . h " <nl> <nl> # include < cstring > <nl> # include < type_traits > <nl> struct SwiftAllocator { <nl> <nl> / / / A CRTP class which provides basic implementations for a number of <nl> / / / value witnesses relating to buffers . <nl> - template < class Impl > <nl> - struct BufferValueWitnessesBase { } ; <nl> + template < class Impl > struct BufferValueWitnessesBase { } ; <nl> <nl> / / / How should a type be packed into a fixed - size buffer ? <nl> enum class FixedPacking { <nl> struct NonFixedBufferValueWitnesses : BufferValueWitnessesBase < Impl > { <nl> } <nl> } ; <nl> <nl> - / / / Provides implementations for <nl> - / / / getEnumTagSinglePayload / storeEnumTagSinglePayload . <nl> - template < class Impl , size_t Size , size_t Alignment , bool hasExtraInhabitants > <nl> - struct FixedSizeBufferValueWitnesses ; <nl> - <nl> - / / / A fixed size buffer value witness that can rely on the presents of the extra <nl> - / / / inhabitant functions . <nl> - template < class Impl , size_t Size , size_t Alignment > <nl> - struct FixedSizeBufferValueWitnesses < Impl , Size , Alignment , <nl> - true / * hasExtraInhabitants * / > <nl> - : BufferValueWitnesses < Impl , Size , Alignment > { <nl> - <nl> - static int getEnumTagSinglePayload ( const OpaqueValue * enumAddr , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - return getEnumTagSinglePayloadImpl ( enumAddr , numEmptyCases , self , Size , <nl> - Impl : : numExtraInhabitants , <nl> - Impl : : getExtraInhabitantIndex ) ; <nl> - } <nl> - <nl> - static void storeEnumTagSinglePayload ( OpaqueValue * enumAddr , int whichCase , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - return storeEnumTagSinglePayloadImpl ( enumAddr , whichCase , numEmptyCases , <nl> - self , Size , Impl : : numExtraInhabitants , <nl> - Impl : : storeExtraInhabitant ) ; <nl> - } <nl> - } ; <nl> - <nl> - / / / A fixed size buffer value witness that cannot rely on the presents of the <nl> - / / / extra inhabitant functions . <nl> - template < class Impl , size_t Size , size_t Alignment > <nl> - struct FixedSizeBufferValueWitnesses < Impl , Size , Alignment , <nl> - false / * hasExtraInhabitants * / > <nl> - : BufferValueWitnesses < Impl , Size , Alignment > { <nl> - <nl> - static int getEnumTagSinglePayload ( const OpaqueValue * enumAddr , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - return getEnumTagSinglePayloadImpl ( enumAddr , numEmptyCases , self , Size , 0 , <nl> - nullptr ) ; <nl> - } <nl> - <nl> - static void storeEnumTagSinglePayload ( OpaqueValue * enumAddr , int whichCase , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - return storeEnumTagSinglePayloadImpl ( enumAddr , whichCase , numEmptyCases , <nl> - self , Size , 0 , nullptr ) ; <nl> - } <nl> - } ; <nl> - <nl> - static constexpr bool hasExtraInhabitants ( unsigned numExtraInhabitants ) { <nl> - return numExtraInhabitants ! = 0 ; <nl> - } <nl> / / / A class which provides default implementations of various value <nl> / / / witnesses based on a box ' s value operations . <nl> / / / <nl> / / / The box type has to provide a numExtraInhabitants member , but as <nl> / / / long as it ' s zero , the rest is fine . <nl> template < class Box > <nl> - struct ValueWitnesses : FixedSizeBufferValueWitnesses < <nl> - ValueWitnesses < Box > , Box : : size , Box : : alignment , <nl> - hasExtraInhabitants ( Box : : numExtraInhabitants ) > { <nl> - using Base = FixedSizeBufferValueWitnesses < <nl> - ValueWitnesses < Box > , Box : : size , Box : : alignment , <nl> - hasExtraInhabitants ( Box : : numExtraInhabitants ) > ; <nl> + struct ValueWitnesses : BufferValueWitnesses < ValueWitnesses < Box > , <nl> + Box : : size , Box : : alignment > <nl> + { <nl> + using Base = BufferValueWitnesses < ValueWitnesses < Box > , <nl> + Box : : size , Box : : alignment > ; <nl> <nl> static constexpr size_t size = Box : : size ; <nl> static constexpr size_t stride = Box : : stride ; <nl> struct NonFixedValueWitnesses : <nl> self ) ; <nl> } <nl> <nl> - static int getEnumTagSinglePayload ( const OpaqueValue * enumAddr , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - auto * payloadWitnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = payloadWitnesses - > getSize ( ) ; <nl> - auto getExtraInhabitantIndex = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( <nl> - payloadWitnesses ) <nl> - - > getExtraInhabitantIndex ) ; <nl> - <nl> - return getEnumTagSinglePayloadImpl ( enumAddr , numEmptyCases , self , size , <nl> - numExtraInhabitants , <nl> - getExtraInhabitantIndex ) ; <nl> - } <nl> - <nl> - static void storeEnumTagSinglePayload ( OpaqueValue * enumAddr , int whichCase , <nl> - unsigned numEmptyCases , <nl> - const Metadata * self ) { <nl> - auto * payloadWitnesses = self - > getValueWitnesses ( ) ; <nl> - auto size = payloadWitnesses - > getSize ( ) ; <nl> - auto numExtraInhabitants = payloadWitnesses - > getNumExtraInhabitants ( ) ; <nl> - auto storeExtraInhabitant = <nl> - ( static_cast < const ExtraInhabitantsValueWitnessTable * > ( <nl> - payloadWitnesses ) <nl> - - > storeExtraInhabitant ) ; <nl> - <nl> - storeEnumTagSinglePayloadImpl ( enumAddr , whichCase , numEmptyCases , self , <nl> - size , numExtraInhabitants , <nl> - storeExtraInhabitant ) ; <nl> - } <nl> - <nl> / / These should not get instantiated if the type doesn ' t have extra <nl> / / inhabitants . <nl> <nl> mmm a / test / IRGen / builtins . swift <nl> ppp b / test / IRGen / builtins . swift <nl> func sizeof_alignof_test ( ) { <nl> <nl> / / CHECK : define hidden { { . * } } void @ _T08builtins27generic_sizeof_alignof_testyxlF ( <nl> func generic_sizeof_alignof_test < T > ( _ : T ) { <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 9 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 7 <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = load i8 * , i8 * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ T1 ] ] to i64 <nl> / / CHECK - NEXT : store i64 [ [ SIZE ] ] , i64 * [ [ S : % . * ] ] <nl> var s = Builtin . sizeof ( T . self ) <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 10 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 8 <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = load i8 * , i8 * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ T2 : % . * ] ] = ptrtoint i8 * [ [ T1 ] ] to i64 <nl> / / CHECK - NEXT : [ [ T3 : % . * ] ] = and i64 [ [ T2 ] ] , 65535 <nl> func generic_sizeof_alignof_test < T > ( _ : T ) { <nl> <nl> / / CHECK : define hidden { { . * } } void @ _T08builtins21generic_strideof_testyxlF ( <nl> func generic_strideof_test < T > ( _ : T ) { <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 11 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 9 <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = load i8 * , i8 * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ STRIDE : % . * ] ] = ptrtoint i8 * [ [ T1 ] ] to i64 <nl> / / CHECK - NEXT : store i64 [ [ STRIDE ] ] , i64 * [ [ S : % . * ] ] <nl> func isUniqueIUO ( _ ref : inout Builtin . NativeObject ? ) - > Bool { <nl> <nl> / / CHECK - LABEL : define { { . * } } @ { { . * } } generic_ispod_test <nl> func generic_ispod_test < T > ( _ : T ) { <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 10 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T : % . * ] ] , i32 8 <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = load i8 * , i8 * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ T1 ] ] to i64 <nl> / / CHECK - NEXT : [ [ ISNOTPOD : % . * ] ] = and i64 [ [ FLAGS ] ] , 65536 <nl> mmm a / test / IRGen / enum . sil <nl> ppp b / test / IRGen / enum . sil <nl> import Swift <nl> / / CHECK - SAME : i32 1 <nl> / / CHECK - SAME : } > <nl> <nl> - / / CHECK : @ _T04enum16DynamicSingletonOMP = internal global < { { { . * } } , [ 18 x i8 * ] } > < { <nl> + / / CHECK : @ _T04enum16DynamicSingletonOMP = internal global < { { { . * } } , [ 16 x i8 * ] } > < { <nl> / / CHECK - SAME : % swift . type * ( % swift . type_pattern * , i8 * * ) * @ create_generic_metadata_DynamicSingleton <nl> / / CHECK - SAME : @ _T04enum16DynamicSingletonOMn <nl> / / CHECK - SAME : i8 * null <nl> import Swift <nl> <nl> / / - - No - payload enums have extra inhabitants in <nl> / / their value witness table . <nl> - / / CHECK : @ _T04enum10NoPayloadsOWV = internal constant [ 18 x i8 * ] [ <nl> + / / CHECK : @ _T04enum10NoPayloadsOWV = internal constant [ 16 x i8 * ] [ <nl> / / - - . . . <nl> / / - - size <nl> / / CHECK - SAME : i8 * inttoptr ( [ [ WORD : i32 | i64 ] ] 1 to i8 * ) , <nl> import Swift <nl> <nl> / / - - Single - payload enums take unused extra inhabitants from their payload <nl> / / as their own . <nl> - / / CHECK : @ _T04enum19SinglePayloadNestedOWV = internal constant [ 18 x i8 * ] [ <nl> + / / CHECK : @ _T04enum19SinglePayloadNestedOWV = internal constant [ 16 x i8 * ] [ <nl> / / - - . . . <nl> / / - - size <nl> / / CHECK - SAME : i8 * inttoptr ( [ [ WORD ] ] 1 to i8 * ) , <nl> import Swift <nl> / / CHECK - SAME : ] <nl> <nl> <nl> - / / CHECK : @ _T04enum20DynamicSinglePayloadOMP = internal global < { { { . * } } , [ 18 x i8 * ] } > < { <nl> + / / CHECK : @ _T04enum20DynamicSinglePayloadOMP = internal global < { { { . * } } , [ 16 x i8 * ] } > < { <nl> / / CHECK - SAME : % swift . type * ( % swift . type_pattern * , i8 * * ) * @ create_generic_metadata_DynamicSinglePayload <nl> / / CHECK - SAME : i8 * null <nl> / / CHECK - SAME : i8 * bitcast ( void ( % swift . opaque * , i32 , % swift . type * ) * @ _T04enum20DynamicSinglePayloadOwxs to i8 * ) <nl> / / CHECK - SAME : i8 * bitcast ( i32 ( % swift . opaque * , % swift . type * ) * @ _T04enum20DynamicSinglePayloadOwxg to i8 * ) <nl> <nl> - / / CHECK : @ _T04enum18MultiPayloadNestedOWV = internal constant [ 18 x i8 * ] [ <nl> + / / CHECK : @ _T04enum18MultiPayloadNestedOWV = internal constant [ 16 x i8 * ] [ <nl> / / - - size <nl> / / CHECK - 32 - SAME : i8 * inttoptr ( [ [ WORD ] ] 5 to i8 * ) , <nl> / / CHECK - 64 - SAME : i8 * inttoptr ( [ [ WORD ] ] 9 to i8 * ) , <nl> enum DynamicSinglePayload < T > { <nl> <nl> / / CHECK : define { { ( protected ) ? } } swiftcc void @ dynamic_single_payload_switch ( % T4enum20DynamicSinglePayloadO * noalias nocapture , % swift . type * % T ) { { . * } } { <nl> / / CHECK : [ [ OPAQUE_ENUM : % . * ] ] = bitcast % T4enum20DynamicSinglePayloadO * % 0 to % swift . opaque * <nl> - / / CHECK : [ [ TMP : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> - / / CHECK : [ [ TMP2 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TMP ] ] , i { { . * } } - 1 <nl> - / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ TMP2 ] ] <nl> - / / CHECK : [ [ ENUMADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> - / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ ENUMADDR ] ] <nl> - / / CHECK : % getEnumTagSinglePayload = bitcast i8 * [ [ WITNESS ] ] to i32 ( % swift . opaque * , i32 , % swift . type * ) * <nl> - / / CHECK : [ [ CASE_INDEX : % . * ] ] = call i32 % getEnumTagSinglePayload ( % swift . opaque * noalias [ [ OPAQUE_ENUM ] ] , i32 3 , % swift . type * % T ) <nl> + / / CHECK : [ [ CASE_INDEX : % . * ] ] = call i32 @ swift_rt_swift_getEnumCaseSinglePayload ( % swift . opaque * [ [ OPAQUE_ENUM ] ] , % swift . type * % T , i32 3 ) <nl> / / CHECK : switch i32 [ [ CASE_INDEX ] ] , label { { % . * } } [ <nl> / / CHECK : i32 - 1 , label { { % . * } } <nl> / / CHECK : i32 2 , label { { % . * } } <nl> end : <nl> } <nl> <nl> / / CHECK : define { { ( protected ) ? } } swiftcc void @ dynamic_single_payload_inject_x ( % T4enum20DynamicSinglePayloadO * noalias nocapture sret , % swift . opaque * noalias nocapture , % swift . type * % T ) { { . * } } { <nl> - / / CHECK : [ [ OPAQUE_ENUM : % . * ] ] = bitcast % T4enum20DynamicSinglePayloadO * % 0 to % swift . opaque * <nl> - / / CHECK : [ [ TMP : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> - / / CHECK : [ [ TMP2 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TMP ] ] , i { { . * } } - 1 <nl> - / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ TMP2 ] ] <nl> - / / CHECK : [ [ ENUMADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> - / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ ENUMADDR ] ] <nl> - / / CHECK : % storeEnumTagSinglePayload = bitcast i8 * [ [ WITNESS ] ] to void ( % swift . opaque * , i32 , i32 , % swift . type * ) * <nl> - / / CHECK : call void % storeEnumTagSinglePayload ( % swift . opaque * noalias [ [ OPAQUE_ENUM ] ] , i32 - 1 , i32 3 , % swift . type * % T ) <nl> + / / CHECK : [ [ ADDR : % . * ] ] = bitcast % T4enum20DynamicSinglePayloadO * % 0 to % swift . opaque * <nl> + / / CHECK : call void @ swift_rt_swift_storeEnumTagSinglePayload ( % swift . opaque * [ [ ADDR ] ] , % swift . type * % T , i32 - 1 , i32 3 ) <nl> sil @ dynamic_single_payload_inject_x : $ < T > ( @ in T ) - > @ out DynamicSinglePayload < T > { <nl> entry ( % r : $ * DynamicSinglePayload < T > , % t : $ * T ) : <nl> inject_enum_addr % r : $ * DynamicSinglePayload < T > , # DynamicSinglePayload . x ! enumelt . 1 <nl> entry ( % r : $ * DynamicSinglePayload < T > , % t : $ * T ) : <nl> } <nl> <nl> / / CHECK : define { { ( protected ) ? } } swiftcc void @ dynamic_single_payload_inject_y ( % T4enum20DynamicSinglePayloadO * noalias nocapture sret , % swift . type * % T ) { { . * } } { <nl> - / / CHECK : [ [ OPAQUE_ENUM : % . * ] ] = bitcast % T4enum20DynamicSinglePayloadO * % 0 to % swift . opaque * <nl> - / / CHECK : [ [ TMP : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> - / / CHECK : [ [ TMP2 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TMP ] ] , i { { . * } } - 1 <nl> - / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ TMP2 ] ] <nl> - / / CHECK : [ [ ENUMADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> - / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ ENUMADDR ] ] <nl> - / / CHECK : % storeEnumTagSinglePayload = bitcast i8 * [ [ WITNESS ] ] to void ( % swift . opaque * , i32 , i32 , % swift . type * ) * <nl> - / / CHECK : call void % storeEnumTagSinglePayload ( % swift . opaque * noalias [ [ OPAQUE_ENUM ] ] , i32 0 , i32 3 , % swift . type * % T ) <nl> + / / CHECK : [ [ ADDR : % . * ] ] = bitcast % T4enum20DynamicSinglePayloadO * % 0 to % swift . opaque * <nl> + / / CHECK : call void @ swift_rt_swift_storeEnumTagSinglePayload ( % swift . opaque * [ [ ADDR ] ] , % swift . type * % T , i32 0 , i32 3 ) <nl> sil @ dynamic_single_payload_inject_y : $ < T > ( ) - > @ out DynamicSinglePayload < T > { <nl> entry ( % r : $ * DynamicSinglePayload < T > ) : <nl> inject_enum_addr % r : $ * DynamicSinglePayload < T > , # DynamicSinglePayload . y ! enumelt <nl> entry ( % x : $ * MyOptional ) : <nl> / / CHECK : [ [ T_VWTS : % . * ] ] = bitcast % swift . type * [ [ T ] ] to i8 * * * <nl> / / CHECK : [ [ T_VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T_VWTS ] ] , [ [ WORD ] ] - 1 <nl> / / CHECK : [ [ T_VWT : % . * ] ] = load i8 * * , i8 * * * [ [ T_VWT_ADDR ] ] <nl> - / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VWT ] ] , i32 9 <nl> - / / CHECK : [ [ SIZE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VWT ] ] , i32 7 <nl> + / / CHECK : [ [ SIZE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ T_SIZE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_LAYOUT ] ] , i32 0 <nl> / / CHECK : [ [ T_SIZE : % . * ] ] = load i8 * , i8 * * [ [ T_SIZE_ADDR ] ] <nl> / / CHECK : store i8 * [ [ T_SIZE ] ] , i8 * * [ [ SIZE_ADDR ] ] <nl> - / / CHECK : [ [ STRIDE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 11 <nl> + / / CHECK : [ [ STRIDE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> / / CHECK : [ [ T_STRIDE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_LAYOUT ] ] , i32 2 <nl> / / CHECK : [ [ T_STRIDE : % . * ] ] = load i8 * , i8 * * [ [ T_STRIDE_ADDR ] ] <nl> / / CHECK : store i8 * [ [ T_STRIDE ] ] , i8 * * [ [ STRIDE_ADDR ] ] <nl> - / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ T_FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_LAYOUT ] ] , i32 1 <nl> / / CHECK : [ [ T_FLAGS : % . * ] ] = load i8 * , i8 * * [ [ T_FLAGS_ADDR ] ] <nl> / / CHECK : [ [ T_FLAGS_INT : % . * ] ] = ptrtoint i8 * [ [ T_FLAGS ] ] to [ [ WORD ] ] <nl> entry ( % x : $ * MyOptional ) : <nl> / / CHECK : [ [ XI_BIT : % . * ] ] = icmp ne [ [ WORD ] ] [ [ XI_FLAG ] ] , 0 <nl> / / CHECK : br i1 [ [ XI_BIT ] ] , label % [ [ HAS_XI : [ 0 - 9 ] + ] ] , label % [ [ HAS_NO_XI : [ 0 - 9 ] + ] ] <nl> / / CHECK : ; < label > : [ [ HAS_XI ] ] <nl> - / / CHECK : [ [ XI_FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 12 <nl> + / / CHECK : [ [ XI_FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> / / CHECK : [ [ T_XI_FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_LAYOUT ] ] , i32 3 <nl> / / CHECK : [ [ T_XI_FLAGS : % . * ] ] = load i8 * , i8 * * [ [ T_XI_FLAGS_ADDR ] ] <nl> / / CHECK : store i8 * [ [ T_XI_FLAGS ] ] , i8 * * [ [ XI_FLAGS_ADDR ] ] <nl> mmm a / test / IRGen / enum_dynamic_multi_payload . sil <nl> ppp b / test / IRGen / enum_dynamic_multi_payload . sil <nl> entry ( % a : $ * EitherOr < T , C > , % b : $ * EitherOr < T , C > ) : <nl> / / CHECK - NEXT : [ [ T0 : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK - NEXT : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK - NEXT : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK - NEXT : store i8 * * [ [ LAYOUT ] ] , { { . * } } [ [ BUF0 ] ] <nl> <nl> / / CHECK : [ [ BUF1 : % . * ] ] = getelementptr { { . * } } [ [ BUF ] ] , i32 0 , i32 1 <nl> / / CHECK - NEXT : [ [ T0 : % . * ] ] = bitcast % swift . type * % U to i8 * * * <nl> / / CHECK - NEXT : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] <nl> / / CHECK - NEXT : [ [ VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK - NEXT : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK - NEXT : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK - NEXT : store i8 * * [ [ LAYOUT ] ] , { { . * } } [ [ BUF1 ] ] <nl> <nl> / / CHECK : call void @ swift_initEnumMetadataMultiPayload ( i8 * * { { % . * } } , % swift . type * [ [ METADATA ] ] , { { i ( 32 | 64 ) } } 2 , i8 * * * [ [ BUF0 ] ] ) <nl> mmm a / test / IRGen / enum_resilience . swift <nl> ppp b / test / IRGen / enum_resilience . swift <nl> public func constructResilientEnumNoPayload ( ) - > Medium { <nl> / / CHECK - NEXT : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ METADATA_ADDR ] ] , [ [ INT : i32 | i64 ] ] - 1 <nl> / / CHECK - NEXT : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> <nl> - / / CHECK - NEXT : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 17 <nl> + / / CHECK - NEXT : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 15 <nl> / / CHECK - NEXT : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ WITNESS_ADDR ] ] <nl> / / CHECK - NEXT : [ [ WITNESS_FN : % . * ] ] = bitcast i8 * [ [ WITNESS ] ] <nl> / / CHECK - NEXT : call void [ [ WITNESS_FN ] ] ( % swift . opaque * noalias % 0 , i32 0 , % swift . type * [ [ METADATA ] ] ) <nl> public func constructResilientEnumPayload ( _ s : Size ) - > Medium { <nl> / / CHECK - NEXT : [ [ VWT_ADDR2 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ METADATA_ADDR2 ] ] , [ [ INT : i32 | i64 ] ] - 1 <nl> / / CHECK - NEXT : [ [ VWT2 : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR2 ] ] <nl> <nl> - / / CHECK - NEXT : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT2 ] ] , i32 17 <nl> + / / CHECK - NEXT : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT2 ] ] , i32 15 <nl> / / CHECK - NEXT : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ WITNESS_ADDR ] ] <nl> / / CHECK - NEXT : [ [ WITNESS_FN : % . * ] ] = bitcast i8 * [ [ WITNESS ] ] <nl> / / CHECK - NEXT : call void [ [ WITNESS_FN ] ] ( % swift . opaque * noalias % 0 , i32 - 2 , % swift . type * [ [ METADATA2 ] ] ) <nl> public func constructResilientEnumPayload ( _ s : Size ) - > Medium { <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ METADATA_ADDR ] ] , [ [ INT ] ] - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> <nl> - / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ WITNESS_ADDR ] ] <nl> / / CHECK : [ [ WITNESS_FOR_SIZE : % . * ] ] = ptrtoint i8 * [ [ WITNESS ] ] <nl> / / CHECK : [ [ ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ WITNESS_FOR_SIZE ] ] , align 16 <nl> public func constructResilientEnumPayload ( _ s : Size ) - > Medium { <nl> / / CHECK : [ [ WITNESS_FN : % . * ] ] = bitcast i8 * [ [ WITNESS ] ] <nl> / / CHECK : [ [ ENUM_COPY : % . * ] ] = call % swift . opaque * [ [ WITNESS_FN ] ] ( % swift . opaque * noalias [ [ ENUM_STORAGE ] ] , % swift . opaque * noalias % 0 , % swift . type * [ [ METADATA ] ] ) <nl> <nl> - / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 15 <nl> + / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 13 <nl> / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ WITNESS_ADDR ] ] <nl> / / CHECK : [ [ WITNESS_FN : % . * ] ] = bitcast i8 * [ [ WITNESS ] ] <nl> / / CHECK : [ [ TAG : % . * ] ] = call i32 % getEnumTag ( % swift . opaque * noalias [ [ ENUM_STORAGE ] ] , % swift . type * [ [ METADATA ] ] ) <nl> mmm a / test / IRGen / enum_value_semantics . sil <nl> ppp b / test / IRGen / enum_value_semantics . sil <nl> enum GenericFixedLayout < T > { <nl> } <nl> <nl> <nl> - / / CHECK - LABEL : @ _T020enum_value_semantics20SinglePayloadTrivialOWV = internal constant [ 18 x i8 * ] [ <nl> + / / CHECK - LABEL : @ _T020enum_value_semantics20SinglePayloadTrivialOWV = internal constant [ 16 x i8 * ] [ <nl> / / CHECK : i8 * bitcast ( i8 * ( i8 * , i8 * , % swift . type * ) * @ __swift_memcpy9_8 to i8 * ) , <nl> / / CHECK : i8 * bitcast ( void ( i8 * , % swift . type * ) * @ __swift_noop_void_return to i8 * ) , <nl> / / CHECK : i8 * bitcast ( i8 * ( i8 * , i8 * , % swift . type * ) * @ __swift_memcpy9_8 to i8 * ) , <nl> enum GenericFixedLayout < T > { <nl> / / CHECK : i8 * bitcast ( i8 * ( i8 * , i8 * , % swift . type * ) * @ __swift_memcpy9_8 to i8 * ) , <nl> / / CHECK : i8 * bitcast ( i8 * ( i8 * , i8 * , % swift . type * ) * @ __swift_memcpy9_8 to i8 * ) , <nl> / / CHECK : i8 * bitcast ( i8 * ( i8 * , i8 * , % swift . type * ) * @ __swift_memcpy9_8 to i8 * ) , <nl> - / / CHECK : i8 * bitcast ( i32 ( % swift . opaque * , i32 , % swift . type * ) * @ _T020enum_value_semantics20SinglePayloadTrivialOwet to i8 * ) , <nl> - / / CHECK : i8 * bitcast ( void ( % swift . opaque * , i32 , i32 , % swift . type * ) * @ _T020enum_value_semantics20SinglePayloadTrivialOwst to i8 * ) , <nl> / / CHECK : i8 * inttoptr ( i64 9 to i8 * ) , <nl> / / CHECK : i8 * inttoptr ( i64 2097159 to i8 * ) , <nl> / / CHECK : i8 * inttoptr ( i64 16 to i8 * ) , <nl> enum GenericFixedLayout < T > { <nl> <nl> / / CHECK - LABEL : @ _T020enum_value_semantics20SinglePayloadTrivialOMf = <nl> / / CHECK - SAME : internal constant < { { { . * } } } > < { <nl> - / / CHECK - SAME : i8 * * getelementptr inbounds ( [ 18 x i8 * ] , [ 18 x i8 * ] * @ _T020enum_value_semantics20SinglePayloadTrivialOWV , i32 0 , i32 0 ) , <nl> + / / CHECK - SAME : i8 * * getelementptr inbounds ( [ 16 x i8 * ] , [ 16 x i8 * ] * @ _T020enum_value_semantics20SinglePayloadTrivialOWV , i32 0 , i32 0 ) , <nl> / / CHECK - SAME : i64 2 , <nl> / / CHECK - SAME : { { . * } } * @ _T020enum_value_semantics20SinglePayloadTrivialOMn <nl> / / CHECK - SAME : } > <nl> <nl> <nl> - / / CHECK - LABEL : @ _T020enum_value_semantics23SinglePayloadNontrivialOWV = internal constant [ 18 x i8 * ] [ <nl> + / / CHECK - LABEL : @ _T020enum_value_semantics23SinglePayloadNontrivialOWV = internal constant [ 16 x i8 * ] [ <nl> / / CHECK : i8 * bitcast ( % swift . opaque * ( [ 24 x i8 ] * , [ 24 x i8 ] * , % swift . type * ) * @ _T020enum_value_semantics23SinglePayloadNontrivialOwCP to i8 * ) , <nl> / / CHECK : i8 * bitcast ( void ( % swift . opaque * , % swift . type * ) * @ _T020enum_value_semantics23SinglePayloadNontrivialOwxx to i8 * ) , <nl> / / CHECK : i8 * bitcast ( % swift . opaque * ( % swift . opaque * , % swift . opaque * , % swift . type * ) * @ _T020enum_value_semantics23SinglePayloadNontrivialOwcp to i8 * ) , <nl> enum GenericFixedLayout < T > { <nl> <nl> / / CHECK - LABEL : @ _T020enum_value_semantics23SinglePayloadNontrivialOMf = <nl> / / CHECK - SAME : internal constant < { { { . * } } } > < { <nl> - / / CHECK - SAME : i8 * * getelementptr inbounds ( [ 18 x i8 * ] , [ 18 x i8 * ] * @ _T020enum_value_semantics23SinglePayloadNontrivialOWV , i32 0 , i32 0 ) , <nl> + / / CHECK - SAME : i8 * * getelementptr inbounds ( [ 16 x i8 * ] , [ 16 x i8 * ] * @ _T020enum_value_semantics23SinglePayloadNontrivialOWV , i32 0 , i32 0 ) , <nl> / / CHECK - SAME : i64 2 , <nl> / / CHECK - SAME : { { . * } } * @ _T020enum_value_semantics23SinglePayloadNontrivialOMn <nl> / / CHECK - SAME : } > <nl> enum GenericFixedLayout < T > { <nl> / / CHECK : % swift . type * ( % swift . type_pattern * , i8 * * ) * @ create_generic_metadata_GenericFixedLayout <nl> / / CHECK : i32 40 , i16 1 , i16 8 , <nl> / / CHECK : [ 16 x i8 * ] zeroinitializer , <nl> - / / CHECK : i8 * * getelementptr inbounds ( [ 18 x i8 * ] , [ 18 x i8 * ] * @ _T020enum_value_semantics18GenericFixedLayoutOWV , i32 0 , i32 0 ) , <nl> + / / CHECK : i8 * * getelementptr inbounds ( [ 16 x i8 * ] , [ 16 x i8 * ] * @ _T020enum_value_semantics18GenericFixedLayoutOWV , i32 0 , i32 0 ) , <nl> / / CHECK : i64 2 , <nl> / / CHECK : { { . * } } * @ _T020enum_value_semantics18GenericFixedLayoutOMn <nl> / / CHECK : i { { 32 | 64 } } 0 <nl> bb0 ( % 0 : $ SinglePayloadNontrivial ) : <nl> <nl> / / - - SinglePayloadTrivial getEnumTag <nl> / / CHECK - LABEL : define linkonce_odr hidden i32 @ _T020enum_value_semantics20SinglePayloadTrivialOwug <nl> - / / CHECK : [ [ SELF : % . * ] ] = bitcast % swift . opaque * % value to % T20enum_value_semantics20SinglePayloadTrivialO * <nl> - / / CHECK : [ [ OPAQUE : % . * ] ] = bitcast % T20enum_value_semantics20SinglePayloadTrivialO * [ [ SELF ] ] to % swift . opaque * <nl> - / / CHECK : [ [ TAG : % . * ] ] = call i32 % getEnumTagSinglePayload ( % swift . opaque * noalias [ [ OPAQUE ] ] , i32 3 , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0Bi64_N , i32 0 , i32 1 ) ) <nl> - / / CHECK : ret i32 [ [ TAG ] ] <nl> + / / CHECK : [ [ SELF : % . * ] ] = bitcast % swift . opaque * % value to % T20enum_value_semantics20SinglePayloadTrivialO * <nl> + / / CHECK - NEXT : [ [ OPAQUE : % . * ] ] = bitcast % T20enum_value_semantics20SinglePayloadTrivialO * [ [ SELF ] ] to % swift . opaque * <nl> + / / CHECK - NEXT : [ [ TAG : % . * ] ] = call i32 @ swift_rt_swift_getEnumCaseSinglePayload ( % swift . opaque * [ [ OPAQUE ] ] , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0Bi64_N , i32 0 , i32 1 ) , i32 3 ) <nl> + / / CHECK - NEXT : ret i32 [ [ TAG ] ] <nl> <nl> <nl> / / - - SinglePayloadTrivial destructiveProjectEnumData <nl> bb0 ( % 0 : $ SinglePayloadNontrivial ) : <nl> / / CHECK - LABEL : define linkonce_odr hidden void @ _T020enum_value_semantics20SinglePayloadTrivialOwui <nl> / / CHECK : [ [ SELF : % . * ] ] = bitcast % swift . opaque * % value to % T20enum_value_semantics20SinglePayloadTrivialO * <nl> / / CHECK - NEXT : [ [ OPAQUE : % . * ] ] = bitcast % T20enum_value_semantics20SinglePayloadTrivialO * [ [ SELF ] ] to % swift . opaque * <nl> - / / CHECK : call void % storeEnumTagSinglePayload ( % swift . opaque * noalias [ [ OPAQUE ] ] , i32 % tag , i32 3 , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0Bi64_N , i32 0 , i32 1 ) ) <nl> + / / CHECK - NEXT : call void @ swift_rt_swift_storeEnumTagSinglePayload ( % swift . opaque * [ [ OPAQUE ] ] , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0Bi64_N , i32 0 , i32 1 ) , i32 % tag , i32 3 ) <nl> / / CHECK - NEXT : ret void <nl> <nl> <nl> mmm a / test / IRGen / existentials_opaque_boxed . sil <nl> ppp b / test / IRGen / existentials_opaque_boxed . sil <nl> entry ( % 0 : $ * T ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ METATYPE ] ] <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ FLAG_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ FLAG_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ FLAG_WITNESS : % . * ] ] = load i8 * , i8 * * [ [ FLAG_WITNESS_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ FLAG_WITNESS ] ] <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> entry : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ META ] ] to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * % 3 , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ VW : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ MASKED : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> entry : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ META ] ] to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR2 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT2 : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR2 ] ] <nl> - / / CHECK : [ [ VW_ADDR2 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT2 ] ] , i32 9 <nl> + / / CHECK : [ [ VW_ADDR2 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT2 ] ] , i32 7 <nl> / / CHECK : [ [ VW2 : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR2 ] ] <nl> / / CHECK : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ VW2 ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ ALIGNMASK : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 65535 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * % 1 to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ VW : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * % 1 to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ VW : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ METADATA ] ] to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ VW : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ DEST_TYPE ] ] to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 10 <nl> + / / CHECK : [ [ VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 8 <nl> / / CHECK : [ [ VW : % . * ] ] = load i8 * , i8 * * [ [ VW_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ MASKED : % . * ] ] = and { { ( i64 | i32 ) } } [ [ FLAGS ] ] , 131072 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ DEST_TYPE ] ] to i8 * * * <nl> / / CHECK : [ [ DEST_VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ DEST_VWT : % . * ] ] = load i8 * * , i8 * * * [ [ DEST_VWT_ADDR ] ] <nl> - / / CHECK : [ [ DEST_VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ DEST_VWT ] ] , i32 10 <nl> + / / CHECK : [ [ DEST_VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ DEST_VWT ] ] , i32 8 <nl> / / CHECK : [ [ DEST_VW : % . * ] ] = load i8 * , i8 * * [ [ DEST_VW_ADDR ] ] <nl> / / CHECK : [ [ DEST_FLAGS : % . * ] ] = ptrtoint i8 * [ [ DEST_VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ DEST_ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ DEST_FLAGS ] ] , 131072 <nl> bb0 ( % 0 : $ * Existential ) : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * [ [ SRC_TYPE ] ] to i8 * * * <nl> / / CHECK : [ [ SRC_VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { ( i64 | i32 ) } } - 1 <nl> / / CHECK : [ [ SRC_VWT : % . * ] ] = load i8 * * , i8 * * * [ [ SRC_VWT_ADDR ] ] <nl> - / / CHECK : [ [ SRC_VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ SRC_VWT ] ] , i32 10 <nl> + / / CHECK : [ [ SRC_VW_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ SRC_VWT ] ] , i32 8 <nl> / / CHECK : [ [ SRC_VW : % . * ] ] = load i8 * , i8 * * [ [ SRC_VW_ADDR ] ] <nl> / / CHECK : [ [ SRC_FLAGS : % . * ] ] = ptrtoint i8 * [ [ SRC_VW ] ] to { { ( i64 | i32 ) } } <nl> / / CHECK : [ [ SRC_ISNOTINLINE : % . * ] ] = and { { ( i64 | i32 ) } } [ [ SRC_FLAGS ] ] , 131072 <nl> mmm a / test / IRGen / generic_casts . swift <nl> ppp b / test / IRGen / generic_casts . swift <nl> func allToInt < T > ( _ x : T ) - > Int { <nl> / / CHECK : [ [ TYPE_ADDR : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TYPE_ADDR ] ] , i64 - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ SIZE_WITNESS : % . * ] ] = load i8 * , i8 * * [ [ SIZE_WITNESS_ADDR ] ] <nl> / / CHECK : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ SIZE_WITNESS ] ] <nl> / / CHECK : [ [ T_ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ SIZE ] ] , align 16 <nl> mmm a / test / IRGen / generic_classes . sil <nl> ppp b / test / IRGen / generic_classes . sil <nl> entry ( % c : $ RootGeneric < Int32 > ) : <nl> / / CHECK : [ [ T0 : % . * ] ] = bitcast % swift . type * % B to i8 * * * <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] , i64 - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] , align 8 <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ FIELDS_ADDR ] ] , i32 0 <nl> / / CHECK : store i8 * * [ [ T0 ] ] , i8 * * * [ [ T1 ] ] , align 8 <nl> / / CHECK : call % swift . type * @ swift_initClassMetadata_UniversalStrategy ( % swift . type * [ [ METADATA ] ] , i64 1 , i8 * * * [ [ FIELDS_ADDR ] ] , i64 * [ [ OFFSETS ] ] ) <nl> mmm a / test / IRGen / generic_structs . sil <nl> ppp b / test / IRGen / generic_structs . sil <nl> import Builtin <nl> / / CHECK : @ _T015generic_structs13SingleDynamicVMP = internal global < { { { . * } } } > < { <nl> / / - - template header <nl> / / CHECK - SAME : % swift . type * ( % swift . type_pattern * , i8 * * ) * @ create_generic_metadata_SingleDynamic , <nl> - / / CHECK - SAME : i32 168 , i16 1 , i16 8 , [ { { [ 0 - 9 ] + } } x i8 * ] zeroinitializer , <nl> + / / CHECK - SAME : i32 152 , i16 1 , i16 8 , [ { { [ 0 - 9 ] + } } x i8 * ] zeroinitializer , <nl> / / - - placeholder for vwtable pointer <nl> / / CHECK - SAME : i8 * null , <nl> / / - - address point <nl> mmm a / test / IRGen / generic_tuples . swift <nl> ppp b / test / IRGen / generic_tuples . swift <nl> func dup < T > ( _ x : T ) - > ( T , T ) { var x = x ; return ( x , x ) } <nl> / / CHECK : [ [ TYPE_ADDR : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TYPE_ADDR ] ] , i64 - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ SIZE_WITNESS : % . * ] ] = load i8 * , i8 * * [ [ SIZE_WITNESS_ADDR ] ] <nl> / / CHECK : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ SIZE_WITNESS ] ] <nl> / / CHECK : [ [ X_ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ SIZE ] ] , align 16 <nl> mmm a / test / IRGen / global_resilience . sil <nl> ppp b / test / IRGen / global_resilience . sil <nl> bb0 : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * % 0 to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { . * } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % . valueWitnesses , i32 10 <nl> + / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % . valueWitnesses , i32 8 <nl> / / CHECK : [ [ FLAGSWITNESS : % . * ] ] = load i8 * , i8 * * [ [ FLAGS_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ FLAGSWITNESS ] ] to i { { . * } } <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { . * } } [ [ FLAGS ] ] , 131072 <nl> bb0 : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * % 0 to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { . * } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ SIZE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ SIZE_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ SIZEWITNESS : % . * ] ] = load i8 * , i8 * * [ [ SIZE_ADDR ] ] <nl> / / CHECK : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ SIZEWITNESS ] ] <nl> / / CHECK : [ [ ALIGN : % . * ] ] = and { { . * } } [ [ FLAGS ] ] , 65535 <nl> bb0 : <nl> / / CHECK : [ [ CAST : % . * ] ] = bitcast % swift . type * % 0 to i8 * * * <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ CAST ] ] , { { . * } } - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % . valueWitnesses , i32 10 <nl> + / / CHECK : [ [ FLAGS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * % . valueWitnesses , i32 8 <nl> / / CHECK : [ [ FLAGSWITNESS : % . * ] ] = load i8 * , i8 * * [ [ FLAGS_ADDR ] ] <nl> / / CHECK : [ [ FLAGS : % . * ] ] = ptrtoint i8 * [ [ FLAGSWITNESS ] ] to i { { . * } } <nl> / / CHECK : [ [ ISNOTINLINE : % . * ] ] = and { { . * } } [ [ FLAGS ] ] , 131072 <nl> mmm a / test / IRGen / globals . swift <nl> ppp b / test / IRGen / globals . swift <nl> extension A { <nl> / / CHECK : [ [ FLOAT : % . * ] ] = type < { float } > <nl> <nl> / / CHECK - NOT : TY8 <nl> + / / CHECK - NOT : TY9 <nl> <nl> / / CHECK : @ _T07globals2g0Sivp = hidden global [ [ INT ] ] zeroinitializer , align 8 <nl> / / CHECK : @ _T07globals2g1yt_Siyttvp = hidden global < { [ [ INT ] ] } > zeroinitializer , align 8 <nl> mmm a / test / IRGen / indexing . sil <nl> ppp b / test / IRGen / indexing . sil <nl> entry ( % p : $ * ( ) , % i : $ Builtin . Word ) : <nl> / / CHECK : % 3 = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK - NEXT : % 4 = getelementptr inbounds i8 * * , i8 * * * % 3 , i64 - 1 <nl> / / CHECK - NEXT : % T . valueWitnesses = load i8 * * , i8 * * * % 4 , align 8 <nl> - / / CHECK - NEXT : % 5 = getelementptr inbounds i8 * , i8 * * % T . valueWitnesses , i32 11 <nl> + / / CHECK - NEXT : % 5 = getelementptr inbounds i8 * , i8 * * % T . valueWitnesses , i32 9 <nl> / / CHECK - NEXT : % 6 = load i8 * , i8 * * % 5 , align 8 <nl> / / CHECK - NEXT : % stride = ptrtoint i8 * % 6 to i64 <nl> / / CHECK - NEXT : % 7 = mul nsw i64 % 1 , % stride <nl> mmm a / test / IRGen / lifetime . sil <nl> ppp b / test / IRGen / lifetime . sil <nl> bb0 ( % x : $ * T ) : <nl> / / CHECK : [ [ TYPE_ADDR : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK - NEXT : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TYPE_ADDR ] ] , { { ( i32 | i64 ) } } - 1 <nl> / / CHECK - NEXT : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK - NEXT : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK - NEXT : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK - NEXT : [ [ SIZE_WITNESS : % . * ] ] = load i8 * , i8 * * [ [ SIZE_WITNESS_ADDR ] ] <nl> / / CHECK - NEXT : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ SIZE_WITNESS ] ] <nl> / / CHECK - NEXT : [ [ Y_ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ SIZE ] ] , align 16 <nl> bb0 ( % x : $ * T ) : <nl> / / CHECK : [ [ TYPE_ADDR : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK - NEXT : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ TYPE_ADDR ] ] , { { ( i32 | i64 ) } } - 1 <nl> / / CHECK - NEXT : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> - / / CHECK - NEXT : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK - NEXT : [ [ SIZE_WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK - NEXT : [ [ SIZE_WITNESS : % . * ] ] = load i8 * , i8 * * [ [ SIZE_WITNESS_ADDR ] ] <nl> / / CHECK - NEXT : [ [ SIZE : % . * ] ] = ptrtoint i8 * [ [ SIZE_WITNESS ] ] <nl> / / CHECK - NEXT : [ [ Y_ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ SIZE ] ] , align 16 <nl> mmm a / test / IRGen / partial_apply . sil <nl> ppp b / test / IRGen / partial_apply . sil <nl> sil public_external @ captured_fixed_and_dependent_params : $ @ convention ( thin ) < A <nl> / / CHECK : [ [ T_METADATA_BASE : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK : [ [ T_VWTABLE_ADDR : % . * ] ] = getelementptr { { . * } } [ [ T_METADATA_BASE ] ] , [ [ WORD : i [ 0 - 9 ] + ] ] - 1 <nl> / / CHECK : [ [ T_VWTABLE : % . * ] ] = load { { . * } } [ [ T_VWTABLE_ADDR ] ] <nl> - / / CHECK : [ [ T_FLAGS_ADDR : % . * ] ] = getelementptr { { . * } } [ [ T_VWTABLE ] ] , i32 10 <nl> + / / CHECK : [ [ T_FLAGS_ADDR : % . * ] ] = getelementptr { { . * } } [ [ T_VWTABLE ] ] , i32 8 <nl> / / CHECK : [ [ T_FLAGS_PTR : % . * ] ] = load { { . * } } [ [ T_FLAGS_ADDR ] ] <nl> / / CHECK : [ [ T_FLAGS : % . * ] ] = ptrtoint { { . * } } [ [ T_FLAGS_PTR ] ] to [ [ WORD ] ] <nl> / / CHECK : [ [ T_ALIGN_MASK : % . * ] ] = and [ [ WORD ] ] [ [ T_FLAGS ] ] , 65535 <nl> sil public_external @ captured_fixed_and_dependent_params : $ @ convention ( thin ) < A <nl> / / CHECK : [ [ T_OFFSET : % . * ] ] = and [ [ WORD ] ] [ [ T_UP_TO_ALIGN_1 ] ] , [ [ T_ALIGN_MASK_NOT ] ] <nl> <nl> / / - - Add the size of T to start the Int field . <nl> - / / CHECK : [ [ T_SIZE_ADDR : % . * ] ] = getelementptr { { . * } } [ [ T_VWTABLE ] ] , i32 9 <nl> + / / CHECK : [ [ T_SIZE_ADDR : % . * ] ] = getelementptr { { . * } } [ [ T_VWTABLE ] ] , i32 7 <nl> / / CHECK : [ [ T_SIZE_PTR : % . * ] ] = load { { . * } } [ [ T_SIZE_ADDR ] ] <nl> / / CHECK : [ [ T_SIZE : % . * ] ] = ptrtoint { { . * } } [ [ T_SIZE_PTR ] ] to [ [ WORD ] ] <nl> / / CHECK : [ [ T_END : % . * ] ] = add [ [ WORD ] ] [ [ T_OFFSET ] ] , [ [ T_SIZE ] ] <nl> mmm a / test / IRGen / struct_resilience . swift <nl> ppp b / test / IRGen / struct_resilience . swift <nl> public func functionWithResilientTypes ( _ s : Size , f : ( Size ) - > Size ) - > Size { <nl> / / CHECK : [ [ VWT_ADDR : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ METADATA_ADDR ] ] , [ [ INT ] ] - 1 <nl> / / CHECK : [ [ VWT : % . * ] ] = load i8 * * , i8 * * * [ [ VWT_ADDR ] ] <nl> <nl> - / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 9 <nl> + / / CHECK : [ [ WITNESS_ADDR : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VWT ] ] , i32 7 <nl> / / CHECK : [ [ WITNESS : % . * ] ] = load i8 * , i8 * * [ [ WITNESS_ADDR ] ] <nl> / / CHECK : [ [ WITNESS_FOR_SIZE : % . * ] ] = ptrtoint i8 * [ [ WITNESS ] ] <nl> / / CHECK : [ [ ALLOCA : % . * ] ] = alloca i8 , { { . * } } [ [ WITNESS_FOR_SIZE ] ] , align 16 <nl> mmm a / test / IRGen / type_layout . swift <nl> ppp b / test / IRGen / type_layout . swift <nl> struct TypeLayoutTest < T > { <nl> / / CHECK : [ [ T0 : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] , { { i32 | i64 } } - 1 <nl> / / CHECK : [ [ T_VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ T_LAYOUT ] ] <nl> var z : T <nl> / / - - native class , use standard NativeObject value witness <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoWV , i32 7 ) <nl> var a : C <nl> / / - - Single - element struct , shares layout of its field ( Builtin . Int64 ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 7 ) <nl> var c : SSing <nl> / / - - Multi - element structs use open - coded layouts <nl> / / CHECK : store i8 * * getelementptr inbounds ( [ 3 x i8 * ] , [ 3 x i8 * ] * @ type_layout_16_8_0_pod , i32 0 , i32 0 ) <nl> struct TypeLayoutTest < T > { <nl> / / CHECK - 32 : store i8 * * getelementptr inbounds ( [ 4 x i8 * ] , [ 4 x i8 * ] * @ type_layout_8_4_ [ [ REF_XI ] ] _bt , i32 0 , i32 0 ) <nl> var f : SMult3 <nl> / / - - Single - case enum , shares layout of its field ( Builtin . Int64 ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 7 ) <nl> var g : ESing <nl> / / - - Multi - case enum , open - coded layout <nl> / / CHECK : store i8 * * getelementptr inbounds ( [ 3 x i8 * ] , [ 3 x i8 * ] * @ type_layout_9_8_0_pod , i32 0 , i32 0 ) <nl> var h : EMult <nl> / / - - Single - element generic struct , shares layout of its field ( T ) <nl> - / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ T_LAYOUT ] ] <nl> var i : GSing < T > <nl> / / - - Multi - element generic struct , need to derive from metadata <nl> struct TypeLayoutTest < T > { <nl> / / CHECK : [ [ T0 : % . * ] ] = bitcast % swift . type * [ [ METADATA ] ] to i8 * * * <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] , { { i32 | i64 } } - 1 <nl> / / CHECK : [ [ VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ LAYOUT ] ] <nl> var j : GMult < T > <nl> / / - - Common layout , reuse common value witness table layout <nl> - / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi32_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi32_WV , i32 7 ) <nl> var k : CommonLayout <nl> / / - - Single - field aggregate with alignment <nl> - / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi128_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi128_WV , i32 7 ) <nl> var l : AlignedFourInts <nl> } <nl> mmm a / test / IRGen / type_layout_objc . swift <nl> ppp b / test / IRGen / type_layout_objc . swift <nl> struct TypeLayoutTest < T > { <nl> / / CHECK : [ [ T0 : % . * ] ] = bitcast % swift . type * % T to i8 * * * <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] , { { i32 | i64 } } - 1 <nl> / / CHECK : [ [ T_VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ T_LAYOUT ] ] <nl> var z : T <nl> / / - - native class , use standard NativeObject value witness <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoWV , i32 7 ) <nl> var a : C <nl> / / - - ObjC class , use standard UnknownObject value witness <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOWV , i32 7 ) <nl> var b : O <nl> / / - - Single - element struct , shares layout of its field ( Builtin . Int64 ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 7 ) <nl> var c : SSing <nl> / / - - Multi - element structs use open - coded layouts <nl> / / CHECK : store i8 * * getelementptr inbounds ( [ 3 x i8 * ] , [ 3 x i8 * ] * @ type_layout_16_8_0_pod , i32 0 , i32 0 ) <nl> struct TypeLayoutTest < T > { <nl> / / CHECK - 32 : store i8 * * getelementptr inbounds ( [ 4 x i8 * ] , [ 4 x i8 * ] * @ type_layout_8_4_1000_bt , i32 0 , i32 0 ) <nl> var f : SMult3 <nl> / / - - Single - case enum , shares layout of its field ( Builtin . Int64 ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0Bi64_WV , i32 7 ) <nl> var g : ESing <nl> / / - - Multi - case enum , open - coded layout <nl> / / CHECK : store i8 * * getelementptr inbounds ( [ 3 x i8 * ] , [ 3 x i8 * ] * @ type_layout_9_8_0_pod , i32 0 , i32 0 ) <nl> var h : EMult <nl> / / - - Single - element generic struct , shares layout of its field ( T ) <nl> - / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ T_LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ T_VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ T_LAYOUT ] ] <nl> var i : GSing < T > <nl> / / - - Multi - element generic struct , need to derive from metadata <nl> struct TypeLayoutTest < T > { <nl> / / CHECK : [ [ T0 : % . * ] ] = bitcast % swift . type * [ [ METADATA ] ] to i8 * * * <nl> / / CHECK : [ [ T1 : % . * ] ] = getelementptr inbounds i8 * * , i8 * * * [ [ T0 ] ] , { { i32 | i64 } } - 1 <nl> / / CHECK : [ [ VALUE_WITNESSES : % . * ] ] = load i8 * * , i8 * * * [ [ T1 ] ] <nl> - / / CHECK : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 9 <nl> + / / CHECK : [ [ LAYOUT : % . * ] ] = getelementptr inbounds i8 * , i8 * * [ [ VALUE_WITNESSES ] ] , i32 7 <nl> / / CHECK : store i8 * * [ [ LAYOUT ] ] <nl> var j : GMult < T > <nl> / / - - Common layout , reuse common value witness table layout <nl> - / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi32_WV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr ( i8 * , i8 * * @ _T0Bi32_WV , i32 7 ) <nl> var k : CommonLayout <nl> } <nl> mmm a / test / IRGen / type_layout_reference_storage . swift <nl> ppp b / test / IRGen / type_layout_reference_storage . swift <nl> struct ReferenceStorageTypeLayout < T , Native : C , Unknown : AnyObject > { <nl> var z : T <nl> <nl> / / - - Known - Swift - refcounted type <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 7 ) <nl> unowned ( safe ) var cs : C <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var cu : C <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var cwo : C ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var cwi : C ! <nl> <nl> / / - - Known - Swift - refcounted archetype <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 7 ) <nl> unowned ( safe ) var nc : Native <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var nu : Native <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var nwo : Native ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var nwi : Native ! <nl> <nl> / / - - Open - code layout for protocol types with witness tables . <nl> struct ReferenceStorageTypeLayout < T , Native : C , Unknown : AnyObject > { <nl> weak var pqcwi : ( P & Q & C ) ! <nl> <nl> / / - - Unknown - refcounted existential without witness tables . <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN : B [ Oo ] ] ] XoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN : B [ Oo ] ] ] XoWV , i32 7 ) <nl> unowned ( safe ) var aos : AnyObject <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var aou : AnyObject <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 7 ) <nl> weak var aowo : AnyObject ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 7 ) <nl> weak var aowi : AnyObject ! <nl> <nl> / / - - Unknown - refcounted archetype <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN : B [ Oo ] ] ] XoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN : B [ Oo ] ] ] XoWV , i32 7 ) <nl> unowned ( safe ) var us : Unknown <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var uu : Unknown <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 7 ) <nl> weak var uwo : Unknown ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0 [ [ UNKNOWN ] ] SgXwWV , i32 7 ) <nl> weak var uwi : Unknown ! <nl> } <nl> mmm a / test / IRGen / type_layout_reference_storage_objc . swift <nl> ppp b / test / IRGen / type_layout_reference_storage_objc . swift <nl> struct ReferenceStorageTypeLayout < T , ObjC : C > { <nl> var z : T <nl> <nl> / / - - ObjC - refcounted class <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 7 ) <nl> unowned ( safe ) var cs : C <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var cu : C <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var cwo : C ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var cwi : C ! <nl> <nl> / / - - ObjC - refcounted archetype <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 7 ) <nl> unowned ( safe ) var os : ObjC <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var ou : ObjC <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var owo : ObjC ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var owi : ObjC ! <nl> <nl> / / - - Pure ObjC protocols are unknown - refcounted <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 7 ) <nl> unowned ( safe ) var ps : P <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var pu : P <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var pwo : P ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var pwi : P ! <nl> <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOXoWV , i32 7 ) <nl> unowned ( safe ) var pqs : P & Q <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var pqu : P & Q <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var pqwo : ( P & Q ) ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BOSgXwWV , i32 7 ) <nl> weak var pqwi : ( P & Q ) ! <nl> <nl> / / - - Composition with ObjC protocol and native class is native - refcounted <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoXoWV , i32 7 ) <nl> unowned ( safe ) var pncs : ( P & NativeClass ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BomWV , i32 7 ) <nl> unowned ( unsafe ) var pncu : ( P & NativeClass ) <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var pncwo : ( P & NativeClass ) ? <nl> - / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 9 ) <nl> + / / CHECK : store i8 * * getelementptr inbounds ( i8 * , i8 * * @ _T0BoSgXwWV , i32 7 ) <nl> weak var pncwi : ( P & NativeClass ) ! <nl> <nl> / / - - Open - code layouts when there are witness tables . <nl> | Merge pull request from aschwaighofer / revert_enum_witness | apple/swift | 3b9752e1a3d131b9190f87fe8fd9b038e56b59d9 | 2017-10-31T17:48:20Z |
mmm a / src / embind / embind . js <nl> ppp b / src / embind / embind . js <nl> function __embind_register_memory_view ( rawType , name ) { <nl> var type = HEAPU32 [ handle > > 2 ] ; <nl> var size = HEAPU32 [ ( handle > > 2 ) + 1 ] ; / / in elements <nl> var data = HEAPU32 [ ( handle > > 2 ) + 2 ] ; / / byte offset into emscripten heap <nl> - _free ( handle ) ; <nl> var TA = typeMapping [ type ] ; <nl> return new TA ( HEAP8 . buffer , data , size ) ; <nl> } , <nl> - destructorFunction : function ( ptr ) { _free ( ptr ) ; } , <nl> } ) ; <nl> } <nl> <nl> mmm a / system / include / emscripten / wire . h <nl> ppp b / system / include / emscripten / wire . h <nl> namespace emscripten { <nl> namespace internal { <nl> template < > <nl> struct BindingType < memory_view > { <nl> - typedef memory_view * WireType ; <nl> + / / This non - word - sized WireType only works because I <nl> + / / happen to know that clang will pass aggregates as <nl> + / / pointers to stack elements and we never support <nl> + / / converting JavaScript typed arrays back into <nl> + / / memory_view . ( That is , fromWireType is not implemented <nl> + / / on the C + + side , nor is toWireType implemented in <nl> + / / JavaScript . ) <nl> + typedef memory_view WireType ; <nl> static WireType toWireType ( const memory_view & mv ) { <nl> - WireType wt = ( WireType ) malloc ( sizeof ( memory_view ) ) ; <nl> - new ( wt ) memory_view ( mv ) ; <nl> - return wt ; <nl> + return mv ; <nl> } <nl> } ; <nl> } <nl> | We can get away with passing memory_view on the stack here . . . | emscripten-core/emscripten | 69d3621782e4b6dc131a2e5d78fdcf92047d667c | 2013-05-17T19:57:10Z |
mmm a / lib / IRGen / IRGenMangler . cpp <nl> ppp b / lib / IRGen / IRGenMangler . cpp <nl> IRGenMangler : : mangleTypeForReflection ( IRGenModule & IGM , <nl> llvm : : SaveAndRestore < std : : function < bool ( const DeclContext * ) > > <nl> SymbolicReferencesForLocalTypes ( CanSymbolicReference ) ; <nl> <nl> - if ( ( ! IGM . CurSourceFile | | ! isa < ClangModuleUnit > ( IGM . CurSourceFile ) ) <nl> + if ( IGM . CurSourceFile <nl> + & & ! isa < ClangModuleUnit > ( IGM . CurSourceFile ) <nl> & & ! IGM . getOptions ( ) . IntegratedREPL ) { <nl> CanSymbolicReference = [ & ] ( const DeclContext * dc ) - > bool { <nl> - / / Can only symbolically reference nominal type declarations . <nl> - auto nominal = dyn_cast < NominalTypeDecl > ( dc ) ; <nl> - if ( ! nominal | | isa < ProtocolDecl > ( dc ) ) <nl> - return false ; <nl> - <nl> / / Symbolically reference types that are defined in the same file unit <nl> / / as we ' re referencing from . <nl> - if ( IGM . CurSourceFile & & <nl> - dc - > getModuleScopeContext ( ) = = IGM . CurSourceFile ) <nl> - return true ; <nl> - <nl> - / / fileprivate and private entities are always in the same file unit <nl> - / / that they ' re referenced from . <nl> - if ( nominal - > getEffectiveAccess ( ) < AccessLevel : : Internal ) <nl> - return true ; <nl> - <nl> - / / FIXME : We could eventually improve this to reference any type that ends <nl> + / / <nl> + / / We could eventually improve this to reference any type that ends <nl> / / up with its nominal type descriptor in the same linked binary as us , <nl> / / but IRGen doesn ' t know that with much certainty currently . <nl> - return false ; <nl> + return dc - > getModuleScopeContext ( ) = = IGM . CurSourceFile <nl> + & & isa < NominalTypeDecl > ( dc ) <nl> + & & ! isa < ProtocolDecl > ( dc ) ; <nl> } ; <nl> } <nl> <nl> mmm a / test / IRGen / associated_type_witness . swift <nl> ppp b / test / IRGen / associated_type_witness . swift <nl> protocol Assocked { <nl> <nl> struct Universal : P , Q { } <nl> <nl> - <nl> - / / CHECK - LABEL : @ " symbolic \ 01____ 23associated_type_witness12OuterPrivate { { . * } } V " = linkonce_odr hidden constant <nl> - / / CHECK - SAME : @ " $ s23associated_type_witness12OuterPrivate { { . * } } 5InnerE0V9InnermostVMn " <nl> - private struct OuterPrivate { <nl> - struct InnerPrivate : HasSimpleAssoc { <nl> - struct Innermost { } <nl> - typealias Assoc = Innermost <nl> - } <nl> - } <nl> - <nl> / / CHECK : [ [ ASSOC_TYPE_NAMES : @ . * ] ] = private constant [ 29 x i8 ] c " OneAssoc TwoAssoc ThreeAssoc \ 00 " <nl> / / CHECK : @ " $ s23associated_type_witness18HasThreeAssocTypesMp " = <nl> / / CHECK - SAME : [ [ ASSOC_TYPE_NAMES ] ] to i64 <nl> protocol HasSimpleAssoc { <nl> } <nl> protocol DerivedFromSimpleAssoc : HasSimpleAssoc { } <nl> <nl> + <nl> / / Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc . <nl> / / GLOBAL - LABEL : @ " $ s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWp " = internal constant [ 2 x i8 * ] <nl> / / GLOBAL - SAME : @ " $ s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc " <nl> deleted file mode 100644 <nl> index fb20f8aaaace . . 000000000000 <nl> mmm a / test / Runtime / associated_type_demangle_private . swift <nl> ppp / dev / null <nl> <nl> - / / RUN : % empty - directory ( % t ) <nl> - / / RUN : % target - build - swift - parse - stdlib % s - module - name main - o % t / a . out <nl> - / / RUN : % target - codesign % t / a . out <nl> - / / RUN : % target - run % t / a . out <nl> - / / REQUIRES : executable_test <nl> - <nl> - import Swift <nl> - import StdlibUnittest <nl> - <nl> - protocol P { <nl> - associatedtype A <nl> - } <nl> - <nl> - fileprivate struct Foo { <nl> - fileprivate struct Inner : P { <nl> - fileprivate struct Innermost { } <nl> - typealias A = Innermost <nl> - } <nl> - } <nl> - <nl> - func getP_A < T : P > ( _ : T . Type ) - > Any . Type { <nl> - return T . A . self <nl> - } <nl> - <nl> - let AssociatedTypeDemangleTests = TestSuite ( " AssociatedTypeDemangle " ) <nl> - <nl> - <nl> - AssociatedTypeDemangleTests . test ( " private types " ) { <nl> - expectEqual ( Foo . Inner . Innermost . self , getP_A ( Foo . Inner . self ) ) <nl> - } <nl> - <nl> - runAllTests ( ) <nl> | Revert " [ IRGen ] Use symbolic references to ( file ) private entities in mangled names " | apple/swift | 46b105e4d6093058ee72349ab52d391e0433b9a8 | 2018-10-13T11:56:02Z |
mmm a / mars / libraries / build_android . py <nl> ppp b / mars / libraries / build_android . py <nl> def build_android_mars_shared_libs ( _path = " mars_android_sdk " ) : <nl> <nl> def choose_android_mars_jni_arch ( ) : <nl> platforms = [ ' armeabi ' , ' x86 ' , ' mips ' , ' armeabi - v7a ' , ' arm64 - v8a ' , ' x86_64 ' , ' mips64 ' ] <nl> - archnum = raw_input ( " Enter the architecture which would like to build , support multi - selection which should be separated by comma ( ' , ' ) : \ n1 . armeabi . \ n2 . x86 . \ n3 . mips . \ n4 . armeabi - v7a . \ n5 . arm64 - v8a . \ n6 . x86_64 . \ n7 . mips64 . \ n " ) <nl> + archnum = raw_input ( " Enter the architecture which would like to build , support multi - selection which should be separated by comma ( ' , ' ) : \ n1 . armeabi . \ n2 . x86 . \ n3 . mips . \ n4 . armeabi - v7a . \ n5 . arm64 - v8a . \ n6 . x86_64 . \ n7 . mips64 . \ n8 . exit . \ n " ) <nl> arr = [ ] <nl> if " 8 " = = archnum : <nl> - arr . append ( ' all ' ) <nl> + arr . append ( ' exit ' ) <nl> elif len ( archnum ) > = 3 : <nl> archs = archnum . split ( ' , ' ) <nl> for i in range ( 0 , len ( archs ) ) : <nl> def choose_android_mars_jni_arch ( ) : <nl> arr . append ( platforms [ int ( archnum ) - 1 ] ) <nl> else : <nl> arr . append ( ' err ' ) <nl> - print ( arr ) <nl> return arr <nl> <nl> def main ( ) : <nl> def main ( ) : <nl> elif " 2 " = = num : <nl> if arch [ 0 ] = = ' err ' : <nl> return <nl> - elif arch [ 0 ] = = ' all ' : <nl> - arch = [ ' armeabi ' , ' x86 ' , ' mips ' , ' armeabi - v7a ' , ' arm64 - v8a ' , ' x86_64 ' , ' mips64 ' ] <nl> - if os . path . exists ( ' mars_android_sdk / so_cache ' ) : <nl> - shutil . rmtree ( ' mars_android_sdk / so_cache ' , True ) <nl> - os . mkdir ( ' mars_android_sdk / so_cache ' ) <nl> - for i in range ( 0 , len ( arch ) ) : <nl> - global NDK_BUILD_CMD <nl> - NDK_BUILD_CMD = " ndk - build _ARCH_ = " + arch [ i ] + " NDK_DEBUG = 0 - j - B SDK = 0 LIBPREFIX = mars - C " <nl> - print ( NDK_BUILD_CMD ) <nl> - build_android_mars_shared_libs ( ) <nl> - if i ! = ( len ( arch ) - 1 ) : <nl> - libs_dir = ' mars_android_sdk / so_cache / ' + arch [ i ] ; <nl> - symbols_dir = ' mars_android_sdk / so_cache / symbol / ' + arch [ i ] ; <nl> - if not os . path . exists ( ' mars_android_sdk / so_cache / symbol / ' ) : <nl> - os . mkdir ( ' mars_android_sdk / so_cache / symbol / ' ) <nl> - os . mkdir ( libs_dir ) <nl> - os . mkdir ( symbols_dir ) <nl> - for lib in glob . glob ( " mars_android_sdk / obj / local / " + arch [ i ] + " / * . so " ) : <nl> - shutil . copy ( lib , symbols_dir ) <nl> - for lib in glob . glob ( " mars_android_sdk / libs / " + arch [ i ] + " / * . so " ) : <nl> - shutil . copy ( lib , libs_dir ) <nl> - for i in range ( 0 , len ( arch ) - 1 ) : <nl> - shutil . copytree ( ' mars_android_sdk / so_cache / ' + arch [ i ] , ' mars_android_sdk / libs / ' + arch [ i ] ) <nl> - shutil . copytree ( ' mars_android_sdk / so_cache / symbol / ' + arch [ i ] , ' mars_android_sdk / obj / local / ' + arch [ i ] ) <nl> + elif arch [ 0 ] = = ' exit ' : <nl> return <nl> else : <nl> if os . path . exists ( ' mars_android_sdk / so_cache ' ) : <nl> shutil . rmtree ( ' mars_android_sdk / so_cache ' , True ) <nl> os . mkdir ( ' mars_android_sdk / so_cache ' ) <nl> for i in range ( 0 , len ( arch ) ) : <nl> - global NDK_BUILD_CMD <nl> NDK_BUILD_CMD = " ndk - build _ARCH_ = " + arch [ i ] + " NDK_DEBUG = 0 - j - B SDK = 0 LIBPREFIX = mars - C " <nl> print ( NDK_BUILD_CMD ) <nl> build_android_mars_shared_libs ( ) <nl> def main ( ) : <nl> elif " 4 " = = num : <nl> if arch [ 0 ] = = ' err ' : <nl> return <nl> - elif arch [ 0 ] = = ' all ' : <nl> - arch = [ ' armeabi ' , ' x86 ' , ' mips ' , ' armeabi - v7a ' , ' arm64 - v8a ' , ' x86_64 ' , ' mips64 ' ] <nl> - if os . path . exists ( ' mars_xlog_sdk / so_cache ' ) : <nl> - shutil . rmtree ( ' mars_xlog_sdk / so_cache ' , True ) <nl> - os . mkdir ( ' mars_xlog_sdk / so_cache ' ) <nl> - for i in range ( 0 , len ( arch ) ) : <nl> - global NDK_BUILD_CMD <nl> - NDK_BUILD_CMD = " ndk - build _ARCH_ = " + arch [ i ] + " NDK_DEBUG = 0 - j - B SDK = 0 LIBPREFIX = mars - C " <nl> - print ( NDK_BUILD_CMD ) <nl> - build_android_xlog_shared_libs ( ) <nl> - if i ! = ( len ( arch ) - 1 ) : <nl> - libs_dir = ' mars_xlog_sdk / so_cache / ' + arch [ i ] ; <nl> - symbols_dir = ' mars_xlog_sdk / so_cache / symbol / ' + arch [ i ] ; <nl> - if not os . path . exists ( ' mars_xlog_sdk / so_cache / symbol / ' ) : <nl> - os . mkdir ( ' mars_xlog_sdk / so_cache / symbol / ' ) <nl> - os . mkdir ( libs_dir ) <nl> - os . mkdir ( symbols_dir ) <nl> - for lib in glob . glob ( " mars_xlog_sdk / obj / local / " + arch [ i ] + " / * . so " ) : <nl> - shutil . copy ( lib , symbols_dir ) <nl> - for lib in glob . glob ( " mars_xlog_sdk / libs / " + arch [ i ] + " / * . so " ) : <nl> - shutil . copy ( lib , libs_dir ) <nl> - for i in range ( 0 , len ( arch ) - 1 ) : <nl> - shutil . copytree ( ' mars_xlog_sdk / so_cache / ' + arch [ i ] , ' mars_xlog_sdk / libs / ' + arch [ i ] ) <nl> - shutil . copytree ( ' mars_xlog_sdk / so_cache / symbol / ' + arch [ i ] , ' mars_xlog_sdk / obj / local / ' + arch [ i ] ) <nl> + elif arch [ 0 ] = = ' exit ' : <nl> return <nl> else : <nl> if os . path . exists ( ' mars_xlog_sdk / so_cache ' ) : <nl> shutil . rmtree ( ' mars_xlog_sdk / so_cache ' , True ) <nl> os . mkdir ( ' mars_xlog_sdk / so_cache ' ) <nl> for i in range ( 0 , len ( arch ) ) : <nl> - global NDK_BUILD_CMD <nl> NDK_BUILD_CMD = " ndk - build _ARCH_ = " + arch [ i ] + " NDK_DEBUG = 0 - j - B SDK = 0 LIBPREFIX = mars - C " <nl> print ( NDK_BUILD_CMD ) <nl> build_android_xlog_shared_libs ( ) <nl> | remove build all and fix syntaxwarning in python script | Tencent/mars | 2b87cceec445b649b5c0190c119e9cbb30e5dc85 | 2016-12-29T14:32:28Z |
mmm a / xbmc / cores / AudioEngine / Sinks / AESinkDARWINOSX . cpp <nl> ppp b / xbmc / cores / AudioEngine / Sinks / AESinkDARWINOSX . cpp <nl> static void EnumerateDevices ( CADeviceList & list ) <nl> / / we rather might need the concatination of all streams * sucks * <nl> if ( defaultDeviceName = = devEnum . GetMasterDeviceName ( ) ) <nl> { <nl> + struct CADeviceInstance deviceInstance ; <nl> + deviceInstance . audioDeviceId = deviceID ; <nl> + deviceInstance . streamIndex = INT_MAX ; / / don ' t limit streamidx for the raw device <nl> + deviceInstance . sourceId = INT_MAX ; <nl> CAEDeviceInfo firstDevice = listForDevice . front ( ) . second ; <nl> firstDevice . m_deviceName = " default " ; <nl> firstDevice . m_displayName = " Default " ; <nl> - firstDevice . m_displayNameExtra = " " ; <nl> - list . insert ( list . begin ( ) , std : : make_pair ( deviceID , firstDevice ) ) ; <nl> + firstDevice . m_displayNameExtra = defaultDeviceName ; <nl> + list . insert ( list . begin ( ) , std : : make_pair ( deviceInstance , firstDevice ) ) ; <nl> } <nl> <nl> deviceIDList . pop_front ( ) ; <nl> OSStatus deviceChangedCB ( AudioObjectID inObjectID , <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> CAESinkDARWINOSX : : CAESinkDARWINOSX ( ) <nl> : m_latentFrames ( 0 ) , <nl> + m_outputBufferIndex ( 0 ) , <nl> m_outputBitstream ( false ) , <nl> m_planes ( 1 ) , <nl> m_frameSizePerPlane ( 0 ) , <nl> CAESinkDARWINOSX : : ~ CAESinkDARWINOSX ( ) <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> { <nl> AudioDeviceID deviceID = 0 ; <nl> + UInt32 requestedStreamIndex = INT_MAX ; <nl> + UInt32 requestedSourceId = INT_MAX ; <nl> + <nl> CADeviceList devices = GetDevices ( ) ; <nl> if ( StringUtils : : EqualsNoCase ( device , " default " ) ) <nl> { <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> { <nl> for ( size_t i = 0 ; i < devices . size ( ) ; i + + ) <nl> { <nl> - if ( device . find ( devices [ i ] . second . m_deviceName ) ! = std : : string : : npos ) <nl> + if ( device = = devices [ i ] . second . m_deviceName ) <nl> { <nl> - deviceID = devices [ i ] . first ; <nl> + const struct CADeviceInstance & deviceInstance = devices [ i ] . first ; <nl> + deviceID = deviceInstance . audioDeviceId ; <nl> + requestedStreamIndex = deviceInstance . streamIndex ; <nl> + requestedSourceId = deviceInstance . sourceId ; <nl> + if ( requestedStreamIndex ! = INT_MAX ) <nl> + CLog : : Log ( LOGNOTICE , " % s pseudo device - requesting stream % d " , __FUNCTION__ , ( unsigned int ) requestedStreamIndex ) ; <nl> + if ( requestedSourceId ! = INT_MAX ) <nl> + CLog : : Log ( LOGNOTICE , " % s device - requesting audiosource % d " , __FUNCTION__ , ( unsigned int ) requestedSourceId ) ; <nl> break ; <nl> } <nl> } <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> AEDeviceEnumerationOSX devEnum ( deviceID ) ; <nl> AudioStreamBasicDescription outputFormat = { 0 } ; <nl> AudioStreamID outputStream = 0 ; <nl> - UInt32 streamIdx = 0 ; <nl> UInt32 numOutputChannels = 0 ; <nl> EPassthroughMode passthrough = PassthroughModeNone ; <nl> m_planes = 1 ; <nl> - if ( devEnum . FindSuitableFormatForStream ( streamIdx , format , outputFormat , passthrough , outputStream ) ) <nl> + / / after FindSuitableFormatForStream requestedStreamIndex will have a valid index and no INT_MAX anymore . . . <nl> + if ( devEnum . FindSuitableFormatForStream ( requestedStreamIndex , format , outputFormat , passthrough , outputStream ) ) <nl> { <nl> numOutputChannels = outputFormat . mChannelsPerFrame ; <nl> <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> / * Update our AE format * / <nl> format . m_sampleRate = outputFormat . mSampleRate ; <nl> <nl> + m_outputBufferIndex = requestedStreamIndex ; <nl> m_outputBitstream = passthrough = = PassthroughModeBitstream ; <nl> <nl> std : : string formatString ; <nl> - CLog : : Log ( LOGDEBUG , " % s : Selected stream [ % u ] - id : 0x % 04X , Physical Format : % s % s " , __FUNCTION__ , ( unsigned int ) 0 , ( unsigned int ) outputStream , StreamDescriptionToString ( outputFormat , formatString ) , m_outputBitstream ? " bitstreamed passthrough " : " " ) ; <nl> + CLog : : Log ( LOGDEBUG , " % s : Selected stream [ % u ] - id : 0x % 04X , Physical Format : % s % s " , __FUNCTION__ , ( unsigned int ) m_outputBufferIndex , ( unsigned int ) outputStream , StreamDescriptionToString ( outputFormat , formatString ) , m_outputBitstream ? " bitstreamed passthrough " : " " ) ; <nl> <nl> m_device . Open ( deviceID ) ; <nl> SetHogMode ( passthrough ! = PassthroughModeNone ) ; <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> CLog : : Log ( LOGDEBUG , " % s : New Virtual Format : % s " , __FUNCTION__ , StreamDescriptionToString ( virtualFormat , formatString ) ) ; <nl> CLog : : Log ( LOGDEBUG , " % s : New Physical Format : % s " , __FUNCTION__ , StreamDescriptionToString ( outputFormat , formatString ) ) ; <nl> <nl> + if ( requestedSourceId ! = INT_MAX & & ! m_device . SetDataSource ( requestedSourceId ) ) <nl> + CLog : : Log ( LOGERROR , " % s : Error setting requested audio source . " , __FUNCTION__ ) ; <nl> + <nl> m_latentFrames = m_device . GetNumLatencyFrames ( ) ; <nl> m_latentFrames + = m_outputStream . GetNumLatencyFrames ( ) ; <nl> <nl> / / update the channel map based on the new stream format <nl> - devEnum . GetAEChannelMap ( format . m_channelLayout , numOutputChannels ) ; <nl> + if ( passthrough = = PassthroughModeNone ) <nl> + devEnum . GetAEChannelMap ( format . m_channelLayout , numOutputChannels ) ; <nl> <nl> / * TODO : Should we use the virtual format to determine our data format ? * / <nl> format . m_frameSize = format . m_channelLayout . Count ( ) * ( CAEUtil : : DataFormatToBits ( format . m_dataFormat ) > > 3 ) ; <nl> bool CAESinkDARWINOSX : : Initialize ( AEAudioFormat & format , std : : string & device ) <nl> m_buffer = new AERingBuffer ( num_buffers * format . m_frames * m_frameSizePerPlane , m_planes ) ; <nl> CLog : : Log ( LOGDEBUG , " % s : using buffer size : % u ( % f ms ) " , __FUNCTION__ , m_buffer - > GetMaxSize ( ) , ( float ) m_buffer - > GetMaxSize ( ) / ( m_framesPerSecond * m_frameSizePerPlane ) ) ; <nl> <nl> - if ( passthrough ! = PassthroughModeNone ) <nl> + if ( m_outputBitstream ) <nl> format . m_dataFormat = AE_FMT_S16NE ; <nl> - else <nl> + else if ( passthrough = = PassthroughModeNone ) <nl> format . m_dataFormat = ( m_planes > 1 ) ? AE_FMT_FLOATP : AE_FMT_FLOAT ; <nl> <nl> / / Register for data request callbacks from the driver and start <nl> void CAESinkDARWINOSX : : Deinitialize ( ) <nl> delete m_buffer ; <nl> m_buffer = NULL ; <nl> } <nl> + m_outputBufferIndex = 0 ; <nl> m_outputBitstream = false ; <nl> m_planes = 1 ; <nl> <nl> OSStatus CAESinkDARWINOSX : : renderCallback ( AudioDeviceID inDevice , const AudioTim <nl> sink - > m_started = true ; <nl> if ( outOutputData - > mNumberBuffers ) <nl> { <nl> + / / planar always starts at outputbuffer / streamidx 0 <nl> + unsigned int startIdx = sink - > m_buffer - > NumPlanes ( ) = = 1 ? sink - > m_outputBufferIndex : 0 ; <nl> + unsigned int endIdx = startIdx + sink - > m_buffer - > NumPlanes ( ) ; <nl> + <nl> / * NOTE : We assume that the buffers are all the same size . . . * / <nl> if ( sink - > m_outputBitstream ) <nl> { <nl> OSStatus CAESinkDARWINOSX : : renderCallback ( AudioDeviceID inDevice , const AudioTim <nl> size_t bytes = std : : min ( ( size_t ) sink - > m_buffer - > GetReadSize ( ) , wanted ) ; <nl> for ( unsigned int j = 0 ; j < bytes / sizeof ( int16_t ) ; j + + ) <nl> { <nl> - for ( unsigned int i = 0 ; i < sink - > m_buffer - > NumPlanes ( ) ; i + + ) <nl> + for ( unsigned int i = startIdx ; i < endIdx ; i + + ) <nl> { <nl> int16_t src ; <nl> sink - > m_buffer - > Read ( ( unsigned char * ) & src , sizeof ( int16_t ) , i ) ; <nl> OSStatus CAESinkDARWINOSX : : renderCallback ( AudioDeviceID inDevice , const AudioTim <nl> / * buffers appear to come from CA already zero ' d , so just copy what is wanted * / <nl> unsigned int wanted = outOutputData - > mBuffers [ 0 ] . mDataByteSize ; <nl> unsigned int bytes = std : : min ( sink - > m_buffer - > GetReadSize ( ) , wanted ) ; <nl> - for ( unsigned int i = 0 ; i < sink - > m_buffer - > NumPlanes ( ) ; i + + ) <nl> + for ( unsigned int i = startIdx ; i < endIdx ; i + + ) <nl> { <nl> if ( i < outOutputData - > mNumberBuffers & & outOutputData - > mBuffers [ i ] . mData ) <nl> sink - > m_buffer - > Read ( ( unsigned char * ) outOutputData - > mBuffers [ i ] . mData , bytes , i ) ; <nl> mmm a / xbmc / cores / AudioEngine / Sinks / AESinkDARWINOSX . h <nl> ppp b / xbmc / cores / AudioEngine / Sinks / AESinkDARWINOSX . h <nl> class CAESinkDARWINOSX : public IAESink <nl> CCoreAudioDevice m_device ; <nl> CCoreAudioStream m_outputStream ; <nl> unsigned int m_latentFrames ; <nl> + unsigned int m_outputBufferIndex ; <nl> <nl> bool m_outputBitstream ; / / / < true if we ' re bistreaming into a LinearPCM stream rather than AC3 stream . <nl> unsigned int m_planes ; / / / < number of audio planes ( 1 if non - planar ) <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / AEDeviceEnumerationOSX . cpp <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / AEDeviceEnumerationOSX . cpp <nl> CADeviceList AEDeviceEnumerationOSX : : GetDeviceInfoList ( ) const <nl> for ( UInt32 streamIdx = 0 ; streamIdx < numDevices ; streamIdx + + ) <nl> { <nl> CAEDeviceInfo deviceInfo ; <nl> + struct CADeviceInstance devInstance ; <nl> + devInstance . audioDeviceId = m_deviceID ; <nl> + devInstance . streamIndex = streamIdx ; <nl> + devInstance . sourceId = INT_MAX ; / / don ' t set audio source by default <nl> <nl> deviceInfo . m_deviceName = getDeviceNameForStream ( streamIdx ) ; <nl> deviceInfo . m_displayName = m_deviceName ; <nl> CADeviceList AEDeviceEnumerationOSX : : GetDeviceInfoList ( ) const <nl> deviceInfo . m_dataFormats = getFormatListForStream ( streamIdx ) ; <nl> deviceInfo . m_deviceType = m_caStreamInfos [ streamIdx ] . deviceType ; <nl> <nl> - list . push_back ( std : : make_pair ( m_deviceID , deviceInfo ) ) ; <nl> + CoreAudioDataSourceList sourceList ; <nl> + / / if this enumerator contains multiple devices with more then 1 source we add : source suffixes to the <nl> + / / device names and overwrite the extraname with the source name <nl> + if ( numDevices = = 1 & & m_caDevice . GetDataSources ( & sourceList ) & & sourceList . size ( ) > 1 ) <nl> + { <nl> + for ( unsigned sourceIdx = 0 ; sourceIdx < sourceList . size ( ) ; sourceIdx + + ) <nl> + { <nl> + std : : stringstream sourceIdxStr ; <nl> + sourceIdxStr < < sourceIdx ; <nl> + deviceInfo . m_deviceName = getDeviceNameForStream ( streamIdx ) + " : source " + sourceIdxStr . str ( ) ; <nl> + deviceInfo . m_displayNameExtra = m_caDevice . GetDataSourceName ( sourceList [ sourceIdx ] ) ; <nl> + devInstance . sourceId = sourceList [ sourceIdx ] ; <nl> + list . push_back ( std : : make_pair ( devInstance , deviceInfo ) ) ; <nl> + } <nl> + } <nl> + else <nl> + list . push_back ( std : : make_pair ( devInstance , deviceInfo ) ) ; <nl> } <nl> return list ; <nl> } <nl> CAEChannelInfo AEDeviceEnumerationOSX : : getChannelInfoForStream ( UInt32 streamIdx ) <nl> else <nl> { <nl> / / get channel map to match the devices channel layout as set in audio - midi - setup <nl> - GetAEChannelMap ( channelInfo , m_caDevice . GetTotalOutputChannels ( ) ) ; <nl> + GetAEChannelMap ( channelInfo , m_caDevice . GetNumChannelsOfStream ( streamIdx ) ) ; <nl> } <nl> return channelInfo ; <nl> } <nl> std : : string AEDeviceEnumerationOSX : : getDeviceNameForStream ( UInt32 streamIdx ) con <nl> } <nl> <nl> std : : string AEDeviceEnumerationOSX : : getExtraDisplayNameForStream ( UInt32 streamIdx ) const <nl> - { <nl> - std : : string extraDisplayName = " " ; <nl> - <nl> + { <nl> / / for distinguishing the streams inside one device we add <nl> - / / Stream < number > to the extraDisplayName <nl> + / / the corresponding channels to the extraDisplayName <nl> / / planar devices are ignored here as their streams are <nl> / / the channels not different subdevices <nl> if ( m_caStreamInfos . size ( ) > 1 & & ! m_isPlanar ) <nl> { <nl> - std : : stringstream streamIdxStr ; <nl> - streamIdxStr < < streamIdx ; <nl> - extraDisplayName = " Stream " + streamIdxStr . str ( ) ; <nl> + / / build a string with the channels for this stream <nl> + UInt32 startChannel = 0 ; <nl> + CCoreAudioStream : : GetStartingChannelInDevice ( m_caStreamInfos [ streamIdx ] . streamID , startChannel ) ; <nl> + UInt32 numChannels = m_caDevice . GetNumChannelsOfStream ( streamIdx ) ; <nl> + std : : stringstream extraName ; <nl> + extraName < < " Channels " ; <nl> + extraName < < startChannel ; <nl> + extraName < < " - " ; <nl> + extraName < < startChannel + numChannels - 1 ; <nl> + CLog : : Log ( LOGNOTICE , " % s adding stream % d as pseudo device with start channel % d and % d channels total " , __FUNCTION__ , ( unsigned int ) streamIdx , ( unsigned int ) startChannel , ( unsigned int ) numChannels ) ; <nl> + return extraName . str ( ) ; <nl> } <nl> - return extraDisplayName ; <nl> + <nl> + / / for all other devices use the datasource as extraname <nl> + return m_caDevice . GetCurrentDataSourceName ( ) ; <nl> } <nl> <nl> float AEDeviceEnumerationOSX : : scoreSampleRate ( Float64 destinationRate , unsigned int sourceRate ) const <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / AEDeviceEnumerationOSX . h <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / AEDeviceEnumerationOSX . h <nl> <nl> # include " cores / AudioEngine / Utils / AEDeviceInfo . h " <nl> # include " cores / AudioEngine / Sinks / osx / CoreAudioDevice . h " <nl> <nl> - typedef std : : vector < std : : pair < AudioDeviceID , CAEDeviceInfo > > CADeviceList ; <nl> + struct CADeviceInstance <nl> + { <nl> + AudioDeviceID audioDeviceId ; <nl> + unsigned int streamIndex ; <nl> + unsigned int sourceId ; <nl> + } ; <nl> + typedef std : : vector < std : : pair < struct CADeviceInstance , CAEDeviceInfo > > CADeviceList ; <nl> <nl> typedef enum PassthroughMode <nl> { <nl> typedef enum PassthroughMode <nl> PassthroughModeNative , <nl> PassthroughModeBitstream <nl> } EPassthroughMode ; <nl> - <nl> + <nl> / / Hirarchy : <nl> / / Device <nl> / / - 1 . . n streams <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioDevice . cpp <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioDevice . cpp <nl> UInt32 CCoreAudioDevice : : GetTotalOutputChannels ( ) const <nl> return channels ; <nl> } <nl> <nl> - UInt32 CCoreAudioDevice : : GetNumChannelsOfStream ( UInt32 streamIdx ) <nl> + UInt32 CCoreAudioDevice : : GetNumChannelsOfStream ( UInt32 streamIdx ) const <nl> { <nl> UInt32 channels = 0 ; <nl> <nl> bool CCoreAudioDevice : : GetPreferredChannelLayoutForStereo ( CCoreAudioChannelLayou <nl> return ( ret = = noErr ) ; <nl> } <nl> <nl> - bool CCoreAudioDevice : : GetDataSources ( CoreAudioDataSourceList * pList ) <nl> + std : : string CCoreAudioDevice : : GetCurrentDataSourceName ( ) const <nl> + { <nl> + UInt32 dataSourceId = 0 ; <nl> + std : : string dataSourceName = " " ; <nl> + if ( GetDataSource ( dataSourceId ) ) <nl> + { <nl> + dataSourceName = GetDataSourceName ( dataSourceId ) ; <nl> + } <nl> + return dataSourceName ; <nl> + } <nl> + <nl> + std : : string CCoreAudioDevice : : GetDataSourceName ( UInt32 dataSourceId ) const <nl> + { <nl> + UInt32 propertySize = 0 ; <nl> + CFStringRef dataSourceNameCF ; <nl> + std : : string dataSourceName ; <nl> + std : : string ret = " " ; <nl> + <nl> + if ( ! m_DeviceId ) <nl> + return ret ; <nl> + <nl> + AudioObjectPropertyAddress propertyAddress ; <nl> + propertyAddress . mScope = kAudioDevicePropertyScopeOutput ; <nl> + propertyAddress . mElement = 0 ; <nl> + propertyAddress . mSelector = kAudioDevicePropertyDataSourceNameForIDCFString ; <nl> + <nl> + AudioValueTranslation translation ; <nl> + translation . mInputData = & dataSourceId ; <nl> + translation . mInputDataSize = sizeof ( UInt32 ) ; <nl> + translation . mOutputData = & dataSourceNameCF ; <nl> + translation . mOutputDataSize = sizeof ( CFStringRef ) ; <nl> + propertySize = sizeof ( AudioValueTranslation ) ; <nl> + OSStatus status = AudioObjectGetPropertyData ( m_DeviceId , & propertyAddress , 0 , NULL , & propertySize , & translation ) ; <nl> + <nl> + if ( ( status = = noErr ) & & dataSourceNameCF ) <nl> + { <nl> + if ( DarwinCFStringRefToUTF8String ( dataSourceNameCF , dataSourceName ) ) <nl> + { <nl> + ret = dataSourceName ; <nl> + } <nl> + CFRelease ( dataSourceNameCF ) ; <nl> + } <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + bool CCoreAudioDevice : : GetDataSource ( UInt32 & dataSourceId ) const <nl> + { <nl> + bool ret = false ; <nl> + <nl> + if ( ! m_DeviceId ) <nl> + return false ; <nl> + <nl> + AudioObjectPropertyAddress propertyAddress ; <nl> + propertyAddress . mScope = kAudioDevicePropertyScopeOutput ; <nl> + propertyAddress . mElement = 0 ; <nl> + propertyAddress . mSelector = kAudioDevicePropertyDataSource ; <nl> + <nl> + UInt32 size = sizeof ( dataSourceId ) ; <nl> + OSStatus status = AudioObjectGetPropertyData ( m_DeviceId , & propertyAddress , 0 , NULL , & size , & dataSourceId ) ; <nl> + if ( status = = noErr ) <nl> + ret = true ; <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + bool CCoreAudioDevice : : SetDataSource ( UInt32 & dataSourceId ) <nl> + { <nl> + bool ret = false ; <nl> + <nl> + if ( ! m_DeviceId ) <nl> + return false ; <nl> + <nl> + AudioObjectPropertyAddress propertyAddress ; <nl> + propertyAddress . mScope = kAudioDevicePropertyScopeOutput ; <nl> + propertyAddress . mElement = 0 ; <nl> + propertyAddress . mSelector = kAudioDevicePropertyDataSource ; <nl> + <nl> + UInt32 size = sizeof ( dataSourceId ) ; <nl> + OSStatus status = AudioObjectSetPropertyData ( m_DeviceId , & propertyAddress , 0 , NULL , size , & dataSourceId ) ; <nl> + if ( status = = noErr ) <nl> + ret = true ; <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> + bool CCoreAudioDevice : : GetDataSources ( CoreAudioDataSourceList * pList ) const <nl> { <nl> if ( ! pList | | ! m_DeviceId ) <nl> return false ; <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioDevice . h <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioDevice . h <nl> <nl> <nl> # include < CoreAudio / CoreAudio . h > <nl> <nl> - typedef std : : list < UInt32 > CoreAudioDataSourceList ; <nl> + typedef std : : vector < UInt32 > CoreAudioDataSourceList ; <nl> typedef std : : list < AudioDeviceID > CoreAudioDeviceList ; <nl> <nl> class CCoreAudioChannelLayout ; <nl> class CCoreAudioDevice <nl> bool IsDigital ( ) const ; <nl> UInt32 GetTransportType ( ) const ; <nl> UInt32 GetTotalOutputChannels ( ) const ; <nl> - UInt32 GetNumChannelsOfStream ( UInt32 streamIdx ) ; <nl> + UInt32 GetNumChannelsOfStream ( UInt32 streamIdx ) const ; <nl> bool GetStreams ( AudioStreamIdList * pList ) ; <nl> bool IsRunning ( ) ; <nl> bool SetHogStatus ( bool hog ) ; <nl> class CCoreAudioDevice <nl> bool SetCurrentVolume ( Float32 vol ) ; <nl> bool GetPreferredChannelLayout ( CCoreAudioChannelLayout & layout ) const ; <nl> bool GetPreferredChannelLayoutForStereo ( CCoreAudioChannelLayout & layout ) const ; <nl> - bool GetDataSources ( CoreAudioDataSourceList * pList ) ; <nl> + bool GetDataSources ( CoreAudioDataSourceList * pList ) const ; <nl> + bool GetDataSource ( UInt32 & dataSourceId ) const ; <nl> + bool SetDataSource ( UInt32 & dataSourceId ) ; <nl> + std : : string GetDataSourceName ( UInt32 dataSourceId ) const ; <nl> + std : : string GetCurrentDataSourceName ( ) const ; <nl> Float64 GetNominalSampleRate ( ) ; <nl> bool SetNominalSampleRate ( Float64 sampleRate ) ; <nl> UInt32 GetNumLatencyFrames ( ) ; <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioStream . cpp <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioStream . cpp <nl> bool CCoreAudioStream : : IsDigitalOuptut ( AudioStreamID id ) <nl> type = = kIOAudioDeviceTransportTypeUSB ) ; <nl> } <nl> <nl> + bool CCoreAudioStream : : GetStartingChannelInDevice ( AudioStreamID id , UInt32 & startingChannel ) <nl> + { <nl> + if ( ! id ) <nl> + return 0 ; <nl> + <nl> + UInt32 i_param_size = sizeof ( UInt32 ) ; <nl> + UInt32 i_param ; <nl> + startingChannel = 0 ; <nl> + bool ret = false ; <nl> + <nl> + AudioObjectPropertyAddress propertyAddress ; <nl> + propertyAddress . mScope = kAudioObjectPropertyScopeGlobal ; <nl> + propertyAddress . mElement = kAudioObjectPropertyElementMaster ; <nl> + propertyAddress . mSelector = kAudioStreamPropertyStartingChannel ; <nl> + <nl> + / / number of frames of latency in the AudioStream <nl> + OSStatus status = AudioObjectGetPropertyData ( id , & propertyAddress , 0 , NULL , & i_param_size , & i_param ) ; <nl> + if ( status = = noErr ) <nl> + { <nl> + startingChannel = i_param ; <nl> + ret = true ; <nl> + } <nl> + <nl> + return ret ; <nl> + } <nl> + <nl> UInt32 CCoreAudioStream : : GetTerminalType ( AudioStreamID id ) <nl> { <nl> if ( ! id ) <nl> mmm a / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioStream . h <nl> ppp b / xbmc / cores / AudioEngine / Sinks / osx / CoreAudioStream . h <nl> class CCoreAudioStream <nl> static bool GetAvailableVirtualFormats ( AudioStreamID id , StreamFormatList * pList ) ; <nl> static bool GetAvailablePhysicalFormats ( AudioStreamID id , StreamFormatList * pList ) ; <nl> static bool IsDigitalOuptut ( AudioStreamID id ) ; <nl> + static bool GetStartingChannelInDevice ( AudioStreamID id , UInt32 & startingChannel ) ; <nl> <nl> protected : <nl> static OSStatus HardwareStreamListener ( AudioObjectID inObjectID , <nl> | Merge pull request from Memphiz / osxfixstreams | xbmc/xbmc | 502c7ae0c7ec1aba1a810c7cdffe7bbcf4a453d8 | 2014-08-03T21:01:45Z |
mmm a / doc / build - unix . txt <nl> ppp b / doc / build - unix . txt <nl> Dependencies <nl> libdb4 . 8 Berkeley DB Blockchain & wallet storage <nl> libboost Boost C + + Library <nl> miniupnpc UPnP Support Optional firewall - jumping support <nl> - libqrencode QRCode generation Optional QRCode generation <nl> <nl> miniupnpc may be used for UPnP port mapping . It can be downloaded from <nl> http : / / miniupnp . tuxfamily . org / files / . UPnP support is compiled in and <nl> turned off by default . Set USE_UPNP to a different value to control this : <nl> USE_UPNP = 0 ( the default ) UPnP support turned off by default at runtime <nl> USE_UPNP = 1 UPnP support turned on by default at runtime <nl> <nl> - libqrencode may be used for QRCode image generation . It can be downloaded <nl> - from http : / / fukuchi . org / works / qrencode / index . html . en , or installed via <nl> - your package manager . Set USE_QRCODE to control this : <nl> - USE_QRCODE = 0 ( the default ) No QRCode support - libqrcode not required <nl> - USE_QRCODE = 1 QRCode support enabled <nl> - <nl> - IPv6 support may be enabled by setting <nl> + IPv6 support may be enabled by setting : <nl> USE_IPV6 = 1 Enable IPv6 support <nl> <nl> Licenses of statically linked libraries : <nl> Versions used in this release : <nl> <nl> Dependency Build Instructions : Ubuntu & Debian <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - sudo apt - get install build - essential <nl> - sudo apt - get install libssl - dev <nl> - sudo apt - get install libdb4 . 8 - dev <nl> - sudo apt - get install libdb4 . 8 + + - dev <nl> - Boost 1 . 40 + : sudo apt - get install libboost - all - dev <nl> - or Boost 1 . 37 : sudo apt - get install libboost1 . 37 - dev <nl> - sudo apt - get install libqrencode - dev <nl> - <nl> - If using Boost 1 . 37 , append - mt to the boost libraries in the makefile . <nl> + Build requirements : <nl> + sudo apt - get install build - essential <nl> + sudo apt - get install libssl - dev <nl> + <nl> + for Ubuntu 12 . 04 : <nl> + sudo apt - get install libboost - all - dev <nl> + <nl> + db4 . 8 packages are available at : <nl> + https : / / launchpad . net / ~ bitcoin / + archive / bitcoin <nl> + <nl> + Ubuntu precise has packages for libdb5 . 1 - dev and libdb5 . 1 + + - dev , <nl> + but using these will break binary wallet compatibility , and is not recommended . <nl> + <nl> + for other Ubuntu & Debian : <nl> + sudo apt - get install libdb4 . 8 - dev <nl> + sudo apt - get install libdb4 . 8 + + - dev <nl> + sudo apt - get install libboost1 . 37 - dev <nl> + ( If using Boost 1 . 37 , append - mt to the boost libraries in the makefile ) <nl> + <nl> + Optional : <nl> + sudo apt - get install libminiupnpc - dev ( see USE_UPNP compile flag ) <nl> <nl> <nl> Dependency Build Instructions : Gentoo <nl> | Merge pull request from osmosis79 / patch - 1 | bitcoin/bitcoin | 8b1eb5687df3f01edeaa2724783faa6a3c08aa03 | 2012-09-11T18:55:29Z |
mmm a / ios / playground / Podfile <nl> ppp b / ios / playground / Podfile <nl> platform : ios , ' 7 . 0 ' <nl> <nl> def common <nl> pod ' WeexSDK ' , : path = > ' . . / . . / ' <nl> - pod ' WXDevtool ' , ' 0 . 9 . 5 ' <nl> + pod ' WXDevtool ' , ' 0 . 15 . 1 ' <nl> pod ' SDWebImage ' , ' 3 . 7 . 5 ' <nl> pod ' SocketRocket ' , ' 0 . 4 . 2 ' <nl> pod ' ATSDK - Weex ' , ' 0 . 0 . 1 ' <nl> | + [ ios ] update podfile | apache/incubator-weex | 9c3011d639744f17b6db3d55e7be70bf991bc35c | 2017-07-26T09:50:37Z |
mmm a / core / math / geometry . cpp <nl> ppp b / core / math / geometry . cpp <nl> Vector < Vector < Point2 > > Geometry : : _polypath_offset ( const Vector < Point2 > & p_polyp <nl> case END_SQUARE : et = etOpenSquare ; break ; <nl> case END_ROUND : et = etOpenRound ; break ; <nl> } <nl> - ClipperOffset co ; <nl> + ClipperOffset co ( 2 . 0 , 0 . 25 * SCALE_FACTOR ) ; / / Defaults from ClipperOffset . <nl> Path path ; <nl> <nl> / / Need to scale points ( Clipper ' s requirement for robust computation ) . <nl> | Fix severe performance drop while deflating polylines | godotengine/godot | 749d917424e20d6af61746c0d69fb54c50619f80 | 2019-12-03T13:43:59Z |
mmm a / buildscripts / resmokeconfig / suites / aggregation_mongos_passthrough . yml <nl> ppp b / buildscripts / resmokeconfig / suites / aggregation_mongos_passthrough . yml <nl> selector : <nl> - jstests / aggregation / bugs / lookup_unwind_killcursor . js <nl> # TODO : Remove when SERVER - 23229 is fixed . <nl> - jstests / aggregation / bugs / groupMissing . js <nl> + # Mongos does not support runtimeConstants . <nl> + - jstests / aggregation / accumulators / internal_js_reduce_with_scope . js <nl> + - jstests / aggregation / expressions / internal_js_emit_with_scope . js <nl> exclude_with_any_tags : <nl> - requires_profiling <nl> # The following tests start their own ShardingTest or ReplSetTest , respectively . <nl> new file mode 100644 <nl> index 000000000000 . . 956c1f62a252 <nl> mmm / dev / null <nl> ppp b / jstests / aggregation / accumulators / internal_js_reduce_with_scope . js <nl> <nl> + / / Tests the ability of the $ _internalJsReduce accumulator to access javascript scope explicitly <nl> + / / specified in runtimeConstants . <nl> + / / <nl> + / / Do not run in sharded passthroughs since ' runtimeConstants ' is disallowed on mongos . <nl> + / / @ tags : [ assumes_unsharded_collection ] <nl> + ( function ( ) { <nl> + " use strict " ; <nl> + <nl> + load ( ' jstests / aggregation / extras / utils . js ' ) ; <nl> + <nl> + db . js_reduce_with_scope . drop ( ) ; <nl> + <nl> + for ( const i of [ " hello " , " world " , " world " , " hello " , " hi " ] ) { <nl> + db . js_reduce . insert ( { word : i , val : 1 } ) ; <nl> + } <nl> + <nl> + / / Simple reduce function which calculates the word value based on weights defined in a local JS <nl> + / / variable . <nl> + const weights = { <nl> + hello : 3 , <nl> + world : 2 , <nl> + hi : 1 <nl> + } ; <nl> + function reduce ( key , values ) { <nl> + return Array . sum ( values ) * weights [ key ] ; <nl> + } <nl> + <nl> + const command = { <nl> + aggregate : ' js_reduce ' , <nl> + cursor : { } , <nl> + runtimeConstants : <nl> + { localNow : new Date ( ) , clusterTime : new Timestamp ( 0 , 0 ) , jsScope : { weights : weights } } , <nl> + pipeline : [ { <nl> + $ group : { <nl> + _id : " $ word " , <nl> + wordCount : { <nl> + $ _internalJsReduce : { <nl> + data : { k : " $ word " , v : " $ val " } , <nl> + eval : reduce , <nl> + } <nl> + } <nl> + } <nl> + } ] , <nl> + } ; <nl> + <nl> + const expectedResults = [ <nl> + { _id : " hello " , wordCount : 6 } , <nl> + { _id : " world " , wordCount : 4 } , <nl> + { _id : " hi " , wordCount : 1 } , <nl> + ] ; <nl> + <nl> + const res = assert . commandWorked ( db . runCommand ( command ) ) ; <nl> + assert ( resultsEq ( res . cursor . firstBatch , expectedResults , res . cursor ) ) ; <nl> + } ) ( ) ; <nl> new file mode 100644 <nl> index 000000000000 . . 731a91717fa5 <nl> mmm / dev / null <nl> ppp b / jstests / aggregation / expressions / internal_js_emit_with_scope . js <nl> <nl> + / / Tests the ability of the $ _internalJsEmit expression to access javascript scope explicitly <nl> + / / specified in runtimeConstants . <nl> + / / <nl> + / / Do not run in sharded passthroughs since ' runtimeConstants ' is disallowed on mongos . <nl> + / / @ tags : [ assumes_unsharded_collection ] <nl> + ( function ( ) { <nl> + " use strict " ; <nl> + <nl> + load ( ' jstests / aggregation / extras / utils . js ' ) ; <nl> + <nl> + const coll = db . js_emit_with_scope ; <nl> + coll . drop ( ) ; <nl> + <nl> + const weights = { <nl> + wood : 5 , <nl> + chuck : 2 , <nl> + could : 0 <nl> + } ; <nl> + <nl> + let constants = { <nl> + localNow : new Date ( ) , <nl> + clusterTime : new Timestamp ( 0 , 0 ) , <nl> + jsScope : { weights : weights } <nl> + } ; <nl> + <nl> + function fmap ( ) { <nl> + for ( let word of this . text . split ( ' ' ) ) { <nl> + emit ( word , weights [ word ] ) ; <nl> + } <nl> + } <nl> + <nl> + let pipeline = [ <nl> + { <nl> + $ project : { <nl> + emits : { <nl> + $ _internalJsEmit : { <nl> + this : ' $ $ ROOT ' , <nl> + eval : fmap , <nl> + } , <nl> + } , <nl> + _id : 0 , <nl> + } <nl> + } , <nl> + { $ unwind : ' $ emits ' } , <nl> + { $ replaceRoot : { newRoot : ' $ emits ' } } <nl> + ] ; <nl> + <nl> + assert . commandWorked ( coll . insert ( { text : ' wood chuck could chuck wood ' } ) ) ; <nl> + <nl> + let results = coll . aggregate ( pipeline , { cursor : { } , runtimeConstants : constants } ) . toArray ( ) ; <nl> + assert ( resultsEq ( results , <nl> + [ <nl> + { k : " wood " , v : weights [ " wood " ] } , <nl> + { k : " chuck " , v : weights [ " chuck " ] } , <nl> + { k : " could " , v : weights [ " could " ] } , <nl> + { k : " chuck " , v : weights [ " chuck " ] } , <nl> + { k : " wood " , v : weights [ " wood " ] } <nl> + ] , <nl> + results ) ) ; <nl> + <nl> + / / <nl> + / / Test that the scope variables are mutable from within a user - defined javascript function . <nl> + / / <nl> + pipeline [ 0 ] . $ project . emits . $ _internalJsEmit . eval = function ( ) { <nl> + for ( let word of this . text . split ( ' ' ) ) { <nl> + emit ( word , weights [ word ] ) ; <nl> + weights [ word ] + = 1 ; <nl> + } <nl> + } ; <nl> + <nl> + results = coll . aggregate ( pipeline , { cursor : { } , runtimeConstants : constants } ) . toArray ( ) ; <nl> + assert ( resultsEq ( results , <nl> + [ <nl> + { k : " wood " , v : weights [ " wood " ] } , <nl> + { k : " chuck " , v : weights [ " chuck " ] } , <nl> + { k : " could " , v : weights [ " could " ] } , <nl> + { k : " chuck " , v : weights [ " chuck " ] + 1 } , <nl> + { k : " wood " , v : weights [ " wood " ] + 1 } <nl> + ] , <nl> + results ) ) ; <nl> + <nl> + / / <nl> + / / Test that the jsScope is allowed to have any number of fields . <nl> + / / <nl> + constants . jsScope . multiplier = 5 ; <nl> + pipeline [ 0 ] . $ project . emits . $ _internalJsEmit . eval = function ( ) { <nl> + for ( let word of this . text . split ( ' ' ) ) { <nl> + emit ( word , weights [ word ] * multiplier ) ; <nl> + } <nl> + } ; <nl> + results = coll . aggregate ( pipeline , { cursor : { } , runtimeConstants : constants } ) . toArray ( ) ; <nl> + assert ( resultsEq ( results , <nl> + [ <nl> + { k : " wood " , v : weights [ " wood " ] * 5 } , <nl> + { k : " chuck " , v : weights [ " chuck " ] * 5 } , <nl> + { k : " could " , v : weights [ " could " ] * 5 } , <nl> + { k : " chuck " , v : weights [ " chuck " ] * 5 } , <nl> + { k : " wood " , v : weights [ " wood " ] * 5 } <nl> + ] , <nl> + results ) ) ; <nl> + constants . jsScope = { } ; <nl> + pipeline [ 0 ] . $ project . emits . $ _internalJsEmit . eval = function ( ) { <nl> + for ( let word of this . text . split ( ' ' ) ) { <nl> + emit ( word , 1 ) ; <nl> + } <nl> + } ; <nl> + results = coll . aggregate ( pipeline , { cursor : { } , runtimeConstants : constants } ) . toArray ( ) ; <nl> + assert ( resultsEq ( results , <nl> + [ <nl> + { k : " wood " , v : 1 } , <nl> + { k : " chuck " , v : 1 } , <nl> + { k : " could " , v : 1 } , <nl> + { k : " chuck " , v : 1 } , <nl> + { k : " wood " , v : 1 } , <nl> + ] , <nl> + results ) ) ; <nl> + <nl> + / / <nl> + / / Test that the command fails if the jsScope is not an object . <nl> + / / <nl> + constants . jsScope = " you cant do this " ; <nl> + assert . commandFailedWithCode ( <nl> + db . runCommand ( <nl> + { aggregate : coll . getName ( ) , pipeline : pipeline , cursor : { } , runtimeConstants : constants } ) , <nl> + ErrorCodes . TypeMismatch ) ; <nl> + } ) ( ) ; <nl> mmm a / src / mongo / db / pipeline / accumulator_js_reduce . cpp <nl> ppp b / src / mongo / db / pipeline / accumulator_js_reduce . cpp <nl> Value AccumulatorInternalJsReduce : : getValue ( bool toBeMerged ) { <nl> bsonValues < < val ; <nl> } <nl> <nl> - / / Function signature : reduce ( key , values ) . <nl> - BSONObj params = BSON_ARRAY ( _key < < bsonValues . arr ( ) ) ; <nl> - auto [ jsExec , newlyCreated ] = getExpressionContext ( ) - > mongoProcessInterface - > getJsExec ( ) ; <nl> + auto expCtx = getExpressionContext ( ) ; <nl> + auto [ jsExec , newlyCreated ] = expCtx - > getJsExecWithScope ( ) ; <nl> ScriptingFunction func = jsExec - > getScope ( ) - > createFunction ( _funcSource . c_str ( ) ) ; <nl> <nl> uassert ( 31247 , " The reduce function failed to parse in the javascript engine " , func ) ; <nl> <nl> - BSONObj thisObj ; / / For reduce , the key and values are both passed as ' params ' so there ' s <nl> - / / no need to set ' this ' . <nl> + / / Function signature : reduce ( key , values ) . <nl> + BSONObj params = BSON_ARRAY ( _key < < bsonValues . arr ( ) ) ; <nl> + / / For reduce , the key and values are both passed as ' params ' so there ' s no need to set <nl> + / / ' this ' . <nl> + BSONObj thisObj ; <nl> return jsExec - > callFunction ( func , params , thisObj ) ; <nl> } ( ) ; <nl> <nl> mmm a / src / mongo / db / pipeline / expression_context . h <nl> ppp b / src / mongo / db / pipeline / expression_context . h <nl> class ExpressionContext : public RefCountable { <nl> auto getRuntimeConstants ( ) const { <nl> return variables . getRuntimeConstants ( ) ; <nl> } <nl> + <nl> + / * * <nl> + * Retrieves the Javascript Scope for the current thread or creates a new one if it has not been <nl> + * created yet . Initializes the Scope with the ' jsScope ' variables from the runtimeConstants . <nl> + * <nl> + * Returns a JsExec and a boolean indicating whether the Scope was created as part of this call . <nl> + * / <nl> + auto getJsExecWithScope ( ) const { <nl> + RuntimeConstants runtimeConstants = getRuntimeConstants ( ) ; <nl> + const boost : : optional < mongo : : BSONObj > & scope = runtimeConstants . getJsScope ( ) ; <nl> + return mongoProcessInterface - > getJsExec ( scope . get_value_or ( BSONObj ( ) ) ) ; <nl> + } <nl> + <nl> / / The explain verbosity requested by the user , or boost : : none if no explain was requested . <nl> boost : : optional < ExplainOptions : : Verbosity > explain ; <nl> <nl> mmm a / src / mongo / db / pipeline / expression_javascript . cpp <nl> ppp b / src / mongo / db / pipeline / expression_javascript . cpp <nl> Value ExpressionInternalJsEmit : : evaluate ( const Document & root , Variables * variab <nl> Value thisVal = _thisRef - > evaluate ( root , variables ) ; <nl> uassert ( 31225 , " ' this ' must be an object . " , thisVal . getType ( ) = = BSONType : : Object ) ; <nl> <nl> - / / If the scope does not exist and is created by the call to ExpressionContext : : getJsExec ( ) , <nl> - / / then make sure to re - bind emit ( ) and the given function to the new scope . <nl> + / / If the scope does not exist and is created by the following call , then make sure to <nl> + / / re - bind emit ( ) and the given function to the new scope . <nl> auto expCtx = getExpressionContext ( ) ; <nl> - auto [ jsExec , newlyCreated ] = expCtx - > mongoProcessInterface - > getJsExec ( ) ; <nl> + auto [ jsExec , newlyCreated ] = expCtx - > getJsExecWithScope ( ) ; <nl> if ( newlyCreated ) { <nl> jsExec - > getScope ( ) - > loadStored ( expCtx - > opCtx , true ) ; <nl> <nl> Value ExpressionInternalJsEmit : : evaluate ( const Document & root , Variables * variab <nl> std : : vector < Value > output ; <nl> <nl> for ( const BSONObj & obj : _emittedObjects ) { <nl> - output . push_back ( Value ( std : : move ( obj ) ) ) ; <nl> + output . push_back ( Value ( obj ) ) ; <nl> } <nl> <nl> / / Need to const_cast here in order to clean out _emittedObjects which were added in the call to <nl> Value ExpressionInternalJs : : evaluate ( const Document & root , Variables * variables ) <nl> < < " can ' t be run on this process . Javascript is disabled . " , <nl> getGlobalScriptEngine ( ) ) ; <nl> <nl> - auto [ jsExec , newlyCreated ] = expCtx - > mongoProcessInterface - > getJsExec ( ) ; <nl> + auto [ jsExec , newlyCreated ] = expCtx - > getJsExecWithScope ( ) ; <nl> if ( newlyCreated ) { <nl> jsExec - > getScope ( ) - > loadStored ( expCtx - > opCtx , true ) ; <nl> <nl> mmm a / src / mongo / db / pipeline / javascript_execution . h <nl> ppp b / src / mongo / db / pipeline / javascript_execution . h <nl> namespace mongo { <nl> class JsExecution { <nl> public : <nl> / * * <nl> - * Construct with a thread - local scope . <nl> + * Construct with a thread - local scope and initialize with the given scope variables . <nl> * / <nl> - JsExecution ( ) : _scope ( nullptr ) { <nl> - _scope . reset ( getGlobalScriptEngine ( ) - > newScopeForCurrentThread ( ) ) ; <nl> + JsExecution ( const BSONObj & scopeVars ) <nl> + : _scope ( getGlobalScriptEngine ( ) - > newScopeForCurrentThread ( ) ) { <nl> + _scopeVars = scopeVars . getOwned ( ) ; <nl> + _scope - > init ( & _scopeVars ) ; <nl> } <nl> <nl> / * * <nl> class JsExecution { <nl> } <nl> <nl> private : <nl> + BSONObj _scopeVars ; <nl> std : : unique_ptr < Scope > _scope ; <nl> } ; <nl> } / / namespace mongo <nl> mmm a / src / mongo / db / pipeline / mongo_process_interface . h <nl> ppp b / src / mongo / db / pipeline / mongo_process_interface . h <nl> class MongoProcessInterface { <nl> * Returns a pointer to a JsExecution and a boolean to indicate whether the JS Scope was newly <nl> * created . <nl> * / <nl> - virtual std : : pair < JsExecution * , bool > getJsExec ( ) = 0 ; <nl> + virtual std : : pair < JsExecution * , bool > getJsExec ( const BSONObj & scope ) = 0 ; <nl> virtual void releaseJsExec ( ) = 0 ; <nl> } ; <nl> <nl> mmm a / src / mongo / db / pipeline / mongos_process_interface . h <nl> ppp b / src / mongo / db / pipeline / mongos_process_interface . h <nl> class MongoSInterface : public MongoProcessCommon { <nl> boost : : optional < ChunkVersion > targetCollectionVersion , <nl> const NamespaceString & outputNs ) const override ; <nl> <nl> - std : : pair < JsExecution * , bool > getJsExec ( ) override { <nl> + std : : pair < JsExecution * , bool > getJsExec ( const BSONObj & ) override { <nl> / / Javascript engine is not support on mongos . <nl> MONGO_UNREACHABLE ; <nl> } <nl> mmm a / src / mongo / db / pipeline / process_interface_standalone . h <nl> ppp b / src / mongo / db / pipeline / process_interface_standalone . h <nl> class MongoInterfaceStandalone : public MongoProcessCommon { <nl> * If we are creating a new JsExecution ( and therefore a new thread - local scope ) , make sure <nl> * we pass that information back to the caller . <nl> * / <nl> - std : : pair < JsExecution * , bool > getJsExec ( ) override { <nl> + std : : pair < JsExecution * , bool > getJsExec ( const BSONObj & scope ) override { <nl> if ( ! _jsExec ) { <nl> - _jsExec = std : : make_unique < JsExecution > ( ) ; <nl> + _jsExec = std : : make_unique < JsExecution > ( scope ) ; <nl> return { _jsExec . get ( ) , true } ; <nl> } <nl> return { _jsExec . get ( ) , false } ; <nl> mmm a / src / mongo / db / pipeline / runtime_constants . idl <nl> ppp b / src / mongo / db / pipeline / runtime_constants . idl <nl> structs : <nl> cpp_name : clusterTime <nl> type : timestamp <nl> description : A value of the $ $ CLUSTER_TIME variable . <nl> + jsScope : <nl> + cpp_name : jsScope <nl> + type : object <nl> + optional : true <nl> + description : Optional scope variables accessible from internal javacsript expressions . <nl> mmm a / src / mongo / db / pipeline / stub_mongo_process_interface . h <nl> ppp b / src / mongo / db / pipeline / stub_mongo_process_interface . h <nl> class StubMongoProcessInterface : public MongoProcessInterface { <nl> return { fieldPaths , targetCollectionVersion } ; <nl> } <nl> <nl> - std : : pair < JsExecution * , bool > getJsExec ( ) { <nl> + std : : pair < JsExecution * , bool > getJsExec ( const BSONObj & ) { <nl> MONGO_UNREACHABLE ; <nl> } <nl> void releaseJsExec ( ) { } <nl> mmm a / src / mongo / db / pipeline / variables . cpp <nl> ppp b / src / mongo / db / pipeline / variables . cpp <nl> namespace mongo { <nl> constexpr Variables : : Id Variables : : kRootId ; <nl> constexpr Variables : : Id Variables : : kRemoveId ; <nl> <nl> - const StringMap < Variables : : Id > Variables : : kBuiltinVarNameToId = { <nl> - { " ROOT " , kRootId } , { " REMOVE " , kRemoveId } , { " NOW " , kNowId } , { " CLUSTER_TIME " , kClusterTimeId } } ; <nl> + const StringMap < Variables : : Id > Variables : : kBuiltinVarNameToId = { { " ROOT " , kRootId } , <nl> + { " REMOVE " , kRemoveId } , <nl> + { " NOW " , kNowId } , <nl> + { " CLUSTER_TIME " , kClusterTimeId } , <nl> + { " JS_SCOPE " , kJsScopeId } } ; <nl> <nl> void Variables : : uassertValidNameForUserWrite ( StringData varName ) { <nl> / / System variables users allowed to write to ( currently just one ) <nl> RuntimeConstants Variables : : getRuntimeConstants ( ) const { <nl> if ( auto it = _runtimeConstants . find ( kClusterTimeId ) ; it ! = _runtimeConstants . end ( ) ) { <nl> constants . setClusterTime ( it - > second . getTimestamp ( ) ) ; <nl> } <nl> + if ( auto it = _runtimeConstants . find ( kJsScopeId ) ; it ! = _runtimeConstants . end ( ) ) { <nl> + constants . setJsScope ( it - > second . getDocument ( ) . toBson ( ) ) ; <nl> + } <nl> <nl> return constants ; <nl> } <nl> void Variables : : setRuntimeConstants ( const RuntimeConstants & constants ) { <nl> if ( ! constants . getClusterTime ( ) . isNull ( ) ) { <nl> _runtimeConstants [ kClusterTimeId ] = Value ( constants . getClusterTime ( ) ) ; <nl> } <nl> + <nl> + if ( constants . getJsScope ( ) ) { <nl> + _runtimeConstants [ kJsScopeId ] = Value ( constants . getJsScope ( ) . get ( ) ) ; <nl> + } <nl> } <nl> <nl> void Variables : : setDefaultRuntimeConstants ( OperationContext * opCtx ) { <nl> mmm a / src / mongo / db / pipeline / variables . h <nl> ppp b / src / mongo / db / pipeline / variables . h <nl> class Variables final { <nl> static constexpr Variables : : Id kRemoveId = Id ( - 2 ) ; <nl> static constexpr Variables : : Id kNowId = Id ( - 3 ) ; <nl> static constexpr Variables : : Id kClusterTimeId = Id ( - 4 ) ; <nl> + static constexpr Variables : : Id kJsScopeId = Id ( - 5 ) ; <nl> <nl> / / Map from builtin var name to reserved id number . <nl> static const StringMap < Id > kBuiltinVarNameToId ; <nl> | SERVER - 42684 Add support for ' scope ' RunTimeConstant | mongodb/mongo | c0ca6049bad1bf918e46d83cddab134b7441abf7 | 2019-08-15T20:08:22Z |
mmm a / torch / csrc / autograd / functions / convolution . cpp <nl> ppp b / torch / csrc / autograd / functions / convolution . cpp <nl> static std : : unique_ptr < Tensor > cat ( const tensor_list & tensors , int dim ) { <nl> / / ConvForward implementation <nl> <nl> auto ConvForward : : apply ( const variable_list & inputs ) - > variable_list { <nl> + / / std : : cout < < " Applying conv with : " < < std : : endl ; <nl> + / / std : : cout < < " stride " ; <nl> + / / for ( auto val : this - > stride ) { <nl> + / / std : : cout < < val < < " " ; <nl> + / / } <nl> + / / std : : cout < < std : : endl ; <nl> + / / std : : cout < < " padding " ; <nl> + / / for ( auto val : this - > padding ) { <nl> + / / std : : cout < < val < < " " ; <nl> + / / } <nl> + / / std : : cout < < std : : endl ; <nl> + / / std : : cout < < " dilation " ; <nl> + / / for ( auto val : this - > dilation ) { <nl> + / / std : : cout < < val < < " " ; <nl> + / / } <nl> + / / std : : cout < < std : : endl ; <nl> + / / std : : cout < < " output_padding " ; <nl> + / / for ( auto val : this - > output_padding ) { <nl> + / / std : : cout < < val < < " " ; <nl> + / / } <nl> + / / std : : cout < < std : : endl ; <nl> + / / std : : cout < < " transposed " < < this - > transposed < < std : : endl ; <nl> + / / std : : cout < < " groups " < < this - > groups < < std : : endl ; <nl> + <nl> check_input_variables ( " ConvNd " , inputs , 3 , 2 ) ; <nl> if ( is_padding_neg ( ) ) throw std : : runtime_error ( " negative padding is not supported " ) ; <nl> if ( is_output_padding_neg ( ) ) throw std : : runtime_error ( " negative output_padding is not supported " ) ; <nl> auto ConvForward : : apply ( const variable_list & inputs ) - > variable_list { <nl> tensor_list ones ( groups ) ; <nl> std : : unique_ptr < Convolution > convolution ; <nl> <nl> - auto weight_t = weight - > clone ( ) ; <nl> - <nl> if ( use_cudnn ( * input ) ) { <nl> # ifdef WITH_CUDNN <nl> if ( input - > type ( ) ! = weight - > type ( ) ) { <nl> auto ConvForward : : apply ( const variable_list & inputs ) - > variable_list { <nl> if ( transposed ) { <nl> convolution . reset ( cudnn_convolution_transpose_full_forward ( <nl> state , torch : : cudnn : : getCudnnHandle ( ) , torch : : cudnn : : getCudnnDataType ( * input ) , <nl> - ( THVoidTensor * ) input - > cdata ( ) , ( THVoidTensor * ) weight_t - > cdata ( ) , <nl> + ( THVoidTensor * ) input - > cdata ( ) , ( THVoidTensor * ) weight - > cdata ( ) , <nl> bias ? ( THVoidTensor * ) bias - > cdata ( ) : nullptr , ( THVoidTensor * ) output - > cdata ( ) , <nl> padding , stride , dilation , groups , benchmark ) ) ; <nl> } else { <nl> convolution . reset ( cudnn_convolution_full_forward ( <nl> state , torch : : cudnn : : getCudnnHandle ( ) , torch : : cudnn : : getCudnnDataType ( * input ) , <nl> - ( THVoidTensor * ) input - > cdata ( ) , ( THVoidTensor * ) weight_t - > cdata ( ) , <nl> + ( THVoidTensor * ) input - > cdata ( ) , ( THVoidTensor * ) weight - > cdata ( ) , <nl> bias ? ( THVoidTensor * ) bias - > cdata ( ) : nullptr , ( THVoidTensor * ) output - > cdata ( ) , <nl> padding , stride , dilation , groups , benchmark ) ) ; <nl> } <nl> auto ConvForward : : apply ( const variable_list & inputs ) - > variable_list { <nl> } <nl> if ( groups = = 1 ) { <nl> output = compute_output ( <nl> - input . get ( ) , weight_t , bias . get ( ) , <nl> + input . get ( ) , weight . get ( ) , bias . get ( ) , <nl> columns [ 0 ] . get ( ) , ones [ 0 ] . get ( ) , kernel_size , * this ) ; <nl> } else { <nl> tensor_list outputs ( groups ) ; <nl> for ( int g = 0 ; g < groups ; + + g ) { <nl> auto input_g = subtensor ( input . get ( ) , 1 , groups , g ) ; <nl> - auto weight_g = subtensor ( weight_t , 0 , groups , g ) ; <nl> + auto weight_g = subtensor ( weight . get ( ) , 0 , groups , g ) ; <nl> auto bias_g = subtensor ( bias . get ( ) , 0 , groups , g ) ; <nl> outputs [ g ] = compute_output ( <nl> input_g . get ( ) , weight_g . get ( ) , bias_g . get ( ) , <nl> auto ConvBackward : : apply ( const variable_list & grad_outputs ) - > variable_list { <nl> std : : unique_ptr < Tensor > grad_weight ; <nl> std : : unique_ptr < Tensor > grad_bias ; <nl> <nl> - auto weight_t = weight - > clone ( ) ; <nl> - <nl> if ( should_compute_output ( 0 ) ) { <nl> if ( use_cudnn ) { <nl> # ifdef WITH_CUDNN <nl> auto ConvBackward : : apply ( const variable_list & grad_outputs ) - > variable_list { <nl> / / but swaps forward and backward calls <nl> cudnn_convolution_forward ( <nl> state , torch : : cudnn : : getCudnnHandle ( ) , torch : : cudnn : : getCudnnDataType ( * input ) , <nl> - ( THVoidTensor * ) grad_output - > cdata ( ) , ( THVoidTensor * ) weight_t - > cdata ( ) , ( THVoidTensor * ) grad_input - > cdata ( ) , <nl> + ( THVoidTensor * ) grad_output - > cdata ( ) , ( THVoidTensor * ) weight - > cdata ( ) , ( THVoidTensor * ) grad_input - > cdata ( ) , <nl> convolution . get ( ) , benchmark ) ; <nl> } else { <nl> cudnn_convolution_backward_data ( <nl> state , torch : : cudnn : : getCudnnHandle ( ) , torch : : cudnn : : getCudnnDataType ( * input ) , <nl> - ( THVoidTensor * ) grad_output - > cdata ( ) , ( THVoidTensor * ) grad_input - > cdata ( ) , ( THVoidTensor * ) weight_t - > cdata ( ) , <nl> + ( THVoidTensor * ) grad_output - > cdata ( ) , ( THVoidTensor * ) grad_input - > cdata ( ) , ( THVoidTensor * ) weight - > cdata ( ) , <nl> convolution . get ( ) , benchmark ) ; <nl> } <nl> # endif <nl> } else if ( groups = = 1 ) { <nl> grad_input = compute_grad_input ( <nl> - input . get ( ) , grad_output . get ( ) , weight_t , <nl> + input . get ( ) , grad_output . get ( ) , weight . get ( ) , <nl> columns [ 0 ] . get ( ) , ones [ 0 ] . get ( ) , kernel_size , * this ) ; <nl> } else { <nl> tensor_list grad_inputs ( groups ) ; <nl> for ( int g = 0 ; g < groups ; + + g ) { <nl> auto input_g = subtensor ( input . get ( ) , 1 , groups , g ) ; <nl> auto grad_output_g = subtensor ( grad_output . get ( ) , 1 , groups , g ) ; <nl> - auto weight_g = subtensor ( weight_t , 0 , groups , g ) ; <nl> + auto weight_g = subtensor ( weight . get ( ) , 0 , groups , g ) ; <nl> grad_inputs [ g ] = compute_grad_input ( <nl> input_g . get ( ) , grad_output_g . get ( ) , weight_g . get ( ) , <nl> columns [ g ] . get ( ) , ones [ g ] . get ( ) , kernel_size , * this ) ; <nl> auto ConvBackward : : apply ( const variable_list & grad_outputs ) - > variable_list { <nl> # endif <nl> } else if ( groups = = 1 ) { <nl> std : : tie ( grad_weight , grad_bias ) = compute_grad_params ( <nl> - input . get ( ) , grad_output . get ( ) , weight_t , bias . get ( ) , <nl> + input . get ( ) , grad_output . get ( ) , weight . get ( ) , bias . get ( ) , <nl> columns [ 0 ] . get ( ) , ones [ 0 ] . get ( ) , kernel_size , * this ) ; <nl> } else { <nl> tensor_list grad_weights ( groups ) ; <nl> auto ConvBackward : : apply ( const variable_list & grad_outputs ) - > variable_list { <nl> for ( int g = 0 ; g < groups ; + + g ) { <nl> auto input_g = subtensor ( input . get ( ) , 1 , groups , g ) ; <nl> auto grad_output_g = subtensor ( grad_output . get ( ) , 1 , groups , g ) ; <nl> - auto weight_g = subtensor ( weight_t , 0 , groups , g ) ; <nl> + auto weight_g = subtensor ( weight . get ( ) , 0 , groups , g ) ; <nl> auto bias_g = subtensor ( bias . get ( ) , 0 , groups , g ) ; <nl> std : : tie ( grad_weights [ g ] , grad_biases [ g ] ) = compute_grad_params ( <nl> input_g . get ( ) , grad_output_g . get ( ) , weight_g . get ( ) , bias_g . get ( ) , <nl> auto ConvBackwardBackward : : apply ( const variable_list & grad_grad_inputs ) - > varia <nl> / / Compute ggO = conv ( w , ggI ) + conv ( ggW , i ) + ggb <nl> std : : shared_ptr < Variable > ggO = nullptr ; <nl> if ( ggI ) { <nl> + if ( weight - > data - > isCuda ( ) ) { <nl> + weight = std : : make_shared < Contiguous > ( ) - > apply ( { weight } ) [ 0 ] ; <nl> + } <nl> ggO = std : : make_shared < ConvForward > ( * this ) - > apply ( { ggI , weight , nullptr } ) [ 0 ] ; <nl> } <nl> <nl> if ( ggW ) { <nl> + if ( ggW - > data - > isCuda ( ) ) { <nl> + ggW = std : : make_shared < Contiguous > ( ) - > apply ( { ggW } ) [ 0 ] ; <nl> + } <nl> auto ggW_term = std : : make_shared < ConvForward > ( * this ) - > apply ( { input_ . unpack ( ) , ggW , nullptr } ) [ 0 ] ; <nl> if ( ggO ) { <nl> ggO = std : : make_shared < Add > ( ) - > apply ( { ggO , ggW_term } ) [ 0 ] ; <nl> auto ConvBackwardBackward : : apply ( const variable_list & grad_grad_inputs ) - > varia <nl> auto gOt = std : : make_shared < Transpose > ( 0 , 1 ) - > apply ( { gO } ) [ 0 ] ; <nl> auto ggIt = std : : make_shared < Transpose > ( 0 , 1 ) - > apply ( { ggI } ) [ 0 ] ; <nl> <nl> + if ( gOt - > data - > isCuda ( ) ) { <nl> + gOt = std : : make_shared < Contiguous > ( ) - > apply ( { gOt } ) [ 0 ] ; <nl> + } <nl> + <nl> / / Compute conv <nl> auto gWt = std : : make_shared < ConvForward > ( gw_conv_params ) - > apply ( { ggIt , gOt , nullptr } ) [ 0 ] ; <nl> <nl> auto ConvBackwardBackward : : apply ( const variable_list & grad_grad_inputs ) - > varia <nl> std : : swap ( gi_conv_params . dilation , gi_conv_params . stride ) ; <nl> <nl> auto ggWt = std : : make_shared < Transpose > ( 0 , 1 ) - > apply ( { ggW } ) [ 0 ] ; <nl> - / / Weight for conv transpose are ( chan_in , chan_out , kern , kern ) <nl> auto gOt = std : : make_shared < Transpose > ( 0 , 1 ) - > apply ( { gO } ) [ 0 ] ; <nl> <nl> + if ( gOt - > data - > isCuda ( ) ) { <nl> + gOt = std : : make_shared < Contiguous > ( ) - > apply ( { gOt } ) [ 0 ] ; <nl> + } <nl> + <nl> auto gIt = std : : make_shared < ConvForward > ( gi_conv_params ) - > apply ( { ggWt , gOt , nullptr } ) [ 0 ] ; <nl> <nl> gI = std : : make_shared < Transpose > ( 0 , 1 ) - > apply ( { gIt } ) [ 0 ] ; <nl> | remove extra cloning and add contiguous calls | pytorch/pytorch | fc0ab229ad8d5d31e28f3d36822a9791f06edf1f | 2017-06-17T15:11:48Z |
mmm a / src / wasm / wasm - interpreter . cc <nl> ppp b / src / wasm / wasm - interpreter . cc <nl> class ThreadImpl { <nl> Push ( WasmValue ( ExecuteI64ReinterpretF64 ( val ) ) ) ; <nl> break ; <nl> } <nl> + # define SIGN_EXTENSION_CASE ( name , wtype , ntype ) \ <nl> + case kExpr # # name : { \ <nl> + ntype val = static_cast < ntype > ( Pop ( ) . to < wtype > ( ) ) ; \ <nl> + Push ( WasmValue ( static_cast < wtype > ( val ) ) ) ; \ <nl> + break ; \ <nl> + } <nl> + SIGN_EXTENSION_CASE ( I32SExtendI8 , int32_t , int8_t ) ; <nl> + SIGN_EXTENSION_CASE ( I32SExtendI16 , int32_t , int16_t ) ; <nl> + SIGN_EXTENSION_CASE ( I64SExtendI8 , int64_t , int8_t ) ; <nl> + SIGN_EXTENSION_CASE ( I64SExtendI16 , int64_t , int16_t ) ; <nl> + SIGN_EXTENSION_CASE ( I64SExtendI32 , int64_t , int32_t ) ; <nl> + # undef SIGN_EXTENSION_CASE <nl> case kNumericPrefix : { <nl> + + len ; <nl> if ( ! ExecuteNumericOp ( opcode , & decoder , code , pc , len ) ) return ; <nl> mmm a / test / cctest / wasm / test - run - wasm - sign - extension . cc <nl> ppp b / test / cctest / wasm / test - run - wasm - sign - extension . cc <nl> namespace internal { <nl> namespace wasm { <nl> <nl> / / TODO ( gdeepti ) : Enable tests to run in the interpreter . <nl> - WASM_COMPILED_EXEC_TEST ( I32SExtendI8 ) { <nl> + WASM_EXEC_TEST ( I32SExtendI8 ) { <nl> EXPERIMENTAL_FLAG_SCOPE ( se ) ; <nl> WasmRunner < int32_t , int32_t > r ( execution_mode ) ; <nl> BUILD ( r , WASM_I32_SIGN_EXT_I8 ( WASM_GET_LOCAL ( 0 ) ) ) ; <nl> WASM_COMPILED_EXEC_TEST ( I32SExtendI8 ) { <nl> CHECK_EQ ( - 0x80 , r . Call ( 0x80 ) ) ; <nl> } <nl> <nl> - WASM_COMPILED_EXEC_TEST ( I32SExtendI16 ) { <nl> + WASM_EXEC_TEST ( I32SExtendI16 ) { <nl> EXPERIMENTAL_FLAG_SCOPE ( se ) ; <nl> WasmRunner < int32_t , int32_t > r ( execution_mode ) ; <nl> BUILD ( r , WASM_I32_SIGN_EXT_I16 ( WASM_GET_LOCAL ( 0 ) ) ) ; <nl> WASM_COMPILED_EXEC_TEST ( I32SExtendI16 ) { <nl> CHECK_EQ ( - 0x8000 , r . Call ( 0x8000 ) ) ; <nl> } <nl> <nl> - WASM_COMPILED_EXEC_TEST ( I64SExtendI8 ) { <nl> + WASM_EXEC_TEST ( I64SExtendI8 ) { <nl> EXPERIMENTAL_FLAG_SCOPE ( se ) ; <nl> WasmRunner < int64_t , int64_t > r ( execution_mode ) ; <nl> BUILD ( r , WASM_I64_SIGN_EXT_I8 ( WASM_GET_LOCAL ( 0 ) ) ) ; <nl> WASM_COMPILED_EXEC_TEST ( I64SExtendI8 ) { <nl> CHECK_EQ ( - 0x80 , r . Call ( 0x80 ) ) ; <nl> } <nl> <nl> - WASM_COMPILED_EXEC_TEST ( I64SExtendI16 ) { <nl> + WASM_EXEC_TEST ( I64SExtendI16 ) { <nl> EXPERIMENTAL_FLAG_SCOPE ( se ) ; <nl> WasmRunner < int64_t , int64_t > r ( execution_mode ) ; <nl> BUILD ( r , WASM_I64_SIGN_EXT_I16 ( WASM_GET_LOCAL ( 0 ) ) ) ; <nl> WASM_COMPILED_EXEC_TEST ( I64SExtendI16 ) { <nl> CHECK_EQ ( - 0x8000 , r . Call ( 0x8000 ) ) ; <nl> } <nl> <nl> - WASM_COMPILED_EXEC_TEST ( I64SExtendI32 ) { <nl> + WASM_EXEC_TEST ( I64SExtendI32 ) { <nl> EXPERIMENTAL_FLAG_SCOPE ( se ) ; <nl> WasmRunner < int64_t , int64_t > r ( execution_mode ) ; <nl> BUILD ( r , WASM_I64_SIGN_EXT_I32 ( WASM_GET_LOCAL ( 0 ) ) ) ; <nl> | [ wasm ] Enable sign extension operations in the interpreter | v8/v8 | 785bd43b7e15fba044b2ed1323bb0018e2c193fa | 2018-06-01T22:12:45Z |
mmm a / libraries / appbase <nl> ppp b / libraries / appbase <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 4b95cd33659e18bd4f6ea2327202cfa20b09c658 <nl> + Subproject commit f34a3b402b0f93d41df850032abdfaca7335172f <nl> | Merge pull request from EOSIO / appbase20190809 | EOSIO/eos | a80dca7de0e18adaa761d9c3a1cb3fb86ef2e93a | 2019-08-09T18:40:08Z |
mmm a / include / swift / Runtime / Atomic . h <nl> ppp b / include / swift / Runtime / Atomic . h <nl> <nl> / / is formally UB by C + + 11 language rules , we should be OK because neither <nl> / / the processor model nor the optimizer can realistically reorder our uses <nl> / / of ' consume ' . <nl> - # if __arm64__ | | __arm__ <nl> + # if defined ( __arm__ ) | | defined ( _M_ARM ) | | defined ( __arm64__ ) | | defined ( __aarch64__ ) | | defined ( _M_ARM64 ) <nl> # define SWIFT_MEMORY_ORDER_CONSUME ( std : : memory_order_relaxed ) <nl> # else <nl> # define SWIFT_MEMORY_ORDER_CONSUME ( std : : memory_order_consume ) <nl> mmm a / stdlib / public / SwiftShims / HeapObject . h <nl> ppp b / stdlib / public / SwiftShims / HeapObject . h <nl> static_assert ( alignof ( HeapObject ) = = alignof ( void * ) , <nl> # define _swift_abi_ObjCReservedLowBits \ <nl> ( unsigned ) SWIFT_ABI_X86_64_OBJC_NUM_RESERVED_LOW_BITS <nl> <nl> - # elif defined ( __arm64__ ) <nl> + # elif defined ( __arm64__ ) | | defined ( __aarch64__ ) | | defined ( _M_ARM64 ) <nl> <nl> # ifdef __APPLE__ <nl> # define _swift_abi_LeastValidPointerValue \ <nl> static_assert ( alignof ( HeapObject ) = = alignof ( void * ) , <nl> # define _swift_abi_LeastValidPointerValue \ <nl> ( __swift_uintptr_t ) SWIFT_ABI_DEFAULT_LEAST_VALID_POINTER <nl> <nl> - # if __i386__ <nl> + # if defined ( __i386__ ) <nl> # define _swift_abi_SwiftSpareBitsMask \ <nl> ( __swift_uintptr_t ) SWIFT_ABI_I386_SWIFT_SPARE_BITS_MASK <nl> - # elif __arm__ <nl> + # elif defined ( __arm__ ) | | defined ( _M_ARM ) <nl> # define _swift_abi_SwiftSpareBitsMask \ <nl> ( __swift_uintptr_t ) SWIFT_ABI_ARM_SWIFT_SPARE_BITS_MASK <nl> # else <nl> mmm a / stdlib / public / runtime / HeapObject . cpp <nl> ppp b / stdlib / public / runtime / HeapObject . cpp <nl> using namespace swift ; <nl> / / / Returns true if the pointer passed to a native retain or release is valid . <nl> / / / If false , the operation should immediately return . <nl> static inline bool isValidPointerForNativeRetain ( const void * p ) { <nl> - # if defined ( __x86_64__ ) | | defined ( __arm64__ ) <nl> + # if defined ( __x86_64__ ) | | defined ( __arm64__ ) | | defined ( __aarch64__ ) | | defined ( _M_ARM64 ) <nl> / / On these platforms , the upper half of address space is reserved for the <nl> / / kernel , so we can assume that pointer values in this range are invalid . <nl> return ( intptr_t ) p > 0 ; <nl> mmm a / stdlib / public / runtime / SwiftObject . mm <nl> ppp b / stdlib / public / runtime / SwiftObject . mm <nl> - ( BOOL ) isNSValue__ { return NO ; } <nl> <nl> # if defined ( __x86_64__ ) <nl> static uintptr_t const objectPointerIsObjCBit = 0x4000000000000000ULL ; <nl> - # elif defined ( __arm64__ ) <nl> + # elif defined ( __arm64__ ) | | defined ( __arch64__ ) | | defined ( _M_ARM64 ) <nl> static uintptr_t const objectPointerIsObjCBit = 0x4000000000000000ULL ; <nl> # else <nl> static uintptr_t const objectPointerIsObjCBit = 0x00000002U ; <nl> mmm a / stdlib / public / runtime / WeakReference . h <nl> ppp b / stdlib / public / runtime / WeakReference . h <nl> class WeakReferenceBits { <nl> # if ! SWIFT_OBJC_INTEROP <nl> NativeMarkerMask = 0 , <nl> NativeMarkerValue = 0 <nl> - # elif __x86_64__ <nl> + # elif defined ( __x86_64__ ) <nl> NativeMarkerMask = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_MASK , <nl> NativeMarkerValue = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_VALUE <nl> - # elif __i386__ <nl> + # elif defined ( __i386__ ) <nl> NativeMarkerMask = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_MASK , <nl> NativeMarkerValue = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_VALUE <nl> - # elif __arm__ <nl> + # elif defined ( __arm__ ) | | defined ( _M_ARM ) <nl> NativeMarkerMask = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_MASK , <nl> NativeMarkerValue = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_VALUE <nl> - # elif __arm64__ <nl> + # elif defined ( __arm64__ ) | | defined ( __aarch64__ ) | | defined ( _M_ARM64 ) <nl> NativeMarkerMask = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_MASK , <nl> NativeMarkerValue = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_VALUE <nl> # else <nl> mmm a / stdlib / public / stubs / MathStubs . cpp <nl> ppp b / stdlib / public / stubs / MathStubs . cpp <nl> extern " C " { <nl> ( defined ( __linux__ ) & & defined ( __aarch64__ ) ) | | \ <nl> ( defined ( __linux__ ) & & defined ( __powerpc64__ ) ) | | \ <nl> ( defined ( __linux__ ) & & defined ( __s390x__ ) ) | | \ <nl> - ( defined ( __ANDROID__ ) & & defined ( __arm64__ ) ) <nl> + ( defined ( __ANDROID__ ) & & defined ( __aarch64__ ) ) <nl> <nl> SWIFT_RUNTIME_STDLIB_API <nl> ti_int <nl> | stdlib : check for ARM / ARM64 more thoroughly ( NFC ) | apple/swift | 2d04b8491b31f379738fca6129c42a294d230510 | 2018-09-21T18:24:03Z |
mmm a / script / create - dist . py <nl> ppp b / script / create - dist . py <nl> <nl> ' atom . exe ' , <nl> ' chromiumcontent . dll ' , <nl> ' content_shell . pak ' , <nl> - ' d3dcompiler_46 . dll ' , <nl> + ' d3dcompiler_47 . dll ' , <nl> ' ffmpegsumo . dll ' , <nl> ' icudtl . dat ' , <nl> ' libEGL . dll ' , <nl> mmm a / script / update - external - binaries . py <nl> ppp b / script / update - external - binaries . py <nl> <nl> from lib . util import safe_mkdir , rm_rf , extract_zip , tempdir , download <nl> <nl> <nl> - VERSION = ' v0 . 4 . 0 ' <nl> + VERSION = ' v0 . 5 . 0 ' <nl> SOURCE_ROOT = os . path . abspath ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) <nl> FRAMEWORKS_URL = ' http : / / github . com / atom / atom - shell - frameworks / releases ' \ <nl> ' / download / ' + VERSION <nl> | win : Ship d3dcompiler_47 . dll | electron/electron | 0477c01fae95576b36e2229eb807a31ed2a8e344 | 2015-03-29T10:33:25Z |
mmm a / test / cctest / test - api . cc <nl> ppp b / test / cctest / test - api . cc <nl> THREADED_TEST ( External ) { <nl> CHECK_EQ ( x , 10 ) ; <nl> <nl> / / Make sure unaligned pointers are wrapped properly . <nl> - char * data = " 0123456789 " ; <nl> + char * data = strdup ( " 0123456789 " ) ; <nl> Local < v8 : : External > zero = v8 : : External : : New ( & data [ 0 ] ) ; <nl> Local < v8 : : External > one = v8 : : External : : New ( & data [ 1 ] ) ; <nl> Local < v8 : : External > two = v8 : : External : : New ( & data [ 2 ] ) ; <nl> THREADED_TEST ( External ) { <nl> CHECK_EQ ( ' 2 ' , * char_ptr ) ; <nl> char_ptr = reinterpret_cast < char * > ( three - > Value ( ) ) ; <nl> CHECK_EQ ( ' 3 ' , * char_ptr ) ; <nl> + free ( data ) ; <nl> } <nl> <nl> <nl> | - Fix constness in tests . | v8/v8 | ce1fe3e4650617fb2b868c0fb86de4228478eb98 | 2009-03-20T23:33:36Z |
mmm a / googlemock / include / gmock / gmock - generated - function - mockers . h <nl> ppp b / googlemock / include / gmock / gmock - generated - function - mockers . h <nl> class FunctionMocker < R ( A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 ) > : public <nl> } <nl> } ; <nl> <nl> + / / Removes the given pointer ; this is a helper for the expectation setter method <nl> + / / for parameterless matchers . <nl> + / / <nl> + / / We want to make sure that the user cannot set a parameterless expectation on <nl> + / / overloaded methods , including methods which are overloaded on const . Example : <nl> + / / <nl> + / / class MockClass { <nl> + / / MOCK_METHOD0 ( GetName , string & ( ) ) ; <nl> + / / MOCK_CONST_METHOD0 ( GetName , const string & ( ) ) ; <nl> + / / } ; <nl> + / / <nl> + / / TEST ( ) { <nl> + / / / / This should be an error , as it ' s not clear which overload is expected . <nl> + / / EXPECT_CALL ( mock , GetName ) . WillOnce ( ReturnRef ( value ) ) ; <nl> + / / } <nl> + / / <nl> + / / Here are the generated expectation - setter methods : <nl> + / / <nl> + / / class MockClass { <nl> + / / / / Overload 1 <nl> + / / MockSpec < string & ( ) > gmock_GetName ( ) { … } <nl> + / / / / Overload 2 . Declared const so that the compiler will generate an <nl> + / / / / error when trying to resolve between this and overload 4 in <nl> + / / / / ' gmock_GetName ( WithoutMatchers ( ) , nullptr ) ' . <nl> + / / MockSpec < string & ( ) > gmock_GetName ( <nl> + / / const WithoutMatchers & , const Function < string & ( ) > * ) const { <nl> + / / / / Removes const from this , calls overload 1 <nl> + / / return AdjustConstness_ ( this ) - > gmock_GetName ( ) ; <nl> + / / } <nl> + / / <nl> + / / / / Overload 3 <nl> + / / const string & gmock_GetName ( ) const { … } <nl> + / / / / Overload 4 <nl> + / / MockSpec < const string & ( ) > gmock_GetName ( <nl> + / / const WithoutMatchers & , const Function < const string & ( ) > * ) const { <nl> + / / / / Does not remove const , calls overload 3 <nl> + / / return AdjustConstness_const ( this ) - > gmock_GetName ( ) ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + template < typename MockType > <nl> + const MockType * AdjustConstness_const ( const MockType * mock ) { <nl> + return mock ; <nl> + } <nl> + <nl> + / / Removes const from and returns the given pointer ; this is a helper for the <nl> + / / expectation setter method for parameterless matchers . <nl> + template < typename MockType > <nl> + MockType * AdjustConstness_ ( const MockType * mock ) { <nl> + return const_cast < MockType * > ( mock ) ; <nl> + } <nl> + <nl> } / / namespace internal <nl> <nl> / / The style guide prohibits " using " statements in a namespace scope <nl> using internal : : FunctionMocker ; <nl> GMOCK_MOCKER_ ( 0 , constness , Method ) . RegisterOwner ( this ) ; \ <nl> return GMOCK_MOCKER_ ( 0 , constness , Method ) . With ( ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 0 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> GMOCK_MOCKER_ ( 1 , constness , Method ) . RegisterOwner ( this ) ; \ <nl> return GMOCK_MOCKER_ ( 1 , constness , Method ) . With ( gmock_a1 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 1 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> GMOCK_MOCKER_ ( 2 , constness , Method ) . RegisterOwner ( this ) ; \ <nl> return GMOCK_MOCKER_ ( 2 , constness , Method ) . With ( gmock_a1 , gmock_a2 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 2 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 3 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 3 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 4 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 , gmock_a4 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 4 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 5 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 , gmock_a4 , gmock_a5 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 5 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 6 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 , gmock_a4 , gmock_a5 , gmock_a6 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 6 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 6 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 7 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 , gmock_a4 , gmock_a5 , gmock_a6 , gmock_a7 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 6 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 7 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 7 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> return GMOCK_MOCKER_ ( 8 , constness , Method ) . With ( gmock_a1 , gmock_a2 , \ <nl> gmock_a3 , gmock_a4 , gmock_a5 , gmock_a6 , gmock_a7 , gmock_a8 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 6 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 7 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 8 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 8 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> gmock_a3 , gmock_a4 , gmock_a5 , gmock_a6 , gmock_a7 , gmock_a8 , \ <nl> gmock_a9 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 6 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 7 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 8 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 9 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 9 , constness , \ <nl> Method ) <nl> <nl> using internal : : FunctionMocker ; <nl> gmock_a3 , gmock_a4 , gmock_a5 , gmock_a6 , gmock_a7 , gmock_a8 , gmock_a9 , \ <nl> gmock_a10 ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( : : testing : : A < GMOCK_ARG_ ( tn , 1 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 2 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 3 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 4 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 5 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 6 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 7 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 8 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 9 , __VA_ARGS__ ) > ( ) , \ <nl> + : : testing : : A < GMOCK_ARG_ ( tn , 10 , __VA_ARGS__ ) > ( ) ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( 10 , constness , \ <nl> Method ) <nl> <nl> mmm a / googlemock / include / gmock / gmock - generated - function - mockers . h . pump <nl> ppp b / googlemock / include / gmock / gmock - generated - function - mockers . h . pump <nl> class FunctionMocker < R ( $ As ) > : public <nl> <nl> <nl> ] ] <nl> + / / Removes the given pointer ; this is a helper for the expectation setter method <nl> + / / for parameterless matchers . <nl> + / / <nl> + / / We want to make sure that the user cannot set a parameterless expectation on <nl> + / / overloaded methods , including methods which are overloaded on const . Example : <nl> + / / <nl> + / / class MockClass { <nl> + / / MOCK_METHOD0 ( GetName , string & ( ) ) ; <nl> + / / MOCK_CONST_METHOD0 ( GetName , const string & ( ) ) ; <nl> + / / } ; <nl> + / / <nl> + / / TEST ( ) { <nl> + / / / / This should be an error , as it ' s not clear which overload is expected . <nl> + / / EXPECT_CALL ( mock , GetName ) . WillOnce ( ReturnRef ( value ) ) ; <nl> + / / } <nl> + / / <nl> + / / Here are the generated expectation - setter methods : <nl> + / / <nl> + / / class MockClass { <nl> + / / / / Overload 1 <nl> + / / MockSpec < string & ( ) > gmock_GetName ( ) { … } <nl> + / / / / Overload 2 . Declared const so that the compiler will generate an <nl> + / / / / error when trying to resolve between this and overload 4 in <nl> + / / / / ' gmock_GetName ( WithoutMatchers ( ) , nullptr ) ' . <nl> + / / MockSpec < string & ( ) > gmock_GetName ( <nl> + / / const WithoutMatchers & , const Function < string & ( ) > * ) const { <nl> + / / / / Removes const from this , calls overload 1 <nl> + / / return AdjustConstness_ ( this ) - > gmock_GetName ( ) ; <nl> + / / } <nl> + / / <nl> + / / / / Overload 3 <nl> + / / const string & gmock_GetName ( ) const { … } <nl> + / / / / Overload 4 <nl> + / / MockSpec < const string & ( ) > gmock_GetName ( <nl> + / / const WithoutMatchers & , const Function < const string & ( ) > * ) const { <nl> + / / / / Does not remove const , calls overload 3 <nl> + / / return AdjustConstness_const ( this ) - > gmock_GetName ( ) ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + template < typename MockType > <nl> + const MockType * AdjustConstness_const ( const MockType * mock ) { <nl> + return mock ; <nl> + } <nl> + <nl> + / / Removes const from and returns the given pointer ; this is a helper for the <nl> + / / expectation setter method for parameterless matchers . <nl> + template < typename MockType > <nl> + MockType * AdjustConstness_ ( const MockType * mock ) { <nl> + return const_cast < MockType * > ( mock ) ; <nl> + } <nl> + <nl> } / / namespace internal <nl> <nl> / / The style guide prohibits " using " statements in a namespace scope <nl> $ var as = [ [ $ for j , \ <nl> $ var matcher_arg_as = [ [ $ for j , \ <nl> [ [ GMOCK_MATCHER_ ( tn , $ j , __VA_ARGS__ ) gmock_a $ j ] ] ] ] <nl> $ var matcher_as = [ [ $ for j , [ [ gmock_a $ j ] ] ] ] <nl> + $ var anything_matchers = [ [ $ for j , \ <nl> + [ [ : : testing : : A < GMOCK_ARG_ ( tn , $ j , __VA_ARGS__ ) > ( ) ] ] ] ] <nl> / / INTERNAL IMPLEMENTATION - DON ' T USE IN USER CODE ! ! ! <nl> # define GMOCK_METHOD $ i [ [ ] ] _ ( tn , constness , ct , Method , . . . ) \ <nl> GMOCK_RESULT_ ( tn , __VA_ARGS__ ) ct Method ( \ <nl> $ var matcher_as = [ [ $ for j , [ [ gmock_a $ j ] ] ] ] <nl> GMOCK_MOCKER_ ( $ i , constness , Method ) . RegisterOwner ( this ) ; \ <nl> return GMOCK_MOCKER_ ( $ i , constness , Method ) . With ( $ matcher_as ) ; \ <nl> } \ <nl> + : : testing : : MockSpec < __VA_ARGS__ > gmock_ # # Method ( \ <nl> + const : : testing : : internal : : WithoutMatchers & , \ <nl> + constness : : testing : : internal : : Function < __VA_ARGS__ > * ) const { \ <nl> + return : : testing : : internal : : AdjustConstness_ # # constness ( this ) - > \ <nl> + gmock_ # # Method ( $ anything_matchers ) ; \ <nl> + } \ <nl> mutable : : testing : : FunctionMocker < __VA_ARGS__ > GMOCK_MOCKER_ ( $ i , constness , Method ) <nl> <nl> <nl> mmm a / googlemock / include / gmock / gmock - spec - builders . h <nl> ppp b / googlemock / include / gmock / gmock - spec - builders . h <nl> class MockSpec { <nl> file , line , source_text , matchers_ ) ; <nl> } <nl> <nl> + / / This operator overload is used to swallow the superfluous parameter list <nl> + / / introduced by the ON / EXPECT_CALL macros . See the macro comments for more <nl> + / / explanation . <nl> + MockSpec < F > & operator ( ) ( const internal : : WithoutMatchers & , void * const ) { <nl> + return * this ; <nl> + } <nl> + <nl> private : <nl> template < typename Function > <nl> friend class internal : : FunctionMocker ; <nl> inline Expectation : : Expectation ( internal : : ExpectationBase & exp ) / / NOLINT <nl> <nl> } / / namespace testing <nl> <nl> - / / A separate macro is required to avoid compile errors when the name <nl> - / / of the method used in call is a result of macro expansion . <nl> - / / See CompilesWithMethodNameExpandedFromMacro tests in <nl> - / / internal / gmock - spec - builders_test . cc for more details . <nl> - # define GMOCK_ON_CALL_IMPL_ ( obj , call ) \ <nl> - ( ( obj ) . gmock_ # # call ) . InternalDefaultActionSetAt ( __FILE__ , __LINE__ , \ <nl> - # obj , # call ) <nl> - # define ON_CALL ( obj , call ) GMOCK_ON_CALL_IMPL_ ( obj , call ) <nl> - <nl> - # define GMOCK_EXPECT_CALL_IMPL_ ( obj , call ) \ <nl> - ( ( obj ) . gmock_ # # call ) . InternalExpectedAt ( __FILE__ , __LINE__ , # obj , # call ) <nl> - # define EXPECT_CALL ( obj , call ) GMOCK_EXPECT_CALL_IMPL_ ( obj , call ) <nl> + / / Implementation for ON_CALL and EXPECT_CALL macros . A separate macro is <nl> + / / required to avoid compile errors when the name of the method used in call is <nl> + / / a result of macro expansion . See CompilesWithMethodNameExpandedFromMacro <nl> + / / tests in internal / gmock - spec - builders_test . cc for more details . <nl> + / / <nl> + / / This macro supports statements both with and without parameter matchers . If <nl> + / / the parameter list is omitted , gMock will accept any parameters , which allows <nl> + / / tests to be written that don ' t need to encode the number of method <nl> + / / parameter . This technique may only be used for non - overloaded methods . <nl> + / / <nl> + / / / / These are the same : <nl> + / / ON_CALL ( mock , NoArgsMethod ( ) ) . WillByDefault ( … ) ; <nl> + / / ON_CALL ( mock , NoArgsMethod ) . WillByDefault ( … ) ; <nl> + / / <nl> + / / / / As are these : <nl> + / / ON_CALL ( mock , TwoArgsMethod ( _ , _ ) ) . WillByDefault ( … ) ; <nl> + / / ON_CALL ( mock , TwoArgsMethod ) . WillByDefault ( … ) ; <nl> + / / <nl> + / / / / Can also specify args if you want , of course : <nl> + / / ON_CALL ( mock , TwoArgsMethod ( _ , 45 ) ) . WillByDefault ( … ) ; <nl> + / / <nl> + / / / / Overloads work as long as you specify parameters : <nl> + / / ON_CALL ( mock , OverloadedMethod ( _ ) ) . WillByDefault ( … ) ; <nl> + / / ON_CALL ( mock , OverloadedMethod ( _ , _ ) ) . WillByDefault ( … ) ; <nl> + / / <nl> + / / / / Oops ! Which overload did you want ? <nl> + / / ON_CALL ( mock , OverloadedMethod ) . WillByDefault ( … ) ; <nl> + / / = > ERROR : call to member function ' gmock_OverloadedMethod ' is ambiguous <nl> + / / <nl> + / / How this works : The mock class uses two overloads of the gmock_Method <nl> + / / expectation setter method plus an operator ( ) overload on the MockSpec object . <nl> + / / In the matcher list form , the macro expands to : <nl> + / / <nl> + / / / / This statement : <nl> + / / ON_CALL ( mock , TwoArgsMethod ( _ , 45 ) ) … <nl> + / / <nl> + / / / / … expands to : <nl> + / / mock . gmock_TwoArgsMethod ( _ , 45 ) ( WithoutMatchers ( ) , nullptr ) … <nl> + / / | mmmmmmmmmmmm - vmmmmmmmmmmmmmmm | | mmmmmmmmmmmmvmmmmmmmmmmmm - | <nl> + / / invokes first overload swallowed by operator ( ) <nl> + / / <nl> + / / / / … which is essentially : <nl> + / / mock . gmock_TwoArgsMethod ( _ , 45 ) … <nl> + / / <nl> + / / Whereas the form without a matcher list : <nl> + / / <nl> + / / / / This statement : <nl> + / / ON_CALL ( mock , TwoArgsMethod ) … <nl> + / / <nl> + / / / / … expands to : <nl> + / / mock . gmock_TwoArgsMethod ( WithoutMatchers ( ) , nullptr ) … <nl> + / / | mmmmmmmmmmmmmmmmmmmmm - - vmmmmmmmmmmmmmmmmmmmmmmmm - - | <nl> + / / invokes second overload <nl> + / / <nl> + / / / / … which is essentially : <nl> + / / mock . gmock_TwoArgsMethod ( _ , _ ) … <nl> + / / <nl> + / / The WithoutMatchers ( ) argument is used to disambiguate overloads and to <nl> + / / block the caller from accidentally invoking the second overload directly . The <nl> + / / second argument is an internal type derived from the method signature . The <nl> + / / failure to disambiguate two overloads of this method in the ON_CALL statement <nl> + / / is how we block callers from setting expectations on overloaded methods . <nl> + # define GMOCK_ON_CALL_IMPL_ ( mock_expr , Setter , call ) \ <nl> + ( ( mock_expr ) . gmock_ # # call ) ( : : testing : : internal : : GetWithoutMatchers ( ) , NULL ) \ <nl> + . Setter ( __FILE__ , __LINE__ , # mock_expr , # call ) <nl> + <nl> + # define ON_CALL ( obj , call ) \ <nl> + GMOCK_ON_CALL_IMPL_ ( obj , InternalDefaultActionSetAt , call ) <nl> + <nl> + # define EXPECT_CALL ( obj , call ) \ <nl> + GMOCK_ON_CALL_IMPL_ ( obj , InternalExpectedAt , call ) <nl> <nl> # endif / / GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ <nl> mmm a / googlemock / include / gmock / internal / gmock - internal - utils . h <nl> ppp b / googlemock / include / gmock / internal / gmock - internal - utils . h <nl> GTEST_API_ bool LogIsVisible ( LogSeverity severity ) ; <nl> GTEST_API_ void Log ( LogSeverity severity , const std : : string & message , <nl> int stack_frames_to_skip ) ; <nl> <nl> + / / A marker class that is used to resolve parameterless expectations to the <nl> + / / correct overload . This must not be instantiable , to prevent client code from <nl> + / / accidentally resolving to the overload ; for example : <nl> + / / <nl> + / / ON_CALL ( mock , Method ( { } , nullptr ) ) … <nl> + / / <nl> + class WithoutMatchers { <nl> + private : <nl> + WithoutMatchers ( ) { } <nl> + friend GTEST_API_ WithoutMatchers GetWithoutMatchers ( ) ; <nl> + } ; <nl> + <nl> + / / Internal use only : access the singleton instance of WithoutMatchers . <nl> + GTEST_API_ WithoutMatchers GetWithoutMatchers ( ) ; <nl> + <nl> / / TODO ( wan @ google . com ) : group all type utilities together . <nl> <nl> / / Type traits . <nl> mmm a / googlemock / src / gmock - internal - utils . cc <nl> ppp b / googlemock / src / gmock - internal - utils . cc <nl> GTEST_API_ void Log ( LogSeverity severity , const std : : string & message , <nl> std : : cout < < : : std : : flush ; <nl> } <nl> <nl> + GTEST_API_ WithoutMatchers GetWithoutMatchers ( ) { return WithoutMatchers ( ) ; } <nl> + <nl> GTEST_API_ void IllegalDoDefault ( const char * file , int line ) { <nl> internal : : Assert ( <nl> false , file , line , <nl> mmm a / googlemock / test / gmock - matchers_test . cc <nl> ppp b / googlemock / test / gmock - matchers_test . cc <nl> TEST ( AllArgsTest , WorksInWithClause ) { <nl> EXPECT_EQ ( 2 , helper . Helper ( ' a ' , 1 ) ) ; <nl> } <nl> <nl> + class OptionalMatchersHelper { <nl> + public : <nl> + OptionalMatchersHelper ( ) { } <nl> + <nl> + MOCK_METHOD0 ( NoArgs , int ( ) ) ; <nl> + <nl> + MOCK_METHOD1 ( OneArg , int ( int y ) ) ; <nl> + <nl> + MOCK_METHOD2 ( TwoArgs , int ( char x , int y ) ) ; <nl> + <nl> + MOCK_METHOD1 ( Overloaded , int ( char x ) ) ; <nl> + MOCK_METHOD2 ( Overloaded , int ( char x , int y ) ) ; <nl> + <nl> + private : <nl> + GTEST_DISALLOW_COPY_AND_ASSIGN_ ( OptionalMatchersHelper ) ; <nl> + } ; <nl> + <nl> + TEST ( AllArgsTest , WorksWithoutMatchers ) { <nl> + OptionalMatchersHelper helper ; <nl> + <nl> + ON_CALL ( helper , NoArgs ) . WillByDefault ( Return ( 10 ) ) ; <nl> + ON_CALL ( helper , OneArg ) . WillByDefault ( Return ( 20 ) ) ; <nl> + ON_CALL ( helper , TwoArgs ) . WillByDefault ( Return ( 30 ) ) ; <nl> + <nl> + EXPECT_EQ ( 10 , helper . NoArgs ( ) ) ; <nl> + EXPECT_EQ ( 20 , helper . OneArg ( 1 ) ) ; <nl> + EXPECT_EQ ( 30 , helper . TwoArgs ( ' \ 1 ' , 2 ) ) ; <nl> + <nl> + EXPECT_CALL ( helper , NoArgs ) . Times ( 1 ) ; <nl> + EXPECT_CALL ( helper , OneArg ) . WillOnce ( Return ( 100 ) ) ; <nl> + EXPECT_CALL ( helper , OneArg ( 17 ) ) . WillOnce ( Return ( 200 ) ) ; <nl> + EXPECT_CALL ( helper , TwoArgs ) . Times ( 0 ) ; <nl> + <nl> + EXPECT_EQ ( 10 , helper . NoArgs ( ) ) ; <nl> + EXPECT_EQ ( 100 , helper . OneArg ( 1 ) ) ; <nl> + EXPECT_EQ ( 200 , helper . OneArg ( 17 ) ) ; <nl> + } <nl> + <nl> / / Tests that ASSERT_THAT ( ) and EXPECT_THAT ( ) work when the value <nl> / / matches the matcher . <nl> TEST ( MatcherAssertionTest , WorksWhenMatcherIsSatisfied ) { <nl> TEST ( NotTest , WorksOnMoveOnlyType ) { <nl> # if defined_MSC_VER <nl> # pragma warning ( pop ) <nl> # endif <nl> - <nl> mmm a / googlemock / test / gmock - spec - builders_test . cc <nl> ppp b / googlemock / test / gmock - spec - builders_test . cc <nl> using testing : : Mock ; <nl> using testing : : NaggyMock ; <nl> using testing : : Ne ; <nl> using testing : : Return ; <nl> + using testing : : SaveArg ; <nl> using testing : : Sequence ; <nl> using testing : : SetArgPointee ; <nl> using testing : : internal : : ExpectationTester ; <nl> TEST ( SynchronizationTest , CanCallMockMethodInAction ) { <nl> / / EXPECT_CALL ( ) did not specify an action . <nl> } <nl> <nl> + TEST ( ParameterlessExpectationsTest , CanSetExpectationsWithoutMatchers ) { <nl> + MockA a ; <nl> + int do_a_arg0 = 0 ; <nl> + ON_CALL ( a , DoA ) . WillByDefault ( SaveArg < 0 > ( & do_a_arg0 ) ) ; <nl> + int do_a_47_arg0 = 0 ; <nl> + ON_CALL ( a , DoA ( 47 ) ) . WillByDefault ( SaveArg < 0 > ( & do_a_47_arg0 ) ) ; <nl> + <nl> + a . DoA ( 17 ) ; <nl> + EXPECT_THAT ( do_a_arg0 , 17 ) ; <nl> + EXPECT_THAT ( do_a_47_arg0 , 0 ) ; <nl> + a . DoA ( 47 ) ; <nl> + EXPECT_THAT ( do_a_arg0 , 17 ) ; <nl> + EXPECT_THAT ( do_a_47_arg0 , 47 ) ; <nl> + <nl> + ON_CALL ( a , Binary ) . WillByDefault ( Return ( true ) ) ; <nl> + ON_CALL ( a , Binary ( _ , 14 ) ) . WillByDefault ( Return ( false ) ) ; <nl> + EXPECT_THAT ( a . Binary ( 14 , 17 ) , true ) ; <nl> + EXPECT_THAT ( a . Binary ( 17 , 14 ) , false ) ; <nl> + } <nl> + <nl> + TEST ( ParameterlessExpectationsTest , CanSetExpectationsForOverloadedMethods ) { <nl> + MockB b ; <nl> + ON_CALL ( b , DoB ( ) ) . WillByDefault ( Return ( 9 ) ) ; <nl> + ON_CALL ( b , DoB ( 5 ) ) . WillByDefault ( Return ( 11 ) ) ; <nl> + <nl> + EXPECT_THAT ( b . DoB ( ) , 9 ) ; <nl> + EXPECT_THAT ( b . DoB ( 1 ) , 0 ) ; / / default value <nl> + EXPECT_THAT ( b . DoB ( 5 ) , 11 ) ; <nl> + } <nl> + <nl> + struct MockWithConstMethods { <nl> + public : <nl> + MOCK_CONST_METHOD1 ( Foo , int ( int ) ) ; <nl> + MOCK_CONST_METHOD2 ( Bar , int ( int , const char * ) ) ; <nl> + } ; <nl> + <nl> + TEST ( ParameterlessExpectationsTest , CanSetExpectationsForConstMethods ) { <nl> + MockWithConstMethods mock ; <nl> + ON_CALL ( mock , Foo ) . WillByDefault ( Return ( 7 ) ) ; <nl> + ON_CALL ( mock , Bar ) . WillByDefault ( Return ( 33 ) ) ; <nl> + <nl> + EXPECT_THAT ( mock . Foo ( 17 ) , 7 ) ; <nl> + EXPECT_THAT ( mock . Bar ( 27 , " purple " ) , 33 ) ; <nl> + } <nl> + <nl> + class MockConstOverload { <nl> + public : <nl> + MOCK_METHOD1 ( Overloaded , int ( int ) ) ; <nl> + MOCK_CONST_METHOD1 ( Overloaded , int ( int ) ) ; <nl> + } ; <nl> + <nl> + TEST ( ParameterlessExpectationsTest , <nl> + CanSetExpectationsForConstOverloadedMethods ) { <nl> + MockConstOverload mock ; <nl> + ON_CALL ( mock , Overloaded ( _ ) ) . WillByDefault ( Return ( 7 ) ) ; <nl> + ON_CALL ( mock , Overloaded ( 5 ) ) . WillByDefault ( Return ( 9 ) ) ; <nl> + ON_CALL ( Const ( mock ) , Overloaded ( 5 ) ) . WillByDefault ( Return ( 11 ) ) ; <nl> + ON_CALL ( Const ( mock ) , Overloaded ( 7 ) ) . WillByDefault ( Return ( 13 ) ) ; <nl> + <nl> + EXPECT_THAT ( mock . Overloaded ( 1 ) , 7 ) ; <nl> + EXPECT_THAT ( mock . Overloaded ( 5 ) , 9 ) ; <nl> + EXPECT_THAT ( mock . Overloaded ( 7 ) , 7 ) ; <nl> + <nl> + const MockConstOverload & const_mock = mock ; <nl> + EXPECT_THAT ( const_mock . Overloaded ( 1 ) , 0 ) ; <nl> + EXPECT_THAT ( const_mock . Overloaded ( 5 ) , 11 ) ; <nl> + EXPECT_THAT ( const_mock . Overloaded ( 7 ) , 13 ) ; <nl> + } <nl> + <nl> } / / namespace <nl> <nl> / / Allows the user to define their own main and then invoke gmock_main <nl> | Merge pull request from dnsunderland / parameterless | google/googletest | a6f06bf2fd3b832822cd4e9e554b7d47f32ec084 | 2018-04-19T22:44:01Z |
mmm a / swoole_server . c <nl> ppp b / swoole_server . c <nl> int php_swoole_task_pack ( swEventData * task , zval * data TSRMLS_DC ) <nl> } <nl> <nl> # if PHP_MAJOR_VERSION > = 7 <nl> - if ( SWOOLE_G ( fast_serialize ) ) <nl> + if ( SWOOLE_G ( fast_serialize ) & & serialized_string ) <nl> { <nl> zend_string_release ( serialized_string ) ; <nl> } <nl> | Merge remote - tracking branch ' origin / master ' | swoole/swoole-src | 91af5a4040669e1226f26764a542c1f12b1fb270 | 2017-03-13T08:35:30Z |
mmm a / PowerEditor / src / ScitillaComponent / ScintillaEditView . cpp <nl> ppp b / PowerEditor / src / ScitillaComponent / ScintillaEditView . cpp <nl> void ScintillaEditView : : bufferUpdated ( Buffer * buffer , int mask ) { <nl> <nl> void ScintillaEditView : : collapse ( int level2Collapse , bool mode ) <nl> { <nl> - / / execute ( SCI_COLOURISE , 0 , - 1 ) ; / / TODO : is this needed ? <nl> + execute ( SCI_COLOURISE , 0 , - 1 ) ; / / make sure folding is done right ( no cut - offs ) <nl> int maxLine = execute ( SCI_GETLINECOUNT ) ; <nl> <nl> for ( int line = 0 ; line < maxLine ; line + + ) <nl> void ScintillaEditView : : collapse ( int level2Collapse , bool mode ) <nl> <nl> void ScintillaEditView : : foldCurrentPos ( bool mode ) <nl> { <nl> - / / execute ( SCI_COLOURISE , 0 , - 1 ) ; <nl> + execute ( SCI_COLOURISE , 0 , - 1 ) ; / / make sure folding is done right ( no cut - offs ) <nl> int currentLine = this - > getCurrentLineNumber ( ) ; <nl> <nl> int headerLine ; <nl> void ScintillaEditView : : foldCurrentPos ( bool mode ) <nl> <nl> void ScintillaEditView : : foldAll ( bool mode ) <nl> { <nl> - / / execute ( SCI_COLOURISE , 0 , - 1 ) ; <nl> + execute ( SCI_COLOURISE , 0 , - 1 ) ; / / make sure folding is done right ( no cut - offs ) <nl> int maxLine = execute ( SCI_GETLINECOUNT ) ; <nl> <nl> for ( int line = 0 ; line < maxLine ; line + + ) <nl> | Fix folding not occuring over entire document | notepad-plus-plus/notepad-plus-plus | 90f5488b597648fecddfb131456745438aac733f | 2008-09-01T22:08:26Z |
mmm a / include / swift / AST / ASTContext . h <nl> ppp b / include / swift / AST / ASTContext . h <nl> namespace swift { <nl> class InFlightDiagnostic ; <nl> class IterableDeclContext ; <nl> class LazyContextData ; <nl> - class LazyGenericContextData ; <nl> class LazyIterableDeclContextData ; <nl> class LazyMemberLoader ; <nl> class LazyResolver ; <nl> class ASTContext final { <nl> LazyContextData * getOrCreateLazyContextData ( const DeclContext * decl , <nl> LazyMemberLoader * lazyLoader ) ; <nl> <nl> - / / / Get the lazy function data for the given generic context . <nl> - / / / <nl> - / / / \ param lazyLoader If non - null , the lazy loader to use when creating the <nl> - / / / function data . The pointer must either be null or be consistent <nl> - / / / across all calls for the same \ p func . <nl> - LazyGenericContextData * getOrCreateLazyGenericContextData ( <nl> - const GenericContext * dc , <nl> - LazyMemberLoader * lazyLoader ) ; <nl> - <nl> / / / Get the lazy iterable context for the given iterable declaration context . <nl> / / / <nl> / / / \ param lazyLoader If non - null , the lazy loader to use when creating the <nl> class ASTContext final { <nl> GenericSignatureBuilder * getOrCreateGenericSignatureBuilder ( <nl> CanGenericSignature sig ) ; <nl> <nl> - / / / Retrieve or create the canonical generic environment of a canonical <nl> - / / / generic signature builder . <nl> - GenericEnvironment * getOrCreateCanonicalGenericEnvironment ( <nl> - GenericSignatureBuilder * builder , <nl> - GenericSignature * sig ) ; <nl> - <nl> / / / Retrieve a generic signature with a single unconstrained type parameter , <nl> / / / like ` < T > ` . <nl> CanGenericSignature getSingleGenericParameterSignature ( ) const ; <nl> mmm a / include / swift / AST / Decl . h <nl> ppp b / include / swift / AST / Decl . h <nl> class alignas ( 8 ) _GenericContext { <nl> / / / moves the trailing where clause into the generic parameter list . <nl> TrailingWhereClause * TrailingWhere = nullptr ; <nl> <nl> - / / / The generic signature or environment of this declaration . <nl> - / / / <nl> - / / / When this declaration stores only a signature , the generic <nl> - / / / environment will be lazily loaded . <nl> - mutable llvm : : PointerUnion < GenericSignature * , GenericEnvironment * > <nl> - GenericSigOrEnv ; <nl> + / / / The generic signature of this declaration . <nl> + GenericSignature * GenericSig = nullptr ; <nl> } ; <nl> <nl> class GenericContext : private _GenericContext , public DeclContext { <nl> - / / / Lazily populate the generic environment . <nl> - GenericEnvironment * getLazyGenericEnvironmentSlow ( ) const ; <nl> - <nl> protected : <nl> GenericContext ( DeclContextKind Kind , DeclContext * Parent ) <nl> : _GenericContext ( ) , DeclContext ( Kind , Parent ) { } <nl> class GenericContext : private _GenericContext , public DeclContext { <nl> / / / Retrieve the generic requirements . <nl> ArrayRef < Requirement > getGenericRequirements ( ) const ; <nl> <nl> - / / / Set a lazy generic environment . <nl> - void setLazyGenericEnvironment ( LazyMemberLoader * lazyLoader , <nl> - GenericSignature * genericSig , <nl> - uint64_t genericEnvData ) ; <nl> - <nl> - / / / Whether this generic context has a lazily - created generic environment <nl> - / / / that has not yet been constructed . <nl> - bool hasLazyGenericEnvironment ( ) const ; <nl> - <nl> - / / / Set the generic context of this context . <nl> - void setGenericEnvironment ( GenericEnvironment * genericEnv ) ; <nl> + / / / Set the generic signature of this context . <nl> + void setGenericSignature ( GenericSignature * genericSig ) ; <nl> <nl> / / / Retrieve the position of any where clause for this context ' s <nl> / / / generic parameters . <nl> mmm a / include / swift / AST / DeclContext . h <nl> ppp b / include / swift / AST / DeclContext . h <nl> class alignas ( 1 < < DeclContextAlignInBits ) DeclContext { <nl> / / / of its parents . <nl> GenericEnvironment * getGenericEnvironmentOfContext ( ) const ; <nl> <nl> - / / / Whether the context has a generic environment that will be constructed <nl> - / / / on first access ( but has not yet been constructed ) . <nl> - bool contextHasLazyGenericEnvironment ( ) const ; <nl> - <nl> / / / Map an interface type to a contextual type within this context . <nl> Type mapTypeIntoContext ( Type type ) const ; <nl> <nl> mmm a / include / swift / AST / GenericEnvironment . h <nl> ppp b / include / swift / AST / GenericEnvironment . h <nl> class alignas ( 1 < < DeclAlignInBits ) GenericEnvironment final <nl> : private llvm : : TrailingObjects < GenericEnvironment , Type > { <nl> GenericSignature * Signature = nullptr ; <nl> GenericSignatureBuilder * Builder = nullptr ; <nl> - DeclContext * OwningDC = nullptr ; <nl> <nl> friend TrailingObjects ; <nl> <nl> class alignas ( 1 < < DeclAlignInBits ) GenericEnvironment final <nl> GenericEnvironment * getIncomplete ( GenericSignature * signature , <nl> GenericSignatureBuilder * builder ) ; <nl> <nl> - / / / Set the owning declaration context for this generic environment . <nl> - void setOwningDeclContext ( DeclContext * owningDC ) ; <nl> - <nl> - / / / Retrieve the declaration context that owns this generic environment , if <nl> - / / / there is one . <nl> - / / / <nl> - / / / Note that several generic environments may refer to the same declaration <nl> - / / / context , because non - generic declarations nested within generic ones <nl> - / / / inherit the enclosing generic environment . In such cases , the owning <nl> - / / / context is the outermost context . <nl> - DeclContext * getOwningDeclContext ( ) const { return OwningDC ; } <nl> - <nl> / / / Add a mapping of a generic parameter to a specific type ( which may be <nl> / / / an archetype ) <nl> void addMapping ( GenericParamKey key , Type contextType ) ; <nl> mmm a / include / swift / AST / GenericSignature . h <nl> ppp b / include / swift / AST / GenericSignature . h <nl> class GenericSignatureBuilder ; <nl> class ProtocolConformanceRef ; <nl> class ProtocolType ; <nl> class SubstitutionMap ; <nl> + class GenericEnvironment ; <nl> <nl> / / / An access path used to find a particular protocol conformance within <nl> / / / a generic signature . <nl> class alignas ( 1 < < TypeAlignInBits ) GenericSignature final <nl> unsigned NumGenericParams ; <nl> unsigned NumRequirements ; <nl> <nl> + GenericEnvironment * GenericEnv = nullptr ; <nl> + <nl> / / Make vanilla new / delete illegal . <nl> void * operator new ( size_t Bytes ) = delete ; <nl> void operator delete ( void * Data ) = delete ; <nl> class alignas ( 1 < < TypeAlignInBits ) GenericSignature final <nl> static ASTContext & getASTContext ( TypeArrayView < GenericTypeParamType > params , <nl> ArrayRef < Requirement > requirements ) ; <nl> <nl> - / / / Retrieve the generic signature builder for the given generic signature . <nl> - GenericSignatureBuilder * getGenericSignatureBuilder ( ) ; <nl> - <nl> void buildConformanceAccessPath ( <nl> SmallVectorImpl < ConformanceAccessPath : : Entry > & path , <nl> ArrayRef < Requirement > reqs , <nl> class alignas ( 1 < < TypeAlignInBits ) GenericSignature final <nl> / / / Canonicalize the components of a generic signature . <nl> CanGenericSignature getCanonicalSignature ( ) const ; <nl> <nl> - / / / Create a new generic environment that provides fresh contextual types <nl> + / / / Retrieve the generic signature builder for the given generic signature . <nl> + GenericSignatureBuilder * getGenericSignatureBuilder ( ) ; <nl> + <nl> + / / / Returns the generic environment that provides fresh contextual types <nl> / / / ( archetypes ) that correspond to the interface types in this generic <nl> / / / signature . <nl> - GenericEnvironment * createGenericEnvironment ( ) ; <nl> + GenericEnvironment * getGenericEnvironment ( ) ; <nl> <nl> / / / Uniquing for the ASTContext . <nl> void Profile ( llvm : : FoldingSetNodeID & ID ) { <nl> mmm a / include / swift / AST / LazyResolver . h <nl> ppp b / include / swift / AST / LazyResolver . h <nl> class LazyContextData { <nl> LazyMemberLoader * loader ; <nl> } ; <nl> <nl> - / / / Context data for generic contexts . <nl> - class LazyGenericContextData : public LazyContextData { <nl> - public : <nl> - / / / The context data used for loading the generic environment . <nl> - uint64_t genericEnvData = 0 ; <nl> - } ; <nl> - <nl> / / / Context data for iterable decl contexts . <nl> - class LazyIterableDeclContextData : public LazyGenericContextData { <nl> + class LazyIterableDeclContextData : public LazyContextData { <nl> public : <nl> / / / The context data used for loading all of the members of the iterable <nl> / / / context . <nl> class alignas ( void * ) LazyMemberLoader { <nl> virtual Type loadAssociatedTypeDefault ( const AssociatedTypeDecl * ATD , <nl> uint64_t contextData ) = 0 ; <nl> <nl> - / / / Returns the generic environment . <nl> - virtual GenericEnvironment * loadGenericEnvironment ( const DeclContext * decl , <nl> - uint64_t contextData ) = 0 ; <nl> - <nl> / / / Loads the requirement signature for a protocol . <nl> virtual void <nl> loadRequirementSignature ( const ProtocolDecl * proto , uint64_t contextData , <nl> mmm a / include / swift / AST / Type . h <nl> ppp b / include / swift / AST / Type . h <nl> class CanGenericSignature { <nl> explicit CanGenericSignature ( GenericSignature * Signature ) ; <nl> ArrayRef < CanTypeWrapper < GenericTypeParamType > > getGenericParams ( ) const ; <nl> <nl> - / / / Retrieve the canonical generic environment associated with this <nl> - / / / generic signature . <nl> - GenericEnvironment * getGenericEnvironment ( ) const ; <nl> - <nl> GenericSignature * operator - > ( ) const { <nl> return Signature ; <nl> } <nl> class CanGenericSignature { <nl> return Signature ; <nl> } <nl> <nl> - bool operator = = ( const swift : : CanGenericSignature & other ) { <nl> + bool operator = = ( const swift : : CanGenericSignature & other ) { <nl> return Signature = = other . Signature ; <nl> } <nl> } ; <nl> mmm a / include / swift / Basic / Statistics . def <nl> ppp b / include / swift / Basic / Statistics . def <nl> FRONTEND_STATISTIC ( Sema , NumFunctionsTypechecked ) <nl> / / / amount of work the GSB does analyzing type signatures . <nl> FRONTEND_STATISTIC ( Sema , NumGenericSignatureBuilders ) <nl> <nl> - / / / Number of lazy generic environments registered . <nl> - FRONTEND_STATISTIC ( Sema , NumLazyGenericEnvironments ) <nl> - <nl> - / / / Number of lazy generic environments deserialized . <nl> - FRONTEND_STATISTIC ( Sema , NumLazyGenericEnvironmentsLoaded ) <nl> - <nl> / / / Number of lazy requirement signatures registered . <nl> FRONTEND_STATISTIC ( Sema , NumLazyRequirementSignatures ) <nl> <nl> mmm a / lib / AST / ASTContext . cpp <nl> ppp b / lib / AST / ASTContext . cpp <nl> FOR_KNOWN_FOUNDATION_TYPES ( CACHE_FOUNDATION_DECL ) <nl> llvm : : DenseMap < GenericSignature * , std : : unique_ptr < GenericSignatureBuilder > > <nl> GenericSignatureBuilders ; <nl> <nl> - / / / Canonical generic environments for canonical generic signatures . <nl> - / / / <nl> - / / / The keys are the generic signature builders in <nl> - / / / \ c GenericSignatureBuilders . <nl> - llvm : : DenseMap < GenericSignatureBuilder * , GenericEnvironment * > <nl> - CanonicalGenericEnvironments ; <nl> - <nl> / / / The set of function types . <nl> llvm : : FoldingSet < FunctionType > FunctionTypes ; <nl> <nl> GenericSignatureBuilder * ASTContext : : getOrCreateGenericSignatureBuilder ( <nl> return builder ; <nl> } <nl> <nl> - GenericEnvironment * ASTContext : : getOrCreateCanonicalGenericEnvironment ( <nl> - GenericSignatureBuilder * builder , <nl> - GenericSignature * sig ) { <nl> - auto arena = getArena ( sig ) ; <nl> - auto & canonicalGenericEnvironments = <nl> - getImpl ( ) . getArena ( arena ) . CanonicalGenericEnvironments ; <nl> - <nl> - auto known = canonicalGenericEnvironments . find ( builder ) ; <nl> - if ( known ! = canonicalGenericEnvironments . end ( ) ) <nl> - return known - > second ; <nl> - <nl> - auto env = sig - > createGenericEnvironment ( ) ; <nl> - canonicalGenericEnvironments [ builder ] = env ; <nl> - return env ; <nl> - } <nl> - <nl> Optional < llvm : : TinyPtrVector < ValueDecl * > > <nl> OverriddenDeclsRequest : : getCachedResult ( ) const { <nl> auto decl = std : : get < 0 > ( getStorage ( ) ) ; <nl> LazyContextData * ASTContext : : getOrCreateLazyContextData ( <nl> assert ( lazyLoader & & " Queried lazy data for non - lazy iterable context " ) ; <nl> if ( isa < ProtocolDecl > ( dc ) ) <nl> entry = Allocate < LazyProtocolData > ( ) ; <nl> - else if ( isa < NominalTypeDecl > ( dc ) | | isa < ExtensionDecl > ( dc ) ) <nl> + else { <nl> + assert ( isa < NominalTypeDecl > ( dc ) | | isa < ExtensionDecl > ( dc ) ) ; <nl> entry = Allocate < LazyIterableDeclContextData > ( ) ; <nl> - else <nl> - entry = Allocate < LazyGenericContextData > ( ) ; <nl> + } <nl> <nl> entry - > loader = lazyLoader ; <nl> return entry ; <nl> LazyIterableDeclContextData * ASTContext : : getOrCreateLazyIterableContextData ( <nl> lazyLoader ) ; <nl> } <nl> <nl> - LazyGenericContextData * ASTContext : : getOrCreateLazyGenericContextData ( <nl> - const GenericContext * dc , <nl> - LazyMemberLoader * lazyLoader ) { <nl> - return ( LazyGenericContextData * ) getOrCreateLazyContextData ( dc , <nl> - lazyLoader ) ; <nl> - } <nl> - <nl> bool ASTContext : : hasDelayedConformanceErrors ( ) const { <nl> for ( const auto & entry : getImpl ( ) . DelayedConformanceDiags ) { <nl> auto & diagnostics = entry . getSecond ( ) ; <nl> OpaqueTypeArchetypeType : : get ( OpaqueTypeDecl * Decl , <nl> <nl> / / Create a generic environment and bind the opaque archetype to the <nl> / / opaque interface type from the decl ' s signature . <nl> - auto env = signature - > createGenericEnvironment ( ) ; <nl> + auto * builder = signature - > getGenericSignatureBuilder ( ) ; <nl> + auto * env = GenericEnvironment : : getIncomplete ( signature , builder ) ; <nl> env - > addMapping ( GenericParamKey ( opaqueInterfaceTy ) , newOpaque ) ; <nl> newOpaque - > Environment = env ; <nl> <nl> GenericEnvironment * OpenedArchetypeType : : getGenericEnvironment ( ) const { <nl> / / Create a generic environment to represent the opened type . <nl> auto signature = ctx . getExistentialSignature ( Opened - > getCanonicalType ( ) , <nl> nullptr ) ; <nl> - auto env = signature - > createGenericEnvironment ( ) ; <nl> + auto * builder = signature - > getGenericSignatureBuilder ( ) ; <nl> + auto * env = GenericEnvironment : : getIncomplete ( signature , builder ) ; <nl> env - > addMapping ( signature - > getGenericParams ( ) [ 0 ] , thisType ) ; <nl> Environment = env ; <nl> <nl> mmm a / lib / AST / ASTDumper . cpp <nl> ppp b / lib / AST / ASTDumper . cpp <nl> namespace { <nl> printArchetypeCommon ( T , " primary_archetype_type " , label ) ; <nl> printField ( " name " , T - > getFullName ( ) ) ; <nl> OS < < " \ n " ; <nl> - auto genericEnv = T - > getGenericEnvironment ( ) ; <nl> - if ( auto owningDC = genericEnv - > getOwningDeclContext ( ) ) { <nl> - owningDC - > printContext ( OS , Indent + 2 ) ; <nl> - } <nl> printArchetypeNestedTypes ( T ) ; <nl> PrintWithColorRAII ( OS , ParenthesisColor ) < < ' ) ' ; <nl> } <nl> mmm a / lib / AST / ASTVerifier . cpp <nl> ppp b / lib / AST / ASTVerifier . cpp <nl> <nl> # include " swift / AST / Expr . h " <nl> # include " swift / AST / ForeignErrorConvention . h " <nl> # include " swift / AST / GenericEnvironment . h " <nl> + # include " swift / AST / GenericSignature . h " <nl> # include " swift / AST / Initializer . h " <nl> # include " swift / AST / Module . h " <nl> # include " swift / AST / ParameterList . h " <nl> std : : pair < bool , Expr * > dispatchVisitPreExprHelper ( <nl> return { false , node } ; <nl> } <nl> <nl> - / / / Describes a generic environment that might be lazily deserialized . <nl> - / / / <nl> - / / / This class abstracts over a declaration context that may have a generic <nl> - / / / environment , ensuring that we don ' t deserialize the environment . <nl> - struct LazyGenericEnvironment { <nl> - llvm : : PointerUnion < DeclContext * , GenericEnvironment * > storage ; <nl> - <nl> - explicit operator bool ( ) const { <nl> - if ( storage . dyn_cast < GenericEnvironment * > ( ) ) <nl> - return true ; <nl> - <nl> - if ( auto dc = storage . dyn_cast < DeclContext * > ( ) ) <nl> - return dc - > getGenericSignatureOfContext ( ) ; <nl> - <nl> - return false ; <nl> - } <nl> - <nl> - bool isLazy ( ) const { <nl> - if ( auto dc = storage . dyn_cast < DeclContext * > ( ) ) <nl> - return dc - > contextHasLazyGenericEnvironment ( ) ; <nl> - <nl> - return false ; <nl> - } <nl> - <nl> - bool containsPrimaryArchetype ( PrimaryArchetypeType * archetype ) const { <nl> - / / Assume true so we don ' t deserialize . <nl> - if ( isLazy ( ) ) return true ; <nl> - <nl> - if ( auto genericEnv = storage . dyn_cast < GenericEnvironment * > ( ) ) <nl> - return archetype - > getGenericEnvironment ( ) = = genericEnv ; <nl> - <nl> - if ( auto dc = storage . dyn_cast < DeclContext * > ( ) ) { <nl> - if ( auto genericEnv = dc - > getGenericEnvironmentOfContext ( ) ) <nl> - return archetype - > getGenericEnvironment ( ) = = genericEnv ; <nl> - } <nl> - <nl> - return false ; <nl> - } <nl> - } ; <nl> - <nl> namespace { <nl> / / / Retrieve the " overridden " declaration of this declaration , but only if <nl> / / it ' s already been computed . <nl> class Verifier : public ASTWalker { <nl> using ScopeLike = llvm : : PointerUnion < DeclContext * , BraceStmt * > ; <nl> SmallVector < ScopeLike , 4 > Scopes ; <nl> <nl> - / / / The stack of generic environments . <nl> - SmallVector < LazyGenericEnvironment , 2 > GenericEnv ; <nl> + / / / The stack of context generic signatures . <nl> + SmallVector < GenericSignature * , 2 > GenericSig ; <nl> <nl> / / / The stack of optional evaluations active at this point . <nl> SmallVector < OptionalEvaluationExpr * , 4 > OptionalEvaluations ; <nl> class Verifier : public ASTWalker { <nl> Ctx ( M . is < ModuleDecl * > ( ) ? M . get < ModuleDecl * > ( ) - > getASTContext ( ) <nl> : M . get < SourceFile * > ( ) - > getASTContext ( ) ) , <nl> Out ( llvm : : errs ( ) ) , HadError ( Ctx . hadError ( ) ) { <nl> - Scopes . push_back ( DC ) ; <nl> - GenericEnv . push_back ( { DC } ) ; <nl> + pushScope ( DC ) ; <nl> } <nl> <nl> public : <nl> class Verifier : public ASTWalker { <nl> } <nl> <nl> / / Otherwise , the archetype needs to be from this scope . <nl> - if ( GenericEnv . empty ( ) | | ! GenericEnv . back ( ) ) { <nl> + if ( GenericSig . empty ( ) | | ! GenericSig . back ( ) ) { <nl> Out < < " AST verification error : archetype outside of generic " <nl> " context : " < < root - > getString ( ) < < " \ n " ; <nl> return true ; <nl> } <nl> <nl> - / / Get the primary archetype . <nl> + / / Get the archetype ' s generic signature . <nl> auto rootPrimary = cast < PrimaryArchetypeType > ( root ) ; <nl> + auto * archetypeEnv = rootPrimary - > getGenericEnvironment ( ) ; <nl> + auto * archetypeSig = archetypeEnv - > getGenericSignature ( ) ; <nl> <nl> - if ( ! GenericEnv . back ( ) . containsPrimaryArchetype ( rootPrimary ) ) { <nl> - Out < < " AST verification error : archetype " <nl> - < < root - > getString ( ) < < " not allowed in this context \ n " ; <nl> + if ( GenericSig . back ( ) ! = archetypeSig ) { <nl> + Out < < " Archetype " < < root - > getString ( ) < < " not allowed " <nl> + < < " in this context \ n " ; <nl> + Out < < " Archetype generic signature : " <nl> + < < archetypeSig - > getAsString ( ) < < " \ n " ; <nl> + Out < < " Context generic signature : " <nl> + < < GenericSig . back ( ) - > getAsString ( ) < < " \ n " ; <nl> <nl> - if ( auto env = rootPrimary - > getGenericEnvironment ( ) ) { <nl> - if ( auto owningDC = env - > getOwningDeclContext ( ) ) { <nl> - llvm : : errs ( ) < < " archetype came from : \ n " ; <nl> - owningDC - > dumpContext ( ) ; <nl> - llvm : : errs ( ) < < " \ n " ; <nl> - } <nl> - } <nl> + return true ; <nl> + } <nl> + <nl> + / / Mapping the archetype out and back in should produce the <nl> + / / same archetype . <nl> + auto interfaceType = archetype - > getInterfaceType ( ) ; <nl> + auto contextType = archetypeEnv - > mapTypeIntoContext ( interfaceType ) ; <nl> + <nl> + if ( contextType . getPointer ( ) ! = archetype ) { <nl> + Out < < " Archetype " < < archetype - > getString ( ) < < " does not appear " <nl> + < < " inside its own generic environment \ n " ; <nl> + Out < < " Interface type : " < < interfaceType . getString ( ) < < " \ n " ; <nl> + Out < < " Contextual type : " < < contextType . getString ( ) < < " \ n " ; <nl> <nl> return true ; <nl> } <nl> class Verifier : public ASTWalker { <nl> <nl> void pushScope ( DeclContext * scope ) { <nl> Scopes . push_back ( scope ) ; <nl> - GenericEnv . push_back ( { scope } ) ; <nl> + GenericSig . push_back ( scope - > getGenericSignatureOfContext ( ) ) ; <nl> } <nl> void pushScope ( BraceStmt * scope ) { <nl> Scopes . push_back ( scope ) ; <nl> } <nl> void popScope ( DeclContext * scope ) { <nl> assert ( Scopes . back ( ) . get < DeclContext * > ( ) = = scope ) ; <nl> - assert ( GenericEnv . back ( ) . storage . get < DeclContext * > ( ) = = scope ) ; <nl> + assert ( GenericSig . back ( ) = = scope - > getGenericSignatureOfContext ( ) ) ; <nl> Scopes . pop_back ( ) ; <nl> - GenericEnv . pop_back ( ) ; <nl> + GenericSig . pop_back ( ) ; <nl> } <nl> void popScope ( BraceStmt * scope ) { <nl> assert ( Scopes . back ( ) . get < BraceStmt * > ( ) = = scope ) ; <nl> class Verifier : public ASTWalker { <nl> const auto & witness = normal - > getWitness ( req ) ; <nl> <nl> if ( auto * genericEnv = witness . getSyntheticEnvironment ( ) ) <nl> - GenericEnv . push_back ( { genericEnv } ) ; <nl> + GenericSig . push_back ( genericEnv - > getGenericSignature ( ) ) ; <nl> <nl> verifyChecked ( witness . getRequirementToSyntheticSubs ( ) ) ; <nl> verifyChecked ( witness . getSubstitutions ( ) ) ; <nl> <nl> if ( auto * genericEnv = witness . getSyntheticEnvironment ( ) ) { <nl> - assert ( GenericEnv . back ( ) . storage . dyn_cast < GenericEnvironment * > ( ) <nl> - = = genericEnv ) ; <nl> - GenericEnv . pop_back ( ) ; <nl> + assert ( GenericSig . back ( ) = = genericEnv - > getGenericSignature ( ) ) ; <nl> + GenericSig . pop_back ( ) ; <nl> } <nl> <nl> continue ; <nl> class Verifier : public ASTWalker { <nl> } <nl> } <nl> <nl> - void verifyGenericEnvironment ( Decl * D , <nl> - GenericSignature * sig , <nl> - GenericEnvironment * env ) { <nl> - if ( ! sig & & ! env ) <nl> - return ; <nl> - <nl> - if ( sig & & env ) { <nl> - for ( auto * paramTy : sig - > getGenericParams ( ) ) { <nl> - ( void ) env - > mapTypeIntoContext ( paramTy ) ; <nl> - } <nl> - <nl> - return ; <nl> - } <nl> - <nl> - Out < < " Decl must have both signature and environment , or neither \ n " ; <nl> - D - > dump ( Out ) ; <nl> - abort ( ) ; <nl> - } <nl> - <nl> void verifyChecked ( GenericTypeDecl * generic ) { <nl> - if ( ! generic - > hasLazyGenericEnvironment ( ) ) { <nl> - verifyGenericEnvironment ( generic , <nl> - generic - > getGenericSignature ( ) , <nl> - generic - > getGenericEnvironment ( ) ) ; <nl> - } <nl> - <nl> verifyCheckedBase ( generic ) ; <nl> } <nl> <nl> class Verifier : public ASTWalker { <nl> abort ( ) ; <nl> } <nl> <nl> - if ( ! AFD - > hasLazyGenericEnvironment ( ) ) { <nl> - verifyGenericEnvironment ( AFD , <nl> - AFD - > getGenericSignature ( ) , <nl> - AFD - > getGenericEnvironment ( ) ) ; <nl> - } <nl> - <nl> / / If there is an interface type , it shouldn ' t have any unresolved <nl> / / dependent member types . <nl> / / FIXME : This is a general property of the type system . <nl> mmm a / lib / AST / Builtins . cpp <nl> ppp b / lib / AST / Builtins . cpp <nl> getBuiltinGenericFunction ( Identifier Id , <nl> ArrayRef < AnyFunctionType : : Param > ArgParamTypes , <nl> Type ResType , <nl> GenericParamList * GenericParams , <nl> - GenericEnvironment * Env ) { <nl> + GenericSignature * Sig ) { <nl> assert ( GenericParams & & " Missing generic parameters " ) ; <nl> auto & Context = ResType - > getASTContext ( ) ; <nl> <nl> getBuiltinGenericFunction ( Identifier Id , <nl> paramList , <nl> TypeLoc : : withoutLoc ( ResType ) , DC ) ; <nl> <nl> - func - > setGenericEnvironment ( Env ) ; <nl> + func - > setGenericSignature ( Sig ) ; <nl> func - > computeType ( ) ; <nl> func - > setValidationToChecked ( ) ; <nl> func - > setImplicit ( ) ; <nl> namespace { <nl> private : <nl> GenericParamList * TheGenericParamList ; <nl> SmallVector < GenericTypeParamDecl * , 2 > GenericTypeParams ; <nl> - GenericEnvironment * GenericEnv = nullptr ; <nl> + GenericSignature * GenericSig = nullptr ; <nl> SmallVector < AnyFunctionType : : Param , 4 > InterfaceParams ; <nl> Type InterfaceResult ; <nl> <nl> namespace { <nl> gp - > getDeclaredInterfaceType ( ) - > castTo < GenericTypeParamType > ( ) ) ; <nl> } <nl> <nl> - auto GenericSig = evaluateOrDefault ( <nl> + GenericSig = evaluateOrDefault ( <nl> ctx . evaluator , <nl> AbstractGenericSignatureRequest { <nl> nullptr , std : : move ( genericParamTypes ) , { } } , <nl> nullptr ) ; <nl> - GenericEnv = GenericSig - > createGenericEnvironment ( ) ; <nl> } <nl> <nl> template < class G > <nl> namespace { <nl> return getBuiltinGenericFunction ( name , InterfaceParams , <nl> InterfaceResult , <nl> TheGenericParamList , <nl> - GenericEnv ) ; <nl> + GenericSig ) ; <nl> } <nl> <nl> / / Don ' t use these generator classes directly ; call the make { . . . } <nl> mmm a / lib / AST / Decl . cpp <nl> ppp b / lib / AST / Decl . cpp <nl> using namespace swift ; <nl> <nl> # define DEBUG_TYPE " Serialization " <nl> <nl> - STATISTIC ( NumLazyGenericEnvironments , <nl> - " # of lazily - deserialized generic environments known " ) ; <nl> - STATISTIC ( NumLazyGenericEnvironmentsLoaded , <nl> - " # of lazily - deserialized generic environments loaded " ) ; <nl> STATISTIC ( NumLazyRequirementSignatures , <nl> " # of lazily - deserialized requirement signatures known " ) ; <nl> <nl> void GenericContext : : setGenericParams ( GenericParamList * params ) { <nl> } <nl> <nl> GenericSignature * GenericContext : : getGenericSignature ( ) const { <nl> - if ( auto genericEnv = GenericSigOrEnv . dyn_cast < GenericEnvironment * > ( ) ) <nl> - return genericEnv - > getGenericSignature ( ) ; <nl> - <nl> - if ( auto genericSig = GenericSigOrEnv . dyn_cast < GenericSignature * > ( ) ) <nl> - return genericSig ; <nl> + if ( GenericSig ) <nl> + return GenericSig ; <nl> <nl> / / The signature of a Protocol is trivial ( Self : TheProtocol ) so let ' s compute <nl> / / it . <nl> GenericSignature * GenericContext : : getGenericSignature ( ) const { <nl> auto self = PD - > getSelfInterfaceType ( ) - > castTo < GenericTypeParamType > ( ) ; <nl> auto req = <nl> Requirement ( RequirementKind : : Conformance , self , PD - > getDeclaredType ( ) ) ; <nl> - auto * genericSig = GenericSignature : : get ( { self } , { req } ) ; <nl> - <nl> - / / Save it for next time . <nl> - const_cast < GenericContext * > ( this ) - > GenericSigOrEnv = genericSig ; <nl> - return genericSig ; <nl> + const_cast < GenericContext * > ( this ) - > GenericSig <nl> + = GenericSignature : : get ( { self } , { req } ) ; <nl> + return GenericSig ; <nl> } <nl> <nl> return nullptr ; <nl> } <nl> <nl> GenericEnvironment * GenericContext : : getGenericEnvironment ( ) const { <nl> - / / Fast case : we already have a generic environment . <nl> - if ( auto genericEnv = GenericSigOrEnv . dyn_cast < GenericEnvironment * > ( ) ) <nl> - return genericEnv ; <nl> - <nl> - / / If we only have a generic signature , build the generic environment . <nl> - if ( GenericSigOrEnv . dyn_cast < GenericSignature * > ( ) | | isa < ProtocolDecl > ( this ) ) <nl> - return getLazyGenericEnvironmentSlow ( ) ; <nl> + if ( auto * genericSig = getGenericSignature ( ) ) <nl> + return genericSig - > getGenericEnvironment ( ) ; <nl> <nl> return nullptr ; <nl> } <nl> <nl> - bool GenericContext : : hasLazyGenericEnvironment ( ) const { <nl> - return GenericSigOrEnv . dyn_cast < GenericSignature * > ( ) ! = nullptr ; <nl> - } <nl> - <nl> - void GenericContext : : setGenericEnvironment ( GenericEnvironment * genericEnv ) { <nl> - assert ( ( GenericSigOrEnv . isNull ( ) | | <nl> - getGenericSignature ( ) - > getCanonicalSignature ( ) = = <nl> - genericEnv - > getGenericSignature ( ) - > getCanonicalSignature ( ) ) & & <nl> - " set a generic environment with a different generic signature " ) ; <nl> - this - > GenericSigOrEnv = genericEnv ; <nl> - if ( genericEnv ) <nl> - genericEnv - > setOwningDeclContext ( this ) ; <nl> - } <nl> - <nl> - GenericEnvironment * <nl> - GenericContext : : getLazyGenericEnvironmentSlow ( ) const { <nl> - assert ( GenericSigOrEnv . is < GenericSignature * > ( ) & & <nl> - " not a lazily computed generic environment " ) ; <nl> - <nl> - if ( auto PD = dyn_cast < ProtocolDecl > ( this ) ) { <nl> - / / The signature of a Protocol is trivial ( Self : TheProtocol ) so let ' s <nl> - / / compute it directly . <nl> - auto * genericEnv = getGenericSignature ( ) - > createGenericEnvironment ( ) ; <nl> - const_cast < GenericContext * > ( this ) - > setGenericEnvironment ( genericEnv ) ; <nl> - return genericEnv ; <nl> - } <nl> - <nl> - auto contextData = getASTContext ( ) . getOrCreateLazyGenericContextData ( <nl> - this , nullptr ) ; <nl> - auto * genericEnv = contextData - > loader - > loadGenericEnvironment ( <nl> - this , contextData - > genericEnvData ) ; <nl> - <nl> - const_cast < GenericContext * > ( this ) - > setGenericEnvironment ( genericEnv ) ; <nl> - + + NumLazyGenericEnvironmentsLoaded ; <nl> - / / FIXME : ( transitional ) increment the redundant " always - on " counter . <nl> - if ( getASTContext ( ) . Stats ) <nl> - getASTContext ( ) . Stats - > getFrontendCounters ( ) . NumLazyGenericEnvironmentsLoaded + + ; <nl> - return genericEnv ; <nl> - } <nl> - <nl> - void GenericContext : : setLazyGenericEnvironment ( LazyMemberLoader * lazyLoader , <nl> - GenericSignature * genericSig , <nl> - uint64_t genericEnvData ) { <nl> - assert ( GenericSigOrEnv . isNull ( ) & & " already have a generic signature " ) ; <nl> - GenericSigOrEnv = genericSig ; <nl> - <nl> - auto contextData = <nl> - getASTContext ( ) . getOrCreateLazyGenericContextData ( this , lazyLoader ) ; <nl> - contextData - > genericEnvData = genericEnvData ; <nl> - <nl> - + + NumLazyGenericEnvironments ; <nl> - / / FIXME : ( transitional ) increment the redundant " always - on " counter . <nl> - if ( getASTContext ( ) . Stats ) <nl> - getASTContext ( ) . Stats - > getFrontendCounters ( ) . NumLazyGenericEnvironments + + ; <nl> - <nl> + void GenericContext : : setGenericSignature ( GenericSignature * genericSig ) { <nl> + assert ( GenericSig = = nullptr & & " Generic signature cannot be changed " ) ; <nl> + this - > GenericSig = genericSig ; <nl> } <nl> <nl> SourceRange GenericContext : : getGenericTrailingWhereClauseSourceRange ( ) const { <nl> GetDestructorRequest : : evaluate ( Evaluator & evaluator , ClassDecl * CD ) const { <nl> DD - > copyFormalAccessFrom ( CD , / * sourceIsParentContext * / true ) ; <nl> <nl> / / Wire up generic environment of DD . <nl> - DD - > setGenericEnvironment ( CD - > getGenericEnvironmentOfContext ( ) ) ; <nl> + DD - > setGenericSignature ( CD - > getGenericSignatureOfContext ( ) ) ; <nl> <nl> / / Mark DD as ObjC , as all dtors are . <nl> DD - > setIsObjC ( ctx . LangOpts . EnableObjCInterop ) ; <nl> mmm a / lib / AST / DeclContext . cpp <nl> ppp b / lib / AST / DeclContext . cpp <nl> GenericEnvironment * DeclContext : : getGenericEnvironmentOfContext ( ) const { <nl> return nullptr ; <nl> } <nl> <nl> - bool DeclContext : : contextHasLazyGenericEnvironment ( ) const { <nl> - auto dc = this ; <nl> - do { <nl> - if ( auto decl = dc - > getAsDecl ( ) ) <nl> - if ( auto GC = decl - > getAsGenericContext ( ) ) <nl> - return GC - > hasLazyGenericEnvironment ( ) ; <nl> - } while ( ( dc = dc - > getParent ( ) ) ) ; <nl> - <nl> - return false ; <nl> - } <nl> - <nl> Type DeclContext : : mapTypeIntoContext ( Type type ) const { <nl> return GenericEnvironment : : mapTypeIntoContext ( <nl> getGenericEnvironmentOfContext ( ) , type ) ; <nl> mmm a / lib / AST / GenericEnvironment . cpp <nl> ppp b / lib / AST / GenericEnvironment . cpp <nl> GenericEnvironment : : GenericEnvironment ( GenericSignature * signature , <nl> Type ( ) ) ; <nl> } <nl> <nl> - void GenericEnvironment : : setOwningDeclContext ( DeclContext * newOwningDC ) { <nl> - if ( ! OwningDC ) { <nl> - OwningDC = newOwningDC ; <nl> - return ; <nl> - } <nl> - <nl> - if ( ! newOwningDC | | OwningDC = = newOwningDC ) <nl> - return ; <nl> - <nl> - / / Find the least common ancestor context to be the owner . <nl> - unsigned oldDepth = OwningDC - > getSyntacticDepth ( ) ; <nl> - unsigned newDepth = newOwningDC - > getSyntacticDepth ( ) ; <nl> - <nl> - while ( oldDepth > newDepth ) { <nl> - OwningDC = OwningDC - > getParent ( ) ; <nl> - - - oldDepth ; <nl> - } <nl> - <nl> - while ( newDepth > oldDepth ) { <nl> - newOwningDC = newOwningDC - > getParent ( ) ; <nl> - - - newDepth ; <nl> - } <nl> - <nl> - while ( OwningDC ! = newOwningDC ) { <nl> - OwningDC = OwningDC - > getParent ( ) ; <nl> - newOwningDC = newOwningDC - > getParent ( ) ; <nl> - } <nl> - } <nl> - <nl> void GenericEnvironment : : addMapping ( GenericParamKey key , <nl> Type contextType ) { <nl> / / Find the index into the parallel arrays of generic parameters and <nl> mmm a / lib / AST / GenericSignature . cpp <nl> ppp b / lib / AST / GenericSignature . cpp <nl> GenericSignature : : getCanonicalSignature ( ) const { <nl> CanonicalSignatureOrASTContext . get < GenericSignature * > ( ) ) ; <nl> } <nl> <nl> - GenericEnvironment * GenericSignature : : createGenericEnvironment ( ) { <nl> - auto * builder = getGenericSignatureBuilder ( ) ; <nl> - return GenericEnvironment : : getIncomplete ( this , builder ) ; <nl> + GenericEnvironment * GenericSignature : : getGenericEnvironment ( ) { <nl> + if ( GenericEnv = = nullptr ) { <nl> + auto * builder = getGenericSignatureBuilder ( ) ; <nl> + GenericEnv = GenericEnvironment : : getIncomplete ( this , builder ) ; <nl> + } <nl> + <nl> + return GenericEnv ; <nl> } <nl> <nl> <nl> CanType GenericSignature : : getCanonicalTypeInContext ( Type type ) { <nl> return getCanonicalTypeInContext ( type , builder ) ; <nl> } <nl> <nl> - GenericEnvironment * CanGenericSignature : : getGenericEnvironment ( ) const { <nl> - / / generic signature builders are stored on the ASTContext . <nl> - auto & ctx = getGenericParams ( ) [ 0 ] - > getASTContext ( ) ; <nl> - return ctx . getOrCreateCanonicalGenericEnvironment ( <nl> - ctx . getOrCreateGenericSignatureBuilder ( * this ) , <nl> - * this ) ; <nl> - } <nl> - <nl> ArrayRef < CanTypeWrapper < GenericTypeParamType > > <nl> CanGenericSignature : : getGenericParams ( ) const { <nl> auto params = Signature - > getGenericParams ( ) . getOriginalArray ( ) ; <nl> mmm a / lib / AST / RequirementEnvironment . cpp <nl> ppp b / lib / AST / RequirementEnvironment . cpp <nl> RequirementEnvironment : : RequirementEnvironment ( <nl> if ( syntheticSignature ) { <nl> syntheticSignature = syntheticSignature - > getCanonicalSignature ( ) ; <nl> syntheticEnvironment = <nl> - syntheticSignature - > createGenericEnvironment ( ) ; <nl> + syntheticSignature - > getGenericEnvironment ( ) ; <nl> } <nl> <nl> return ; <nl> RequirementEnvironment : : RequirementEnvironment ( <nl> AbstractGenericSignatureRequest { <nl> nullptr , std : : move ( genericParamTypes ) , std : : move ( requirements ) } , <nl> nullptr ) ; <nl> - syntheticEnvironment = syntheticSignature - > createGenericEnvironment ( ) ; <nl> + syntheticEnvironment = syntheticSignature - > getGenericEnvironment ( ) ; <nl> } <nl> mmm a / lib / ClangImporter / ImportDecl . cpp <nl> ppp b / lib / ClangImporter / ImportDecl . cpp <nl> buildSubscriptGetterDecl ( ClangImporter : : Implementation & Impl , <nl> TypeLoc : : withoutLoc ( elementTy ) , dc , <nl> getter - > getClangNode ( ) ) ; <nl> <nl> - thunk - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + thunk - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> thunk - > computeType ( ) ; <nl> thunk - > setValidationToChecked ( ) ; <nl> <nl> buildSubscriptSetterDecl ( ClangImporter : : Implementation & Impl , <nl> valueIndicesPL , <nl> TypeLoc : : withoutLoc ( TupleType : : getEmpty ( C ) ) , dc , <nl> setter - > getClangNode ( ) ) ; <nl> - thunk - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + thunk - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> thunk - > computeType ( ) ; <nl> thunk - > setValidationToChecked ( ) ; <nl> <nl> namespace { <nl> nameLoc , bodyParams , resultTy , <nl> / * throws * / false , dc , decl ) ; <nl> <nl> - result - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + result - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> <nl> if ( ! dc - > isModuleScopeContext ( ) ) { <nl> if ( selfIsInOut ) <nl> namespace { <nl> / / Record the return type . <nl> result - > getBodyResultTypeLoc ( ) . setType ( resultTy ) ; <nl> <nl> - result - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + result - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> <nl> / / Optional methods in protocols . <nl> if ( decl - > getImplementationControl ( ) = = clang : : ObjCMethodDecl : : Optional & & <nl> namespace { <nl> / / Determine the type and generic args of the extension . <nl> if ( objcClass - > getGenericParams ( ) ) { <nl> result - > createGenericParamsIfMissing ( objcClass ) ; <nl> - <nl> - auto * env = objcClass - > getGenericEnvironment ( ) ; <nl> - result - > setGenericEnvironment ( env ) ; <nl> + result - > setGenericSignature ( objcClass - > getGenericSignature ( ) ) ; <nl> } <nl> <nl> / / Create the extension declaration and record it . <nl> namespace { <nl> if ( genericParams ) { <nl> result - > setGenericParams ( genericParams ) ; <nl> <nl> - auto * env = Impl . buildGenericEnvironment ( genericParams , dc ) ; <nl> - result - > setGenericEnvironment ( env ) ; <nl> + auto * sig = Impl . buildGenericSignature ( genericParams , dc ) ; <nl> + result - > setGenericSignature ( sig ) ; <nl> } <nl> } else { <nl> return nullptr ; <nl> namespace { <nl> / * genericparams = * / nullptr , dc ) ; <nl> <nl> if ( auto * GTD = dyn_cast < GenericTypeDecl > ( typeDecl ) ) { <nl> - typealias - > setGenericEnvironment ( GTD - > getGenericEnvironment ( ) ) ; <nl> + typealias - > setGenericSignature ( GTD - > getGenericSignature ( ) ) ; <nl> if ( GTD - > isGeneric ( ) ) <nl> typealias - > setGenericParams ( GTD - > getGenericParams ( ) - > clone ( typealias ) ) ; <nl> } <nl> Decl * SwiftDeclConverter : : importCompatibilityTypeAlias ( <nl> <nl> auto * GTD = dyn_cast < GenericTypeDecl > ( typeDecl ) ; <nl> if ( GTD & & ! isa < ProtocolDecl > ( GTD ) ) { <nl> - alias - > setGenericEnvironment ( GTD - > getGenericEnvironment ( ) ) ; <nl> + alias - > setGenericSignature ( GTD - > getGenericSignature ( ) ) ; <nl> if ( GTD - > isGeneric ( ) ) <nl> alias - > setGenericParams ( GTD - > getGenericParams ( ) - > clone ( alias ) ) ; <nl> } <nl> ConstructorDecl * SwiftDeclConverter : : importConstructor ( <nl> addObjCAttribute ( result , selector ) ; <nl> <nl> / / Calculate the function type of the result . <nl> - result - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + result - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> result - > computeType ( ) ; <nl> <nl> Impl . recordImplicitUnwrapForDecl ( result , <nl> SwiftDeclConverter : : importSubscript ( Decl * decl , <nl> if ( setterObjCMethod ) <nl> Impl . importAttributes ( setterObjCMethod , setterThunk ) ; <nl> <nl> - subscript - > setGenericEnvironment ( dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + subscript - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> <nl> subscript - > setIsSetterMutating ( false ) ; <nl> makeComputed ( subscript , getterThunk , setterThunk ) ; <nl> GenericSignature * ClangImporter : : Implementation : : buildGenericSignature ( <nl> nullptr ) ; <nl> } <nl> <nl> - / / Calculate the generic environment from an imported generic param list . <nl> - GenericEnvironment * ClangImporter : : Implementation : : buildGenericEnvironment ( <nl> - GenericParamList * genericParams , DeclContext * dc ) { <nl> - return buildGenericSignature ( genericParams , dc ) - > createGenericEnvironment ( ) ; <nl> - } <nl> - <nl> DeclContext * <nl> ClangImporter : : Implementation : : importDeclContextOf ( <nl> const clang : : Decl * decl , <nl> ClangImporter : : Implementation : : importDeclContextOf ( <nl> <nl> if ( auto protoDecl = ext - > getExtendedProtocolDecl ( ) ) { <nl> ext - > createGenericParamsIfMissing ( protoDecl ) ; <nl> - ext - > setGenericEnvironment ( protoDecl - > getGenericEnvironment ( ) ) ; <nl> + ext - > setGenericSignature ( protoDecl - > getGenericSignature ( ) ) ; <nl> } <nl> <nl> / / Add the extension to the nominal type . <nl> mmm a / lib / ClangImporter / ImporterImpl . h <nl> ppp b / lib / ClangImporter / ImporterImpl . h <nl> class LLVM_LIBRARY_VISIBILITY ClangImporter : : Implementation <nl> GenericSignature * buildGenericSignature ( GenericParamList * genericParams , <nl> DeclContext * dc ) ; <nl> <nl> - / / / Utility function for building simple generic environments . <nl> - GenericEnvironment * buildGenericEnvironment ( GenericParamList * genericParams , <nl> - DeclContext * dc ) ; <nl> - <nl> / / / Import the given Clang declaration context into Swift . <nl> / / / <nl> / / / Usually one will use \ c importDeclContextOf instead . <nl> class LLVM_LIBRARY_VISIBILITY ClangImporter : : Implementation <nl> uint64_t contextData ) override { <nl> llvm_unreachable ( " unimplemented for ClangImporter " ) ; <nl> } <nl> - <nl> - / / / Returns the generic environment . <nl> - virtual GenericEnvironment * loadGenericEnvironment ( const DeclContext * decl , <nl> - uint64_t contextData ) override { <nl> - llvm_unreachable ( " unimplemented for ClangImporter " ) ; <nl> - } <nl> <nl> void loadRequirementSignature ( const ProtocolDecl * decl , uint64_t contextData , <nl> SmallVectorImpl < Requirement > & reqs ) override { <nl> mmm a / lib / IRGen / GenKeyPath . cpp <nl> ppp b / lib / IRGen / GenKeyPath . cpp <nl> IRGenModule : : getAddrOfKeyPathPattern ( KeyPathPattern * pattern , <nl> <nl> GenericEnvironment * genericEnv = nullptr ; <nl> if ( auto sig = pattern - > getGenericSignature ( ) ) { <nl> - genericEnv = sig - > createGenericEnvironment ( ) ; <nl> + genericEnv = sig - > getGenericEnvironment ( ) ; <nl> enumerateGenericSignatureRequirements ( pattern - > getGenericSignature ( ) , <nl> [ & ] ( GenericRequirement reqt ) { requirements . push_back ( reqt ) ; } ) ; <nl> } <nl> mmm a / lib / IRGen / GenReflection . cpp <nl> ppp b / lib / IRGen / GenReflection . cpp <nl> getTypeRefByFunction ( IRGenModule & IGM , <nl> if ( sig ) { <nl> enumerateGenericSignatureRequirements ( sig , <nl> [ & ] ( GenericRequirement reqt ) { requirements . push_back ( reqt ) ; } ) ; <nl> - genericEnv = sig - > createGenericEnvironment ( ) ; <nl> + genericEnv = sig - > getGenericEnvironment ( ) ; <nl> } <nl> <nl> { <nl> IRGenModule : : emitWitnessTableRefString ( CanType type , <nl> genericSig = origGenericSig - > getCanonicalSignature ( ) ; <nl> enumerateGenericSignatureRequirements ( genericSig , <nl> [ & ] ( GenericRequirement reqt ) { requirements . push_back ( reqt ) ; } ) ; <nl> - genericEnv = genericSig - > createGenericEnvironment ( ) ; <nl> + genericEnv = genericSig - > getGenericEnvironment ( ) ; <nl> } <nl> <nl> IRGenMangler mangler ; <nl> mmm a / lib / IRGen / GenType . cpp <nl> ppp b / lib / IRGen / GenType . cpp <nl> void TypeConverter : : popGenericContext ( CanGenericSignature signature ) { <nl> <nl> GenericEnvironment * TypeConverter : : getGenericEnvironment ( ) { <nl> auto genericSig = IGM . getSILTypes ( ) . getCurGenericContext ( ) ; <nl> - return genericSig - > getCanonicalSignature ( ) . getGenericEnvironment ( ) ; <nl> + return genericSig - > getCanonicalSignature ( ) - > getGenericEnvironment ( ) ; <nl> } <nl> <nl> GenericEnvironment * IRGenModule : : getGenericEnvironment ( ) { <nl> ArchetypeType * TypeConverter : : getExemplarArchetype ( ArchetypeType * t ) { <nl> / / Dig out the canonical generic environment . <nl> auto genericSig = genericEnv - > getGenericSignature ( ) ; <nl> auto canGenericSig = genericSig - > getCanonicalSignature ( ) ; <nl> - auto canGenericEnv = canGenericSig . getGenericEnvironment ( ) ; <nl> + auto canGenericEnv = canGenericSig - > getGenericEnvironment ( ) ; <nl> if ( canGenericEnv = = genericEnv ) return t ; <nl> <nl> / / Map the archetype out of its own generic environment and into the <nl> bool TypeConverter : : isExemplarArchetype ( ArchetypeType * arch ) const { <nl> / / Dig out the canonical generic environment . <nl> auto genericSig = genericEnv - > getGenericSignature ( ) ; <nl> auto canGenericSig = genericSig - > getCanonicalSignature ( ) ; <nl> - auto canGenericEnv = canGenericSig . getGenericEnvironment ( ) ; <nl> + auto canGenericEnv = canGenericSig - > getGenericEnvironment ( ) ; <nl> <nl> / / If this archetype is in the canonical generic environment , it ' s an <nl> / / exemplar archetype . <nl> mmm a / lib / IRGen / LoadableByAddress . cpp <nl> ppp b / lib / IRGen / LoadableByAddress . cpp <nl> using namespace swift ; <nl> using namespace swift : : irgen ; <nl> <nl> static GenericEnvironment * getGenericEnvironment ( CanSILFunctionType loweredTy ) { <nl> - return loweredTy - > getGenericSignature ( ) . getGenericEnvironment ( ) ; <nl> + return loweredTy - > getGenericSignature ( ) - > getGenericEnvironment ( ) ; <nl> } <nl> <nl> class LargeSILTypeMapper { <nl> mmm a / lib / SIL / TypeLowering . cpp <nl> ppp b / lib / SIL / TypeLowering . cpp <nl> namespace { <nl> / / signature plumbed through . <nl> if ( Sig & & type - > hasTypeParameter ( ) ) { <nl> type = Sig - > getCanonicalSignature ( ) <nl> - . getGenericEnvironment ( ) <nl> + - > getGenericEnvironment ( ) <nl> - > mapTypeIntoContext ( type ) <nl> - > getCanonicalType ( ) ; <nl> } <nl> TypeConverter : : getInterfaceBoxTypeForCapture ( ValueDecl * captured , <nl> auto loweredContextType = loweredInterfaceType ; <nl> auto contextBoxTy = boxTy ; <nl> if ( signature ) { <nl> - auto env = signature . getGenericEnvironment ( ) ; <nl> + auto env = signature - > getGenericEnvironment ( ) ; <nl> loweredContextType = env - > mapTypeIntoContext ( loweredContextType ) <nl> - > getCanonicalType ( ) ; <nl> contextBoxTy = cast < SILBoxType > ( <nl> mmm a / lib / SILGen / SILGen . cpp <nl> ppp b / lib / SILGen / SILGen . cpp <nl> SILGenModule : : getKeyPathProjectionCoroutine ( bool isReadAccess , <nl> / * error result * / { } , <nl> getASTContext ( ) ) ; <nl> <nl> - auto env = sig - > createGenericEnvironment ( ) ; <nl> + auto env = sig - > getGenericEnvironment ( ) ; <nl> <nl> SILGenFunctionBuilder builder ( * this ) ; <nl> fn = builder . createFunction ( SILLinkage : : PublicExternal , <nl> mmm a / lib / SILGen / SILGenPoly . cpp <nl> ppp b / lib / SILGen / SILGenPoly . cpp <nl> buildThunkSignature ( SILGenFunction & SGF , <nl> AbstractGenericSignatureRequest { <nl> baseGenericSig , { newGenericParam } , { newRequirement } } , <nl> nullptr ) ; <nl> - genericEnv = genericSig - > createGenericEnvironment ( ) ; <nl> + genericEnv = genericSig - > getGenericEnvironment ( ) ; <nl> <nl> newArchetype = genericEnv - > mapTypeIntoContext ( newGenericParam ) <nl> - > castTo < ArchetypeType > ( ) ; <nl> mmm a / lib / SILOptimizer / FunctionSignatureTransforms / ExistentialTransform . cpp <nl> ppp b / lib / SILOptimizer / FunctionSignatureTransforms / ExistentialTransform . cpp <nl> ExistentialTransform : : createExistentialSpecializedFunctionType ( ) { <nl> OrigGenericSig , std : : move ( GenericParams ) , std : : move ( Requirements ) } , <nl> nullptr ) ; <nl> <nl> - NewGenericEnv = NewGenericSig - > createGenericEnvironment ( ) ; <nl> + NewGenericEnv = NewGenericSig - > getGenericEnvironment ( ) ; <nl> <nl> / / / Create a lambda for GenericParams . <nl> auto getCanonicalType = [ & ] ( Type t ) - > CanType { <nl> void ExistentialTransform : : createExistentialSpecializedFunction ( ) { <nl> auto NewFTy = createExistentialSpecializedFunctionType ( ) ; <nl> <nl> auto NewFGenericSig = NewFTy - > getGenericSignature ( ) ; <nl> - auto NewFGenericEnv = NewFGenericSig - > createGenericEnvironment ( ) ; <nl> + auto NewFGenericEnv = NewFGenericSig - > getGenericEnvironment ( ) ; <nl> <nl> / / / Step 1 : Create the new protocol constrained generic function . <nl> NewF = FunctionBuilder . createFunction ( <nl> mmm a / lib / SILOptimizer / Utils / Generics . cpp <nl> ppp b / lib / SILOptimizer / Utils / Generics . cpp <nl> getGenericEnvironmentAndSignatureWithRequirements ( <nl> OrigGenSig , { } , std : : move ( RequirementsCopy ) } , <nl> nullptr ) ; <nl> <nl> - auto NewGenEnv = NewGenSig - > createGenericEnvironment ( ) ; <nl> + auto NewGenEnv = NewGenSig - > getGenericEnvironment ( ) ; <nl> return { NewGenEnv , NewGenSig } ; <nl> } <nl> <nl> class FunctionSignaturePartialSpecializer { <nl> M ( M ) , SM ( M . getSwiftModule ( ) ) , Ctx ( M . getASTContext ( ) ) { <nl> <nl> / / Create the new generic signature using provided requirements . <nl> - SpecializedGenericEnv = SpecializedGenericSig - > createGenericEnvironment ( ) ; <nl> + SpecializedGenericEnv = SpecializedGenericSig - > getGenericEnvironment ( ) ; <nl> <nl> / / Compute SubstitutionMaps required for re - mapping . <nl> <nl> FunctionSignaturePartialSpecializer : : <nl> Ctx . evaluator , <nl> AbstractGenericSignatureRequest { nullptr , AllGenericParams , AllRequirements } , <nl> nullptr ) ; <nl> - auto GenEnv = GenSig ? GenSig - > createGenericEnvironment ( ) : nullptr ; <nl> + auto GenEnv = GenSig ? GenSig - > getGenericEnvironment ( ) : nullptr ; <nl> return { GenEnv , GenSig } ; <nl> } <nl> <nl> mmm a / lib / Sema / CSDiag . cpp <nl> ppp b / lib / Sema / CSDiag . cpp <nl> bool FailureDiagnosis : : diagnoseArgumentGenericRequirements ( <nl> } <nl> } ; <nl> <nl> - auto * dc = env - > getOwningDeclContext ( ) ; <nl> auto substitutionFn = QueryTypeSubstitutionMap { substitutions } ; <nl> RequirementsListener genericReqListener ( CS , AFD , substitutionFn , <nl> callExpr , fnExpr , argExpr ) ; <nl> <nl> auto result = TC . checkGenericArguments ( <nl> - dc , callExpr - > getLoc ( ) , fnExpr - > getLoc ( ) , AFD - > getInterfaceType ( ) , <nl> + AFD , callExpr - > getLoc ( ) , fnExpr - > getLoc ( ) , AFD - > getInterfaceType ( ) , <nl> env - > getGenericSignature ( ) - > getGenericParams ( ) , <nl> env - > getGenericSignature ( ) - > getRequirements ( ) , <nl> substitutionFn , <nl> - LookUpConformanceInModule { dc - > getParentModule ( ) } , <nl> + LookUpConformanceInModule { AFD - > getParentModule ( ) } , <nl> ConformanceCheckFlags : : SuppressDependencyTracking , & genericReqListener ) ; <nl> <nl> / / Note : If result is RequirementCheckResult : : SubstitutionFailure , we did <nl> mmm a / lib / Sema / CodeSynthesis . cpp <nl> ppp b / lib / Sema / CodeSynthesis . cpp <nl> synthesizeStubBody ( AbstractFunctionDecl * fn , void * ) { <nl> / * isTypeChecked = * / true } ; <nl> } <nl> <nl> - static std : : tuple < GenericEnvironment * , GenericParamList * , SubstitutionMap > <nl> + static std : : tuple < GenericSignature * , GenericParamList * , SubstitutionMap > <nl> configureGenericDesignatedInitOverride ( ASTContext & ctx , <nl> ClassDecl * classDecl , <nl> Type superclassTy , <nl> configureGenericDesignatedInitOverride ( ASTContext & ctx , <nl> auto subMap = superclassTy - > getContextSubstitutionMap ( <nl> moduleDecl , superclassDecl ) ; <nl> <nl> - GenericEnvironment * genericEnv ; <nl> + GenericSignature * genericSig ; <nl> <nl> / / Inheriting initializers that have their own generic parameters <nl> auto * genericParams = superclassCtor - > getGenericParams ( ) ; <nl> configureGenericDesignatedInitOverride ( ASTContext & ctx , <nl> subMap = SubstitutionMap : : get ( superclassSig , <nl> substFn , lookupConformanceFn ) ; <nl> <nl> - auto * genericSig = evaluateOrDefault ( <nl> + genericSig = evaluateOrDefault ( <nl> ctx . evaluator , <nl> AbstractGenericSignatureRequest { <nl> classDecl - > getGenericSignature ( ) , <nl> configureGenericDesignatedInitOverride ( ASTContext & ctx , <nl> std : : move ( requirements ) <nl> } , <nl> nullptr ) ; <nl> - genericEnv = genericSig - > createGenericEnvironment ( ) ; <nl> } else { <nl> - genericEnv = classDecl - > getGenericEnvironment ( ) ; <nl> + genericSig = classDecl - > getGenericSignature ( ) ; <nl> } <nl> <nl> - return std : : make_tuple ( genericEnv , genericParams , subMap ) ; <nl> + return std : : make_tuple ( genericSig , genericParams , subMap ) ; <nl> } <nl> <nl> static void <nl> createDesignatedInitOverride ( ClassDecl * classDecl , <nl> return nullptr ; <nl> } <nl> <nl> - GenericEnvironment * genericEnv ; <nl> + GenericSignature * genericSig ; <nl> GenericParamList * genericParams ; <nl> SubstitutionMap subMap ; <nl> <nl> - std : : tie ( genericEnv , genericParams , subMap ) = <nl> + std : : tie ( genericSig , genericParams , subMap ) = <nl> configureGenericDesignatedInitOverride ( ctx , <nl> classDecl , <nl> superclassTy , <nl> createDesignatedInitOverride ( ClassDecl * classDecl , <nl> ctor - > setImplicit ( ) ; <nl> <nl> / / Set the interface type of the initializer . <nl> - ctor - > setGenericEnvironment ( genericEnv ) ; <nl> + ctor - > setGenericSignature ( genericSig ) ; <nl> ctor - > computeType ( ) ; <nl> <nl> ctor - > setImplicitlyUnwrappedOptional ( <nl> mmm a / lib / Sema / DerivedConformanceCodable . cpp <nl> ppp b / lib / Sema / DerivedConformanceCodable . cpp <nl> static FuncDecl * deriveEncodable_encode ( DerivedConformance & derived ) { <nl> encodeDecl - > getAttrs ( ) . add ( attr ) ; <nl> } <nl> <nl> - if ( auto env = conformanceDC - > getGenericEnvironmentOfContext ( ) ) <nl> - encodeDecl - > setGenericEnvironment ( env ) ; <nl> + encodeDecl - > setGenericSignature ( conformanceDC - > getGenericSignatureOfContext ( ) ) ; <nl> encodeDecl - > computeType ( FunctionType : : ExtInfo ( ) . withThrows ( ) ) ; <nl> <nl> encodeDecl - > setValidationToChecked ( ) ; <nl> static ValueDecl * deriveDecodable_init ( DerivedConformance & derived ) { <nl> initDecl - > getAttrs ( ) . add ( reqAttr ) ; <nl> } <nl> <nl> - if ( auto env = conformanceDC - > getGenericEnvironmentOfContext ( ) ) <nl> - initDecl - > setGenericEnvironment ( env ) ; <nl> + initDecl - > setGenericSignature ( conformanceDC - > getGenericSignatureOfContext ( ) ) ; <nl> initDecl - > computeType ( AnyFunctionType : : ExtInfo ( ) . withThrows ( ) ) ; <nl> <nl> initDecl - > setValidationToChecked ( ) ; <nl> mmm a / lib / Sema / DerivedConformanceCodingKey . cpp <nl> ppp b / lib / Sema / DerivedConformanceCodingKey . cpp <nl> static ValueDecl * deriveInitDecl ( DerivedConformance & derived , Type paramType , <nl> synthesizer ( initDecl ) ; <nl> <nl> / / Compute the interface type of the initializer . <nl> - if ( auto env = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - initDecl - > setGenericEnvironment ( env ) ; <nl> + initDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> initDecl - > computeType ( ) ; <nl> <nl> initDecl - > setAccess ( derived . Nominal - > getFormalAccess ( ) ) ; <nl> mmm a / lib / Sema / DerivedConformanceEquatableHashable . cpp <nl> ppp b / lib / Sema / DerivedConformanceEquatableHashable . cpp <nl> deriveEquatable_eq ( <nl> eqDecl - > setBodySynthesizer ( bodySynthesizer ) ; <nl> <nl> / / Compute the interface type . <nl> - if ( auto genericEnv = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - eqDecl - > setGenericEnvironment ( genericEnv ) ; <nl> + eqDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> eqDecl - > computeType ( ) ; <nl> <nl> eqDecl - > copyFormalAccessFrom ( derived . Nominal , / * sourceIsParentContext * / true ) ; <nl> deriveHashable_hashInto ( <nl> hashDecl - > setImplicit ( ) ; <nl> hashDecl - > setBodySynthesizer ( bodySynthesizer ) ; <nl> <nl> - if ( auto env = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - hashDecl - > setGenericEnvironment ( env ) ; <nl> + hashDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> hashDecl - > computeType ( ) ; <nl> hashDecl - > copyFormalAccessFrom ( derived . Nominal ) ; <nl> hashDecl - > setValidationToChecked ( ) ; <nl> static ValueDecl * deriveHashable_hashValue ( DerivedConformance & derived ) { <nl> getterDecl - > setIsTransparent ( false ) ; <nl> <nl> / / Compute the interface type of hashValue ( ) . <nl> - if ( auto env = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - getterDecl - > setGenericEnvironment ( env ) ; <nl> + getterDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> getterDecl - > computeType ( ) ; <nl> <nl> getterDecl - > setValidationToChecked ( ) ; <nl> mmm a / lib / Sema / DerivedConformanceRawRepresentable . cpp <nl> ppp b / lib / Sema / DerivedConformanceRawRepresentable . cpp <nl> deriveRawRepresentable_init ( DerivedConformance & derived ) { <nl> initDecl - > setBodySynthesizer ( & deriveBodyRawRepresentable_init ) ; <nl> <nl> / / Compute the interface type of the initializer . <nl> - if ( auto env = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - initDecl - > setGenericEnvironment ( env ) ; <nl> + initDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> initDecl - > computeType ( ) ; <nl> <nl> initDecl - > copyFormalAccessFrom ( enumDecl , / * sourceIsParentContext * / true ) ; <nl> mmm a / lib / Sema / DerivedConformances . cpp <nl> ppp b / lib / Sema / DerivedConformances . cpp <nl> DerivedConformance : : declareDerivedPropertyGetter ( VarDecl * property , <nl> getterDecl - > setIsTransparent ( false ) ; <nl> <nl> / / Compute the interface type of the getter . <nl> - if ( auto env = parentDC - > getGenericEnvironmentOfContext ( ) ) <nl> - getterDecl - > setGenericEnvironment ( env ) ; <nl> + getterDecl - > setGenericSignature ( parentDC - > getGenericSignatureOfContext ( ) ) ; <nl> getterDecl - > computeType ( ) ; <nl> <nl> getterDecl - > copyFormalAccessFrom ( property ) ; <nl> mmm a / lib / Sema / TypeCheckDecl . cpp <nl> ppp b / lib / Sema / TypeCheckDecl . cpp <nl> TypeChecker : : handleSILGenericParams ( GenericParamList * genericParams , <nl> genericParams - > setDepth ( i ) ; <nl> } <nl> <nl> - return TypeChecker : : checkGenericEnvironment ( <nl> + auto * sig = TypeChecker : : checkGenericSignature ( <nl> nestedList . back ( ) , DC , <nl> / * parentSig = * / nullptr , <nl> / * allowConcreteGenericParams = * / true ) ; <nl> + return ( sig ? sig - > getGenericEnvironment ( ) : nullptr ) ; <nl> } <nl> <nl> / / / Check whether \ c current is a redeclaration . <nl> void TypeChecker : : validateDecl ( ValueDecl * D ) { <nl> for ( auto member : proto - > getMembers ( ) ) { <nl> if ( auto * aliasDecl = dyn_cast < TypeAliasDecl > ( member ) ) { <nl> if ( ! aliasDecl - > isGeneric ( ) ) { <nl> - aliasDecl - > setGenericEnvironment ( proto - > getGenericEnvironment ( ) ) ; <nl> + / / FIXME : Force creation of the protocol ' s generic environment now . <nl> + ( void ) proto - > getGenericEnvironment ( ) ; <nl> + aliasDecl - > setGenericSignature ( proto - > getGenericSignature ( ) ) ; <nl> <nl> / / The generic environment didn ' t exist until now , we may have <nl> / / unresolved types we will need to deal with , and need to record the <nl> static unsigned getExtendedTypeGenericDepth ( ExtensionDecl * ext ) { <nl> <nl> / / / Check the generic parameters of an extension , recursively handling all of <nl> / / / the parameter lists within the extension . <nl> - static GenericEnvironment * <nl> + static GenericSignature * <nl> checkExtensionGenericParams ( TypeChecker & tc , ExtensionDecl * ext , <nl> GenericParamList * genericParams ) { <nl> assert ( ! ext - > getGenericEnvironment ( ) ) ; <nl> checkExtensionGenericParams ( TypeChecker & tc , ExtensionDecl * ext , <nl> } ; <nl> <nl> / / Re - use the signature of the type being extended by default . <nl> - GenericSignature * sig = <nl> - ext - > getSelfNominalTypeDecl ( ) - > getGenericSignatureOfContext ( ) ; <nl> if ( cannotReuseNominalSignature ( ) ) { <nl> - return TypeChecker : : checkGenericEnvironment ( <nl> + return TypeChecker : : checkGenericSignature ( <nl> genericParams , ext , <nl> / * parent signature * / nullptr , <nl> / * allowConcreteGenericParams = * / true , <nl> checkExtensionGenericParams ( TypeChecker & tc , ExtensionDecl * ext , <nl> { TypeLoc { nullptr , extInterfaceType } } ) ; <nl> } <nl> <nl> - / / Form the generic environment . <nl> - return sig - > createGenericEnvironment ( ) ; <nl> + return ext - > getSelfNominalTypeDecl ( ) - > getGenericSignatureOfContext ( ) ; <nl> } <nl> <nl> static bool isNonGenericTypeAliasType ( Type type ) { <nl> void TypeChecker : : validateExtension ( ExtensionDecl * ext ) { <nl> validateDecl ( nominal ) ; <nl> <nl> if ( auto * genericParams = ext - > getGenericParams ( ) ) { <nl> - auto * env = checkExtensionGenericParams ( * this , ext , genericParams ) ; <nl> - ext - > setGenericEnvironment ( env ) ; <nl> + auto * sig = checkExtensionGenericParams ( * this , ext , genericParams ) ; <nl> + ext - > setGenericSignature ( sig ) ; <nl> } <nl> } <nl> } <nl> mmm a / lib / Sema / TypeCheckGeneric . cpp <nl> ppp b / lib / Sema / TypeCheckGeneric . cpp <nl> Type TypeChecker : : getOrCreateOpaqueResultType ( TypeResolution resolution , <nl> interfaceSignature , <nl> returnTypeParam ) ; <nl> opaqueDecl - > copyFormalAccessFrom ( originatingDecl ) ; <nl> - if ( auto originatingEnv = originatingDC - > getGenericEnvironmentOfContext ( ) ) { <nl> - opaqueDecl - > setGenericEnvironment ( originatingEnv ) ; <nl> + if ( auto originatingSig = originatingDC - > getGenericSignatureOfContext ( ) ) { <nl> + opaqueDecl - > setGenericSignature ( originatingSig ) ; <nl> } <nl> <nl> originatingDecl - > setOpaqueResultTypeDecl ( opaqueDecl ) ; <nl> void TypeChecker : : validateGenericFuncOrSubscriptSignature ( <nl> gpList - > setDepth ( genCtx - > getGenericContextDepth ( ) ) ; <nl> } else { <nl> / / Inherit the signature of the surrounding environment . <nl> - genCtx - > setGenericEnvironment ( <nl> - decl - > getDeclContext ( ) - > getGenericEnvironmentOfContext ( ) ) ; <nl> + genCtx - > setGenericSignature ( <nl> + decl - > getDeclContext ( ) - > getGenericSignatureOfContext ( ) ) ; <nl> } <nl> <nl> / / Accessors can always use the generic context of their storage <nl> void TypeChecker : : validateGenericFuncOrSubscriptSignature ( <nl> if ( auto accessor = dyn_cast < AccessorDecl > ( decl ) ) { <nl> auto subscr = dyn_cast < SubscriptDecl > ( accessor - > getStorage ( ) ) ; <nl> if ( gpList & & subscr ) { <nl> - auto env = subscr - > getGenericEnvironment ( ) ; <nl> - assert ( subscr - > getGenericSignature ( ) & & env & & <nl> - " accessor has generics but subscript is not generic " ) ; <nl> - genCtx - > setGenericEnvironment ( env ) ; <nl> + genCtx - > setGenericSignature ( subscr - > getGenericSignature ( ) ) ; <nl> } <nl> / / We ' ve inherited all of the type information already . <nl> accessor - > computeType ( ) ; <nl> void TypeChecker : : validateGenericFuncOrSubscriptSignature ( <nl> llvm : : errs ( ) < < " \ n " ; <nl> } <nl> <nl> - genCtx - > setGenericEnvironment ( sig - > createGenericEnvironment ( ) ) ; <nl> + genCtx - > setGenericSignature ( sig ) ; <nl> } <nl> <nl> auto resolution = TypeResolution : : forInterface ( genCtx , sig ) ; <nl> void TypeChecker : : validateGenericFuncOrSubscriptSignature ( <nl> / / / Generic types <nl> / / / <nl> <nl> - GenericEnvironment * TypeChecker : : checkGenericEnvironment ( <nl> + GenericSignature * TypeChecker : : checkGenericSignature ( <nl> GenericParamList * genericParams , <nl> DeclContext * dc , <nl> GenericSignature * parentSig , <nl> GenericEnvironment * TypeChecker : : checkGenericEnvironment ( <nl> llvm : : errs ( ) < < " \ n " ; <nl> } <nl> <nl> - <nl> - / / Form the generic environment . <nl> - return sig - > createGenericEnvironment ( ) ; <nl> + return sig ; <nl> } <nl> <nl> void TypeChecker : : validateGenericTypeSignature ( GenericTypeDecl * typeDecl ) { <nl> void TypeChecker : : validateGenericTypeSignature ( GenericTypeDecl * typeDecl ) { <nl> auto * dc = typeDecl - > getDeclContext ( ) ; <nl> <nl> if ( ! gp ) { <nl> - typeDecl - > setGenericEnvironment ( <nl> - dc - > getGenericEnvironmentOfContext ( ) ) ; <nl> + typeDecl - > setGenericSignature ( dc - > getGenericSignatureOfContext ( ) ) ; <nl> return ; <nl> } <nl> <nl> gp - > setDepth ( typeDecl - > getGenericContextDepth ( ) ) ; <nl> <nl> - auto * env = TypeChecker : : checkGenericEnvironment ( <nl> + auto * sig = TypeChecker : : checkGenericSignature ( <nl> gp , dc , <nl> dc - > getGenericSignatureOfContext ( ) , <nl> / * allowConcreteGenericParams = * / false ) ; <nl> - typeDecl - > setGenericEnvironment ( env ) ; <nl> + typeDecl - > setGenericSignature ( sig ) ; <nl> } <nl> <nl> / / / <nl> mmm a / lib / Sema / TypeCheckProtocol . cpp <nl> ppp b / lib / Sema / TypeCheckProtocol . cpp <nl> void ConformanceChecker : : recordTypeWitness ( AssociatedTypeDecl * assocType , <nl> SourceLoc ( ) , <nl> / * genericparams * / nullptr , <nl> DC ) ; <nl> - aliasDecl - > setGenericEnvironment ( DC - > getGenericEnvironmentOfContext ( ) ) ; <nl> + aliasDecl - > setGenericSignature ( DC - > getGenericSignatureOfContext ( ) ) ; <nl> aliasDecl - > setUnderlyingType ( type ) ; <nl> <nl> aliasDecl - > setImplicit ( ) ; <nl> mmm a / lib / Sema / TypeCheckType . cpp <nl> ppp b / lib / Sema / TypeCheckType . cpp <nl> GenericSignatureBuilder * TypeResolution : : getGenericSignatureBuilder ( ) const { <nl> assert ( stage = = TypeResolutionStage : : Interface ) ; <nl> if ( ! complete . builder ) { <nl> auto genericSig = getGenericSignature ( ) ; <nl> - ASTContext & ctx = genericSig - > getASTContext ( ) ; <nl> - complete . builder = ctx . getOrCreateGenericSignatureBuilder ( <nl> - genericSig - > getCanonicalSignature ( ) ) ; <nl> - <nl> + complete . builder = genericSig - > getGenericSignatureBuilder ( ) ; <nl> } <nl> <nl> return complete . builder ; <nl> mmm a / lib / Sema / TypeChecker . h <nl> ppp b / lib / Sema / TypeChecker . h <nl> class TypeChecker final : public LazyResolver { <nl> / / / <nl> / / / \ param inferenceSources Additional types to infer requirements from . <nl> / / / <nl> - / / / \ returns the resulting generic environment . <nl> - static GenericEnvironment * checkGenericEnvironment ( <nl> + / / / \ returns the resulting generic signature . <nl> + static GenericSignature * checkGenericSignature ( <nl> GenericParamList * genericParams , <nl> DeclContext * dc , <nl> GenericSignature * outerSignature , <nl> mmm a / lib / Serialization / Deserialization . cpp <nl> ppp b / lib / Serialization / Deserialization . cpp <nl> static void skipGenericRequirements ( llvm : : BitstreamCursor & Cursor ) { <nl> } <nl> } <nl> <nl> - void ModuleFile : : configureGenericEnvironment ( <nl> - GenericContext * genericDecl , serialization : : GenericSignatureID envID ) { <nl> - if ( envID = = 0 ) return ; <nl> - <nl> - auto sigOrEnv = getGenericSignatureOrEnvironment ( envID ) ; <nl> - <nl> - / / If we just have a generic signature , set up lazy generic environment <nl> - / / creation . <nl> - if ( auto genericSig = sigOrEnv . dyn_cast < GenericSignature * > ( ) ) { <nl> - genericDecl - > setLazyGenericEnvironment ( this , genericSig , envID ) ; <nl> - return ; <nl> - } <nl> - <nl> - / / If we have a full generic environment , it ' s because it happened to be <nl> - / / deserialized already . Record it directly . <nl> - if ( auto genericEnv = sigOrEnv . dyn_cast < GenericEnvironment * > ( ) ) { <nl> - genericDecl - > setGenericEnvironment ( genericEnv ) ; <nl> - return ; <nl> - } <nl> - } <nl> - <nl> GenericSignature * ModuleFile : : getGenericSignature ( <nl> serialization : : GenericSignatureID ID ) { <nl> using namespace decls_block ; <nl> GenericSignature * ModuleFile : : getGenericSignature ( <nl> / / Zero is a sentinel for having no generic signature . <nl> if ( ID = = 0 ) return nullptr ; <nl> <nl> - assert ( ID < = GenericSignaturesAndEnvironments . size ( ) & & <nl> + assert ( ID < = GenericSignatures . size ( ) & & <nl> " invalid GenericSignature ID " ) ; <nl> - auto & sigOrEnvOrOffset = GenericSignaturesAndEnvironments [ ID - 1 ] ; <nl> + auto & sigOffset = GenericSignatures [ ID - 1 ] ; <nl> <nl> / / If we ' ve already deserialized this generic signature , return it . <nl> - if ( sigOrEnvOrOffset . isComplete ( ) ) { <nl> - if ( auto * env = sigOrEnvOrOffset . get ( ) . dyn_cast < GenericEnvironment * > ( ) ) <nl> - return env - > getGenericSignature ( ) ; <nl> - return sigOrEnvOrOffset . get ( ) . get < GenericSignature * > ( ) ; <nl> - } <nl> + if ( sigOffset . isComplete ( ) ) <nl> + return sigOffset . get ( ) ; <nl> <nl> / / Read the generic signature . <nl> BCOffsetRAII restoreOffset ( DeclTypeCursor ) ; <nl> - DeclTypeCursor . JumpToBit ( sigOrEnvOrOffset ) ; <nl> + DeclTypeCursor . JumpToBit ( sigOffset ) ; <nl> <nl> / / Read the parameter types . <nl> SmallVector < GenericTypeParamType * , 4 > paramTypes ; <nl> GenericSignature * ModuleFile : : getGenericSignature ( <nl> / / If we ' ve already deserialized this generic signature , start over to return <nl> / / it directly . <nl> / / FIXME : Is this kind of re - entrancy actually possible ? <nl> - if ( sigOrEnvOrOffset . isComplete ( ) ) <nl> + if ( sigOffset . isComplete ( ) ) <nl> return getGenericSignature ( ID ) ; <nl> <nl> / / Construct the generic signature from the loaded parameters and <nl> / / requirements . <nl> auto signature = GenericSignature : : get ( paramTypes , requirements ) ; <nl> - sigOrEnvOrOffset = signature ; <nl> + sigOffset = signature ; <nl> return signature ; <nl> } <nl> <nl> - ModuleFile : : GenericSignatureOrEnvironment <nl> - ModuleFile : : getGenericSignatureOrEnvironment ( <nl> - serialization : : GenericSignatureID ID , <nl> - bool wantEnvironment ) { <nl> - / / The empty result with the type the caller expects . <nl> - GenericSignatureOrEnvironment result ; <nl> - if ( wantEnvironment ) <nl> - result = static_cast < GenericEnvironment * > ( nullptr ) ; <nl> - <nl> - / / Zero is a sentinel for having no generic environment . <nl> - if ( ID = = 0 ) return result ; <nl> - <nl> - assert ( ID < = GenericSignaturesAndEnvironments . size ( ) & & <nl> - " invalid GenericEnvironment ID " ) ; <nl> - auto & sigOrEnvOrOffset = GenericSignaturesAndEnvironments [ ID - 1 ] ; <nl> - <nl> - if ( ! sigOrEnvOrOffset . isComplete ( ) ) { <nl> - / / Force the loading process by fetching the generic signature . <nl> - ( void ) getGenericSignature ( ID ) ; <nl> - assert ( sigOrEnvOrOffset . isComplete ( ) ) ; <nl> - } <nl> - <nl> - if ( wantEnvironment ) <nl> - if ( auto * sig = sigOrEnvOrOffset . get ( ) . dyn_cast < GenericSignature * > ( ) ) <nl> - sigOrEnvOrOffset . uncheckedOverwrite ( sig - > createGenericEnvironment ( ) ) ; <nl> - <nl> - return sigOrEnvOrOffset . get ( ) ; <nl> - } <nl> - <nl> - GenericEnvironment * <nl> - ModuleFile : : getGenericEnvironment ( serialization : : GenericSignatureID ID ) { <nl> - return getGenericSignatureOrEnvironment ( ID , / * wantEnvironment = * / true ) <nl> - . get < GenericEnvironment * > ( ) ; <nl> - } <nl> - <nl> SubstitutionMap ModuleFile : : getSubstitutionMap ( <nl> serialization : : SubstitutionMapID id ) { <nl> using namespace decls_block ; <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> TypeID underlyingTypeID , interfaceTypeID ; <nl> bool isImplicit ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> uint8_t rawAccessLevel ; <nl> ArrayRef < uint64_t > dependencyIDs ; <nl> <nl> decls_block : : TypeAliasLayout : : readRecord ( scratch , nameID , contextID , <nl> underlyingTypeID , interfaceTypeID , <nl> - isImplicit , genericEnvID , <nl> + isImplicit , genericSigID , <nl> rawAccessLevel , dependencyIDs ) ; <nl> <nl> Identifier name = MF . getIdentifier ( nameID ) ; <nl> class swift : : DeclDeserializer { <nl> SourceLoc ( ) , genericParams , DC ) ; <nl> declOrOffset = alias ; <nl> <nl> - MF . configureGenericEnvironment ( alias , genericEnvID ) ; <nl> + alias - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> alias - > setUnderlyingType ( MF . getType ( underlyingTypeID ) ) ; <nl> <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> bool isImplicit ; <nl> bool isObjC ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> uint8_t rawAccessLevel ; <nl> unsigned numConformances , numInheritedTypes ; <nl> ArrayRef < uint64_t > rawInheritedAndDependencyIDs ; <nl> <nl> decls_block : : StructLayout : : readRecord ( scratch , nameID , contextID , <nl> - isImplicit , isObjC , genericEnvID , <nl> + isImplicit , isObjC , genericSigID , <nl> rawAccessLevel , <nl> numConformances , numInheritedTypes , <nl> rawInheritedAndDependencyIDs ) ; <nl> class swift : : DeclDeserializer { <nl> declOrOffset = theStruct ; <nl> <nl> / / Read the generic environment . <nl> - MF . configureGenericEnvironment ( theStruct , genericEnvID ) ; <nl> + theStruct - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> if ( auto accessLevel = getActualAccessLevel ( rawAccessLevel ) ) <nl> theStruct - > setAccess ( * accessLevel ) ; <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> bool isIUO , isFailable ; <nl> bool isImplicit , isObjC , hasStubImplementation , throws ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> uint8_t storedInitKind , rawAccessLevel ; <nl> DeclID overriddenID ; <nl> bool needsNewVTableEntry , firstTimeRequired ; <nl> class swift : : DeclDeserializer { <nl> isFailable , isIUO , isImplicit , <nl> isObjC , hasStubImplementation , <nl> throws , storedInitKind , <nl> - genericEnvID , <nl> + genericSigID , <nl> overriddenID , <nl> rawAccessLevel , <nl> needsNewVTableEntry , <nl> class swift : : DeclDeserializer { <nl> genericParams , parent ) ; <nl> declOrOffset = ctor ; <nl> <nl> - MF . configureGenericEnvironment ( ctor , genericEnvID ) ; <nl> + ctor - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> if ( auto accessLevel = getActualAccessLevel ( rawAccessLevel ) ) <nl> ctor - > setAccess ( * accessLevel ) ; <nl> class swift : : DeclDeserializer { <nl> uint8_t rawAccessorKind ; <nl> bool isObjC , hasForcedStaticDispatch , throws ; <nl> unsigned numNameComponentsBiased ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> TypeID resultInterfaceTypeID ; <nl> bool isIUO ; <nl> DeclID associatedDeclID ; <nl> class swift : : DeclDeserializer { <nl> isStatic , rawStaticSpelling , isObjC , <nl> rawMutModifier , <nl> hasForcedStaticDispatch , throws , <nl> - genericEnvID , <nl> + genericSigID , <nl> resultInterfaceTypeID , <nl> isIUO , <nl> associatedDeclID , overriddenID , <nl> class swift : : DeclDeserializer { <nl> isStatic , rawStaticSpelling , isObjC , <nl> rawMutModifier , <nl> hasForcedStaticDispatch , throws , <nl> - genericEnvID , <nl> + genericSigID , <nl> resultInterfaceTypeID , <nl> isIUO , <nl> overriddenID , <nl> class swift : : DeclDeserializer { <nl> } <nl> declOrOffset = fn ; <nl> <nl> - MF . configureGenericEnvironment ( fn , genericEnvID ) ; <nl> + fn - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> if ( auto accessLevel = getActualAccessLevel ( rawAccessLevel ) ) <nl> fn - > setAccess ( * accessLevel ) ; <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> GenericSignatureID interfaceSigID ; <nl> TypeID interfaceTypeID ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> SubstitutionMapID underlyingTypeID ; <nl> <nl> decls_block : : OpaqueTypeLayout : : readRecord ( scratch , contextID , <nl> namingDeclID , interfaceSigID , <nl> - interfaceTypeID , genericEnvID , <nl> + interfaceTypeID , genericSigID , <nl> underlyingTypeID ) ; <nl> <nl> auto declContext = MF . getDeclContext ( contextID ) ; <nl> - auto sig = MF . getGenericSignature ( interfaceSigID ) ; <nl> + auto interfaceSig = MF . getGenericSignature ( interfaceSigID ) ; <nl> auto interfaceType = MF . getType ( interfaceTypeID ) <nl> - > castTo < GenericTypeParamType > ( ) ; <nl> <nl> class swift : : DeclDeserializer { <nl> / / Create the decl . <nl> auto opaqueDecl = <nl> new ( ctx ) OpaqueTypeDecl ( nullptr , nullptr , declContext , <nl> - sig , interfaceType ) ; <nl> + interfaceSig , interfaceType ) ; <nl> declOrOffset = opaqueDecl ; <nl> <nl> auto namingDecl = cast < ValueDecl > ( MF . getDecl ( namingDeclID ) ) ; <nl> class swift : : DeclDeserializer { <nl> if ( auto genericParams = MF . maybeReadGenericParams ( opaqueDecl ) ) <nl> opaqueDecl - > setGenericParams ( genericParams ) ; <nl> <nl> - auto genericEnv = MF . getGenericEnvironment ( genericEnvID ) ; <nl> - opaqueDecl - > setGenericEnvironment ( genericEnv ) ; <nl> + auto genericSig = MF . getGenericSignature ( genericSigID ) ; <nl> + if ( genericSig ) <nl> + opaqueDecl - > setGenericSignature ( genericSig ) ; <nl> if ( underlyingTypeID ) <nl> opaqueDecl - > setUnderlyingTypeSubstitutions ( <nl> MF . getSubstitutionMap ( underlyingTypeID ) ) ; <nl> SubstitutionMap subs ; <nl> - if ( genericEnv ) { <nl> - subs = genericEnv - > getGenericSignature ( ) - > getIdentitySubstitutionMap ( ) ; <nl> + if ( genericSig ) { <nl> + subs = genericSig - > getIdentitySubstitutionMap ( ) ; <nl> } <nl> auto opaqueTy = OpaqueTypeArchetypeType : : get ( opaqueDecl , subs ) ; <nl> auto metatype = MetatypeType : : get ( opaqueTy ) ; <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> bool isImplicit , isObjC ; <nl> bool inheritsSuperclassInitializers ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> TypeID superclassID ; <nl> uint8_t rawAccessLevel ; <nl> unsigned numConformances , numInheritedTypes ; <nl> class swift : : DeclDeserializer { <nl> decls_block : : ClassLayout : : readRecord ( scratch , nameID , contextID , <nl> isImplicit , isObjC , <nl> inheritsSuperclassInitializers , <nl> - genericEnvID , superclassID , <nl> + genericSigID , superclassID , <nl> rawAccessLevel , numConformances , <nl> numInheritedTypes , <nl> rawInheritedAndDependencyIDs ) ; <nl> class swift : : DeclDeserializer { <nl> None , genericParams , DC ) ; <nl> declOrOffset = theClass ; <nl> <nl> - MF . configureGenericEnvironment ( theClass , genericEnvID ) ; <nl> + theClass - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> if ( auto accessLevel = getActualAccessLevel ( rawAccessLevel ) ) <nl> theClass - > setAccess ( * accessLevel ) ; <nl> class swift : : DeclDeserializer { <nl> DeclContextID contextID ; <nl> bool isImplicit ; <nl> bool isObjC ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> TypeID rawTypeID ; <nl> uint8_t rawAccessLevel ; <nl> unsigned numConformances , numInherited ; <nl> ArrayRef < uint64_t > rawInheritedAndDependencyIDs ; <nl> <nl> decls_block : : EnumLayout : : readRecord ( scratch , nameID , contextID , <nl> - isImplicit , isObjC , genericEnvID , <nl> + isImplicit , isObjC , genericSigID , <nl> rawTypeID , rawAccessLevel , <nl> numConformances , numInherited , <nl> rawInheritedAndDependencyIDs ) ; <nl> class swift : : DeclDeserializer { <nl> <nl> declOrOffset = theEnum ; <nl> <nl> - MF . configureGenericEnvironment ( theEnum , genericEnvID ) ; <nl> + theEnum - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> if ( auto accessLevel = getActualAccessLevel ( rawAccessLevel ) ) <nl> theEnum - > setAccess ( * accessLevel ) ; <nl> class swift : : DeclDeserializer { <nl> StringRef blobData ) { <nl> DeclContextID contextID ; <nl> bool isImplicit , isObjC , isGetterMutating , isSetterMutating ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> TypeID elemInterfaceTypeID ; <nl> bool isIUO ; <nl> ModuleFile : : AccessorRecord accessors ; <nl> class swift : : DeclDeserializer { <nl> opaqueReadOwnership , <nl> readImpl , writeImpl , readWriteImpl , <nl> numAccessors , <nl> - genericEnvID , <nl> + genericSigID , <nl> elemInterfaceTypeID , <nl> isIUO , <nl> overriddenID , rawAccessLevel , <nl> class swift : : DeclDeserializer { <nl> subscript - > setIsSetterMutating ( isSetterMutating ) ; <nl> declOrOffset = subscript ; <nl> <nl> - MF . configureGenericEnvironment ( subscript , genericEnvID ) ; <nl> + subscript - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> subscript - > setIndices ( MF . readParameterList ( ) ) ; <nl> <nl> class swift : : DeclDeserializer { <nl> DeclID extendedNominalID ; <nl> DeclContextID contextID ; <nl> bool isImplicit ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> unsigned numConformances , numInherited ; <nl> ArrayRef < uint64_t > inheritedAndDependencyIDs ; <nl> <nl> decls_block : : ExtensionLayout : : readRecord ( scratch , extendedTypeID , <nl> extendedNominalID , contextID , <nl> - isImplicit , genericEnvID , <nl> + isImplicit , genericSigID , <nl> numConformances , numInherited , <nl> inheritedAndDependencyIDs ) ; <nl> <nl> class swift : : DeclDeserializer { <nl> outerParams = genericParams ; <nl> } <nl> <nl> - MF . configureGenericEnvironment ( extension , genericEnvID ) ; <nl> + extension - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> auto extendedType = MF . getType ( extendedTypeID ) ; <nl> ctx . evaluator . cacheOutput ( ExtendedTypeRequest { extension } , <nl> class swift : : DeclDeserializer { <nl> StringRef blobData ) { <nl> DeclContextID contextID ; <nl> bool isImplicit , isObjC ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> <nl> decls_block : : DestructorLayout : : readRecord ( scratch , contextID , <nl> isImplicit , isObjC , <nl> - genericEnvID ) ; <nl> + genericSigID ) ; <nl> <nl> DeclContext * DC = MF . getDeclContext ( contextID ) ; <nl> if ( declOrOffset . isComplete ( ) ) <nl> class swift : : DeclDeserializer { <nl> if ( auto bodyText = MF . maybeReadInlinableBodyText ( ) ) <nl> dtor - > setBodyStringRepresentation ( * bodyText ) ; <nl> <nl> - MF . configureGenericEnvironment ( dtor , genericEnvID ) ; <nl> + dtor - > setGenericSignature ( MF . getGenericSignature ( genericSigID ) ) ; <nl> <nl> dtor - > setAccess ( std : : max ( cast < ClassDecl > ( DC ) - > getFormalAccess ( ) , <nl> AccessLevel : : Internal ) ) ; <nl> class swift : : TypeDeserializer { <nl> <nl> Expected < Type > deserializePrimaryArchetypeType ( ArrayRef < uint64_t > scratch , <nl> StringRef blobData ) { <nl> - GenericSignatureID envID ; <nl> + GenericSignatureID sigID ; <nl> unsigned depth , index ; <nl> <nl> - decls_block : : PrimaryArchetypeTypeLayout : : readRecord ( scratch , envID , <nl> + decls_block : : PrimaryArchetypeTypeLayout : : readRecord ( scratch , sigID , <nl> depth , index ) ; <nl> <nl> - auto env = MF . getGenericEnvironment ( envID ) ; <nl> - if ( ! env ) <nl> + auto sig = MF . getGenericSignature ( sigID ) ; <nl> + if ( ! sig ) <nl> MF . fatal ( ) ; <nl> <nl> Type interfaceType = GenericTypeParamType : : get ( depth , index , ctx ) ; <nl> - Type contextType = env - > mapTypeIntoContext ( interfaceType ) ; <nl> + Type contextType = sig - > getGenericEnvironment ( ) <nl> + - > mapTypeIntoContext ( interfaceType ) ; <nl> <nl> if ( contextType - > hasError ( ) ) <nl> MF . fatal ( ) ; <nl> class swift : : TypeDeserializer { <nl> <nl> auto rootTy = MF . getType ( rootID ) - > castTo < ArchetypeType > ( ) ; <nl> auto interfaceTy = MF . getType ( interfaceTyID ) - > castTo < DependentMemberType > ( ) ; <nl> - auto rootInterfaceTy = interfaceTy - > getRootGenericParam ( ) ; <nl> - <nl> - auto sig = rootTy - > getGenericEnvironment ( ) - > getGenericSignature ( ) ; <nl> - <nl> - auto subs = SubstitutionMap : : get ( sig , <nl> - [ & ] ( SubstitutableType * t ) - > Type { <nl> - if ( t - > isEqual ( rootInterfaceTy ) ) <nl> - return rootTy ; <nl> - return t ; <nl> - } , LookUpConformanceInModule ( MF . getAssociatedModule ( ) ) ) ; <nl> - <nl> - return Type ( interfaceTy ) . subst ( subs ) ; <nl> + return rootTy - > getGenericEnvironment ( ) - > mapTypeIntoContext ( interfaceTy ) ; <nl> } <nl> <nl> Expected < Type > deserializeGenericTypeParamType ( ArrayRef < uint64_t > scratch , <nl> void ModuleFile : : finishNormalConformance ( NormalProtocolConformance * conformance , <nl> } <nl> } <nl> <nl> - GenericEnvironment * ModuleFile : : loadGenericEnvironment ( const DeclContext * decl , <nl> - uint64_t contextData ) { <nl> - return getGenericEnvironment ( contextData ) ; <nl> - } <nl> - <nl> void ModuleFile : : loadRequirementSignature ( const ProtocolDecl * decl , <nl> uint64_t contextData , <nl> SmallVectorImpl < Requirement > & reqs ) { <nl> mmm a / lib / Serialization / DeserializeSIL . cpp <nl> ppp b / lib / Serialization / DeserializeSIL . cpp <nl> SILDeserializer : : readSILFunctionChecked ( DeclID FID , SILFunction * existingFn , <nl> DeclID clangNodeOwnerID ; <nl> TypeID funcTyID ; <nl> IdentifierID replacedFunctionID ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> unsigned rawLinkage , isTransparent , isSerialized , isThunk , <nl> isWithoutactuallyEscapingThunk , isGlobal , inlineStrategy , <nl> optimizationMode , effect , numSpecAttrs , hasQualifiedOwnership , <nl> SILDeserializer : : readSILFunctionChecked ( DeclID FID , SILFunction * existingFn , <nl> isWithoutactuallyEscapingThunk , isGlobal , inlineStrategy , <nl> optimizationMode , effect , numSpecAttrs , hasQualifiedOwnership , <nl> isWeakLinked , isDynamic , isExactSelfClass , <nl> - funcTyID , replacedFunctionID , genericEnvID , <nl> + funcTyID , replacedFunctionID , genericSigID , <nl> clangNodeOwnerID , SemanticsIDs ) ; <nl> <nl> if ( funcTyID = = 0 ) { <nl> SILDeserializer : : readSILFunctionChecked ( DeclID FID , SILFunction * existingFn , <nl> <nl> GenericEnvironment * genericEnv = nullptr ; <nl> if ( ! declarationOnly ) <nl> - genericEnv = MF - > getGenericEnvironment ( genericEnvID ) ; <nl> + if ( auto * genericSig = MF - > getGenericSignature ( genericSigID ) ) <nl> + genericEnv = genericSig - > getGenericEnvironment ( ) ; <nl> <nl> / / If the next entry is the end of the block , then this function has <nl> / / no contents . <nl> bool SILDeserializer : : hasSILFunction ( StringRef Name , <nl> DeclID clangOwnerID ; <nl> TypeID funcTyID ; <nl> IdentifierID replacedFunctionID ; <nl> - GenericSignatureID genericEnvID ; <nl> + GenericSignatureID genericSigID ; <nl> unsigned rawLinkage , isTransparent , isSerialized , isThunk , <nl> isWithoutactuallyEscapingThunk , isGlobal , inlineStrategy , <nl> optimizationMode , effect , numSpecAttrs , hasQualifiedOwnership , <nl> bool SILDeserializer : : hasSILFunction ( StringRef Name , <nl> isWithoutactuallyEscapingThunk , isGlobal , inlineStrategy , <nl> optimizationMode , effect , numSpecAttrs , hasQualifiedOwnership , <nl> isWeakLinked , isDynamic , isExactSelfClass , <nl> - funcTyID , replacedFunctionID , genericEnvID , <nl> + funcTyID , replacedFunctionID , genericSigID , <nl> clangOwnerID , SemanticsIDs ) ; <nl> auto linkage = fromStableSILLinkage ( rawLinkage ) ; <nl> if ( ! linkage ) { <nl> mmm a / lib / Serialization / ModuleFile . cpp <nl> ppp b / lib / Serialization / ModuleFile . cpp <nl> bool ModuleFile : : readIndexBlock ( llvm : : BitstreamCursor & cursor ) { <nl> break ; <nl> case index_block : : GENERIC_SIGNATURE_OFFSETS : <nl> assert ( blobData . empty ( ) ) ; <nl> - allocateBuffer ( GenericSignaturesAndEnvironments , scratch ) ; <nl> + allocateBuffer ( GenericSignatures , scratch ) ; <nl> break ; <nl> case index_block : : SUBSTITUTION_MAP_OFFSETS : <nl> assert ( blobData . empty ( ) ) ; <nl> bool SerializedASTFile : : hasEntryPoint ( ) const { <nl> bool SerializedASTFile : : getAllGenericSignatures ( <nl> SmallVectorImpl < GenericSignature * > & genericSignatures ) { <nl> genericSignatures . clear ( ) ; <nl> - for ( unsigned index : indices ( File . GenericSignaturesAndEnvironments ) ) { <nl> + for ( unsigned index : indices ( File . GenericSignatures ) ) { <nl> if ( auto genericSig = File . getGenericSignature ( index + 1 ) ) <nl> genericSignatures . push_back ( genericSig ) ; <nl> } <nl> mmm a / lib / Serialization / ModuleFile . h <nl> ppp b / lib / Serialization / ModuleFile . h <nl> class ModuleFile <nl> / / / Types referenced by this module . <nl> MutableArrayRef < Serialized < Type > > Types ; <nl> <nl> - using GenericSignatureOrEnvironment = <nl> - llvm : : PointerUnion < GenericSignature * , GenericEnvironment * > ; <nl> - <nl> - / / / Generic signatures and environments referenced by this module . <nl> - / / / <nl> - / / / Technically only the GenericSignatures are encoded , but storing the <nl> - / / / environment here too allows caching them . <nl> - / / FIXME : That caching should be done at the AST level ; it ' s not specific to <nl> - / / Serialization . <nl> - MutableArrayRef < Serialized < GenericSignatureOrEnvironment > > <nl> - GenericSignaturesAndEnvironments ; <nl> + / / / Generic signatures referenced by this module . <nl> + MutableArrayRef < Serialized < GenericSignature * > > GenericSignatures ; <nl> <nl> / / / Substitution maps referenced by this module . <nl> MutableArrayRef < Serialized < SubstitutionMap > > SubstitutionMaps ; <nl> class ModuleFile <nl> void readGenericRequirements ( SmallVectorImpl < Requirement > & requirements , <nl> llvm : : BitstreamCursor & Cursor ) ; <nl> <nl> - / / / Set up a ( potentially lazy ) generic environment for the given type , <nl> - / / / function or extension . <nl> - void configureGenericEnvironment ( GenericContext * genericDecl , <nl> - serialization : : GenericSignatureID envID ) ; <nl> - <nl> / / / Populates the protocol ' s default witness table . <nl> / / / <nl> / / / Returns true if there is an error . <nl> class ModuleFile <nl> virtual void finishNormalConformance ( NormalProtocolConformance * conformance , <nl> uint64_t contextData ) override ; <nl> <nl> - GenericEnvironment * loadGenericEnvironment ( const DeclContext * decl , <nl> - uint64_t contextData ) override ; <nl> - <nl> void <nl> loadRequirementSignature ( const ProtocolDecl * proto , uint64_t contextData , <nl> SmallVectorImpl < Requirement > & requirements ) override ; <nl> class ModuleFile <nl> / / / Returns the generic signature for the given ID . <nl> GenericSignature * getGenericSignature ( serialization : : GenericSignatureID ID ) ; <nl> <nl> - / / / Returns the generic signature or environment for the given ID , <nl> - / / / deserializing it if needed . <nl> - / / / <nl> - / / / \ param wantEnvironment If true , always return the full generic <nl> - / / / environment . Otherwise , only return the generic environment if it ' s <nl> - / / / already been constructed , and the signature in other cases . <nl> - GenericSignatureOrEnvironment <nl> - getGenericSignatureOrEnvironment ( serialization : : GenericSignatureID ID , <nl> - bool wantEnvironment = false ) ; <nl> - <nl> - / / / Returns the generic environment for the given ID , deserializing it if <nl> - / / / needed . <nl> - GenericEnvironment * <nl> - getGenericEnvironment ( serialization : : GenericSignatureID ID ) ; <nl> - <nl> / / / Returns the substitution map for the given ID , deserializing it if <nl> / / / needed . <nl> SubstitutionMap getSubstitutionMap ( serialization : : SubstitutionMapID id ) ; <nl> mmm a / lib / Serialization / Serialization . cpp <nl> ppp b / lib / Serialization / Serialization . cpp <nl> LocalDeclContextID Serializer : : addLocalDeclContextRef ( const DeclContext * DC ) { <nl> <nl> GenericSignatureID <nl> Serializer : : addGenericSignatureRef ( const GenericSignature * sig ) { <nl> - return GenericSignaturesToSerialize . addRef ( sig ) ; <nl> - } <nl> - <nl> - GenericSignatureID <nl> - Serializer : : addGenericEnvironmentRef ( const GenericEnvironment * env ) { <nl> - if ( ! env ) <nl> + if ( ! sig ) <nl> return 0 ; <nl> - return addGenericSignatureRef ( env - > getGenericSignature ( ) ) ; <nl> + return GenericSignaturesToSerialize . addRef ( sig ) ; <nl> } <nl> <nl> SubstitutionMapID <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> S . addDeclRef ( extendedNominal ) , <nl> contextID . getOpaqueValue ( ) , <nl> extension - > isImplicit ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - extension - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + extension - > getGenericSignature ( ) ) , <nl> conformances . size ( ) , <nl> numInherited , <nl> inheritedAndDependencyTypes ) ; <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> S . addTypeRef ( underlying ) , <nl> / * no longer used * / TypeID ( ) , <nl> typeAlias - > isImplicit ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - typeAlias - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + typeAlias - > getGenericSignature ( ) ) , <nl> rawAccessLevel , <nl> dependencyIDs ) ; <nl> writeGenericParams ( typeAlias - > getGenericParams ( ) ) ; <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> contextID . getOpaqueValue ( ) , <nl> theStruct - > isImplicit ( ) , <nl> theStruct - > isObjC ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - theStruct - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + theStruct - > getGenericSignature ( ) ) , <nl> rawAccessLevel , <nl> conformances . size ( ) , <nl> theStruct - > getInherited ( ) . size ( ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> contextID . getOpaqueValue ( ) , <nl> theEnum - > isImplicit ( ) , <nl> theEnum - > isObjC ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - theEnum - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + theEnum - > getGenericSignature ( ) ) , <nl> S . addTypeRef ( theEnum - > getRawType ( ) ) , <nl> rawAccessLevel , <nl> conformances . size ( ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> theClass - > isImplicit ( ) , <nl> theClass - > isObjC ( ) , <nl> inheritsSuperclassInitializers , <nl> - S . addGenericEnvironmentRef ( <nl> - theClass - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + theClass - > getGenericSignature ( ) ) , <nl> S . addTypeRef ( theClass - > getSuperclass ( ) ) , <nl> rawAccessLevel , <nl> conformances . size ( ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> getStableSelfAccessKind ( fn - > getSelfAccessKind ( ) ) ) , <nl> fn - > hasForcedStaticDispatch ( ) , <nl> fn - > hasThrows ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - fn - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + fn - > getGenericSignature ( ) ) , <nl> S . addTypeRef ( fn - > getResultInterfaceType ( ) ) , <nl> fn - > isImplicitlyUnwrappedOptional ( ) , <nl> S . addDeclRef ( fn - > getOperatorDecl ( ) ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> auto interfaceTypeID = <nl> S . addTypeRef ( opaqueDecl - > getUnderlyingInterfaceType ( ) ) ; <nl> <nl> - auto genericEnvID = S . addGenericEnvironmentRef ( opaqueDecl - > getGenericEnvironment ( ) ) ; <nl> + auto genericSigID = S . addGenericSignatureRef ( opaqueDecl - > getGenericSignature ( ) ) ; <nl> <nl> SubstitutionMapID underlyingTypeID = 0 ; <nl> if ( auto underlying = opaqueDecl - > getUnderlyingTypeSubstitutions ( ) ) <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> unsigned abbrCode = S . DeclTypeAbbrCodes [ OpaqueTypeLayout : : Code ] ; <nl> OpaqueTypeLayout : : emitRecord ( S . Out , S . ScratchRecord , abbrCode , <nl> contextID . getOpaqueValue ( ) , namingDeclID , <nl> - interfaceSigID , interfaceTypeID , genericEnvID , <nl> + interfaceSigID , interfaceTypeID , genericSigID , <nl> underlyingTypeID ) ; <nl> writeGenericParams ( opaqueDecl - > getGenericParams ( ) ) ; <nl> } <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> fn - > getSelfAccessKind ( ) ) ) , <nl> fn - > hasForcedStaticDispatch ( ) , <nl> fn - > hasThrows ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - fn - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + fn - > getGenericSignature ( ) ) , <nl> S . addTypeRef ( fn - > getResultInterfaceType ( ) ) , <nl> fn - > isImplicitlyUnwrappedOptional ( ) , <nl> S . addDeclRef ( fn - > getOverriddenDecl ( ) ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> accessors . WriteImpl , <nl> accessors . ReadWriteImpl , <nl> accessors . Decls . size ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - subscript - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + subscript - > getGenericSignature ( ) ) , <nl> S . addTypeRef ( subscript - > getElementInterfaceType ( ) ) , <nl> subscript - > isImplicitlyUnwrappedOptional ( ) , <nl> S . addDeclRef ( subscript - > getOverriddenDecl ( ) ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> ctor - > hasThrows ( ) , <nl> getStableCtorInitializerKind ( <nl> ctor - > getInitKind ( ) ) , <nl> - S . addGenericEnvironmentRef ( <nl> - ctor - > getGenericEnvironment ( ) ) , <nl> + S . addGenericSignatureRef ( <nl> + ctor - > getGenericSignature ( ) ) , <nl> S . addDeclRef ( ctor - > getOverriddenDecl ( ) ) , <nl> rawAccessLevel , <nl> ctor - > needsNewVTableEntry ( ) , <nl> class Serializer : : DeclSerializer : public DeclVisitor < DeclSerializer > { <nl> contextID . getOpaqueValue ( ) , <nl> dtor - > isImplicit ( ) , <nl> dtor - > isObjC ( ) , <nl> - S . addGenericEnvironmentRef ( <nl> - dtor - > getGenericEnvironment ( ) ) ) ; <nl> + S . addGenericSignatureRef ( <nl> + dtor - > getGenericSignature ( ) ) ) ; <nl> writeInlinableBodyTextIfNeeded ( dtor ) ; <nl> } <nl> <nl> class Serializer : : TypeSerializer : public TypeVisitor < TypeSerializer > { <nl> <nl> void visitPrimaryArchetypeType ( const PrimaryArchetypeType * archetypeTy ) { <nl> using namespace decls_block ; <nl> - auto env = archetypeTy - > getGenericEnvironment ( ) ; <nl> + auto sig = archetypeTy - > getGenericEnvironment ( ) - > getGenericSignature ( ) ; <nl> <nl> - GenericSignatureID envID = S . addGenericEnvironmentRef ( env ) ; <nl> + GenericSignatureID sigID = S . addGenericSignatureRef ( sig ) ; <nl> auto interfaceType = archetypeTy - > getInterfaceType ( ) <nl> - > castTo < GenericTypeParamType > ( ) ; <nl> <nl> unsigned abbrCode = S . DeclTypeAbbrCodes [ PrimaryArchetypeTypeLayout : : Code ] ; <nl> PrimaryArchetypeTypeLayout : : emitRecord ( S . Out , S . ScratchRecord , abbrCode , <nl> - envID , <nl> + sigID , <nl> interfaceType - > getDepth ( ) , <nl> interfaceType - > getIndex ( ) ) ; <nl> } <nl> mmm a / lib / Serialization / Serialization . h <nl> ppp b / lib / Serialization / Serialization . h <nl> class Serializer : public SerializerBase { <nl> / / / The GenericSignature will be scheduled for serialization if necessary . <nl> GenericSignatureID addGenericSignatureRef ( const GenericSignature * sig ) ; <nl> <nl> - / / / Records the use of the given generic environment . <nl> - / / / <nl> - / / / The GenericEnvironment will be scheduled for serialization if necessary . <nl> - GenericSignatureID addGenericEnvironmentRef ( const GenericEnvironment * env ) ; <nl> - <nl> / / / Records the use of the given substitution map . <nl> / / / <nl> / / / The SubstitutionMap will be scheduled for serialization if necessary . <nl> mmm a / lib / Serialization / SerializeSIL . cpp <nl> ppp b / lib / Serialization / SerializeSIL . cpp <nl> <nl> # define DEBUG_TYPE " sil - serialize " <nl> # include " SILFormat . h " <nl> # include " Serialization . h " <nl> + # include " swift / AST / GenericEnvironment . h " <nl> # include " swift / AST / GenericSignature . h " <nl> # include " swift / AST / Module . h " <nl> # include " swift / AST / ProtocolConformance . h " <nl> void SILSerializer : : writeSILFunction ( const SILFunction & F , bool DeclOnly ) { <nl> } <nl> <nl> / / If we have a body , we might have a generic environment . <nl> - GenericSignatureID genericEnvID = 0 ; <nl> + GenericSignatureID genericSigID = 0 ; <nl> if ( ! NoBody ) <nl> - genericEnvID = S . addGenericEnvironmentRef ( F . getGenericEnvironment ( ) ) ; <nl> + if ( auto * genericEnv = F . getGenericEnvironment ( ) ) <nl> + genericSigID = S . addGenericSignatureRef ( genericEnv - > getGenericSignature ( ) ) ; <nl> <nl> DeclID clangNodeOwnerID ; <nl> if ( F . hasClangNode ( ) ) <nl> void SILSerializer : : writeSILFunction ( const SILFunction & F , bool DeclOnly ) { <nl> ( unsigned ) numSpecAttrs , ( unsigned ) F . hasOwnership ( ) , <nl> F . isWeakLinked ( ) , ( unsigned ) F . isDynamicallyReplaceable ( ) , <nl> ( unsigned ) F . isExactSelfClass ( ) , <nl> - FnID , replacedFunctionID , genericEnvID , clangNodeOwnerID , SemanticsIDs ) ; <nl> + FnID , replacedFunctionID , genericSigID , clangNodeOwnerID , SemanticsIDs ) ; <nl> <nl> if ( NoBody ) <nl> return ; <nl> | Merge pull request from slavapestov / unique - generic - environments | apple/swift | 19f5ac15c9d1ae98b76f8038f36bf2e98ec7cf07 | 2019-09-07T00:08:25Z |
mmm a / swoole_coroutine . cc <nl> ppp b / swoole_coroutine . cc <nl> int sw_get_current_cid ( ) <nl> } <nl> else <nl> { <nl> - coro_task * task = sw_get_current_task ( ) ; <nl> + coro_task * task = sw_get_current_task ( ) ; <nl> if ( task ) <nl> { <nl> return task - > cid ; <nl> mmm a / swoole_server . c <nl> ppp b / swoole_server . c <nl> static void php_swoole_onManagerStop ( swServer * serv ) ; <nl> static void php_swoole_onConnect_finish ( void * param ) ; <nl> static void php_swoole_onSendTimeout ( swTimer * timer , swTimer_node * tnode ) ; <nl> static void php_swoole_server_send_resume ( swServer * serv , php_context * context , int fd ) ; <nl> + static void php_swoole_task_onTimeout ( swTimer * timer , swTimer_node * tnode ) ; <nl> # endif <nl> <nl> static zval * php_swoole_server_add_port ( swServer * serv , swListenPort * port TSRMLS_DC ) ; <nl> zval * php_swoole_task_unpack ( swEventData * task_result TSRMLS_DC ) <nl> return result_data ; <nl> } <nl> <nl> + static void php_swoole_task_wait_co ( swServer * serv , swEventData * req , double timeout , int dst_worker_id , INTERNAL_FUNCTION_PARAMETERS ) <nl> + { <nl> + swTask_type ( req ) | = ( SW_TASK_NONBLOCK | SW_TASK_COROUTINE ) ; <nl> + <nl> + swTaskCo * task_co = emalloc ( sizeof ( swTaskCo ) ) ; <nl> + <nl> + task_co - > result = NULL ; <nl> + task_co - > list = NULL ; <nl> + task_co - > count = 1 ; <nl> + task_co - > context . onTimeout = NULL ; <nl> + task_co - > context . state = SW_CORO_CONTEXT_RUNNING ; <nl> + Z_LVAL ( task_co - > context . coro_params ) = req - > info . fd ; <nl> + <nl> + if ( swProcessPool_dispatch ( & serv - > gs - > task_workers , req , & dst_worker_id ) < 0 ) <nl> + { <nl> + RETURN_FALSE ; <nl> + } <nl> + else <nl> + { <nl> + sw_atomic_fetch_add ( & serv - > stats - > tasking_num , 1 ) ; <nl> + swHashMap_add_int ( task_coroutine_map , req - > info . fd , task_co ) ; <nl> + } <nl> + <nl> + int ms = ( int ) ( timeout * 1000 ) ; <nl> + php_swoole_check_timer ( ms ) ; <nl> + swTimer_node * timer = SwooleG . timer . add ( & SwooleG . timer , ms , 0 , task_co , php_swoole_task_onTimeout ) ; <nl> + if ( timer ) <nl> + { <nl> + task_co - > timer = timer ; <nl> + } <nl> + coro_save ( & task_co - > context ) ; <nl> + coro_yield ( ) ; <nl> + } <nl> + <nl> # ifdef SW_COROUTINE <nl> static void php_swoole_task_onTimeout ( swTimer * timer , swTimer_node * tnode ) <nl> { <nl> swTaskCo * task_co = ( swTaskCo * ) tnode - > data ; <nl> - int i ; <nl> + php_context * context = & task_co - > context ; <nl> zval * retval = NULL ; <nl> + <nl> + / / Server - > taskwait , single task <nl> + if ( task_co - > list = = NULL ) <nl> + { <nl> + zval result ; <nl> + ZVAL_FALSE ( & result ) ; <nl> + int ret = coro_resume ( context , & result , & retval ) ; <nl> + if ( ret = = CORO_END & & retval ) <nl> + { <nl> + sw_zval_ptr_dtor ( & retval ) ; <nl> + } <nl> + efree ( task_co ) ; <nl> + swHashMap_del_int ( task_coroutine_map , Z_LVAL ( context - > coro_params ) ) ; <nl> + return ; <nl> + } <nl> + <nl> + int i ; <nl> zval * result = task_co - > result ; <nl> <nl> for ( i = 0 ; i < task_co - > count ; i + + ) <nl> static void php_swoole_task_onTimeout ( swTimer * timer , swTimer_node * tnode ) <nl> } <nl> } <nl> <nl> - php_context * context = & task_co - > context ; <nl> int ret = coro_resume ( context , result , & retval ) ; <nl> if ( ret = = CORO_END & & retval ) <nl> { <nl> static int php_swoole_onFinish ( swServer * serv , swEventData * req ) <nl> fail : sw_zval_free ( zdata ) ; <nl> return SW_OK ; <nl> } <nl> + / / Server - > taskwait <nl> + if ( task_co - > list = = NULL ) <nl> + { <nl> + if ( task_co - > timer ) <nl> + { <nl> + swTimer_del ( & SwooleG . timer , task_co - > timer ) ; <nl> + } <nl> + php_context * context = & task_co - > context ; <nl> + int ret = coro_resume ( context , zdata , & retval ) ; <nl> + if ( ret = = CORO_END & & retval ) <nl> + { <nl> + sw_zval_ptr_dtor ( & retval ) ; <nl> + } <nl> + efree ( task_co ) ; <nl> + efree ( zdata ) ; <nl> + swHashMap_del_int ( task_coroutine_map , task_id ) ; <nl> + return SW_OK ; <nl> + } <nl> + / / Server - > taskCo <nl> int i , task_index = - 1 ; <nl> zval * result = task_co - > result ; <nl> for ( i = 0 ; i < task_co - > count ; i + + ) <nl> static int php_swoole_onFinish ( swServer * serv , swEventData * req ) <nl> goto fail ; <nl> } <nl> add_index_zval ( result , task_index , zdata ) ; <nl> - # if PHP_MAJOR_VERSION > = 7 <nl> efree ( zdata ) ; <nl> - # endif <nl> swHashMap_del_int ( task_coroutine_map , task_id ) ; <nl> <nl> if ( php_swoole_array_length ( result ) = = task_co - > count ) <nl> PHP_METHOD ( swoole_server , taskwait ) <nl> RETURN_FALSE ; <nl> } <nl> <nl> + int _dst_worker_id = ( int ) dst_worker_id ; <nl> + <nl> + / / coroutine <nl> + if ( sw_get_current_cid ( ) > = 0 ) <nl> + { <nl> + php_swoole_task_wait_co ( serv , & buf , timeout , _dst_worker_id , INTERNAL_FUNCTION_PARAM_PASSTHRU ) ; <nl> + return ; <nl> + } <nl> + <nl> int task_id = buf . info . fd ; <nl> <nl> uint64_t notify ; <nl> PHP_METHOD ( swoole_server , taskwait ) <nl> / / clear history task <nl> while ( read ( efd , & notify , sizeof ( notify ) ) > 0 ) ; <nl> <nl> - int _dst_worker_id = ( int ) dst_worker_id ; <nl> if ( swProcessPool_dispatch_blocking ( & serv - > gs - > task_workers , & buf , & _dst_worker_id ) > = 0 ) <nl> { <nl> sw_atomic_fetch_add ( & serv - > stats - > tasking_num , 1 ) ; <nl> similarity index 98 % <nl> rename from tests / swoole_server / taskwait . phpt <nl> rename to tests / swoole_server / taskwait_01 . phpt <nl> mmm a / tests / swoole_server / taskwait . phpt <nl> ppp b / tests / swoole_server / taskwait_01 . phpt <nl> <nl> - - TEST - - <nl> - swoole_server : taskwait <nl> + swoole_server : taskwait [ blocking ] <nl> - - SKIPIF - - <nl> < ? php require __DIR__ . ' / . . / include / skipif . inc ' ; ? > <nl> - - INI - - <nl> $ pm - > childFunc = function ( ) use ( $ pm , $ port ) <nl> $ serv - > set ( array ( <nl> " worker_num " = > 1 , <nl> ' task_worker_num ' = > 1 , <nl> + ' enable_coroutine ' = > false , <nl> ' log_file ' = > ' / dev / null ' , <nl> ) ) ; <nl> $ serv - > on ( " WorkerStart " , function ( \ swoole_server $ serv ) use ( $ pm ) <nl> new file mode 100644 <nl> index 0000000000 . . c2fac2a52b <nl> mmm / dev / null <nl> ppp b / tests / swoole_server / taskwait_02 . phpt <nl> <nl> + - - TEST - - <nl> + swoole_server : taskwait [ coroutine ] <nl> + - - SKIPIF - - <nl> + < ? php require __DIR__ . ' / . . / include / skipif . inc ' ; ? > <nl> + - - INI - - <nl> + assert . active = 1 <nl> + assert . warning = 1 <nl> + assert . bail = 0 <nl> + assert . quiet_eval = 0 <nl> + <nl> + <nl> + - - FILE - - <nl> + < ? php <nl> + require_once __DIR__ . ' / . . / include / bootstrap . php ' ; <nl> + $ port = get_one_free_port ( ) ; <nl> + <nl> + $ pm = new ProcessManager ; <nl> + $ pm - > parentFunc = function ( $ pid ) use ( $ port ) <nl> + { <nl> + $ cli = new swoole_client ( SWOOLE_SOCK_TCP , SWOOLE_SOCK_SYNC ) ; <nl> + $ cli - > connect ( " 127 . 0 . 0 . 1 " , $ port , 0 . 5 ) or die ( " ERROR " ) ; <nl> + <nl> + $ cli - > send ( " array - 01 " ) or die ( " ERROR " ) ; <nl> + assert ( $ cli - > recv ( ) = = ' OK ' ) ; <nl> + $ cli - > send ( " array - 02 " ) or die ( " ERROR " ) ; <nl> + assert ( $ cli - > recv ( ) = = ' OK ' ) ; <nl> + $ cli - > send ( " string - 01 " ) or die ( " ERROR " ) ; <nl> + assert ( $ cli - > recv ( ) = = ' OK ' ) ; <nl> + $ cli - > send ( " string - 02 " ) or die ( " ERROR " ) ; <nl> + assert ( $ cli - > recv ( ) = = ' OK ' ) ; <nl> + $ cli - > send ( " timeout " ) or die ( " ERROR " ) ; <nl> + assert ( $ cli - > recv ( ) = = ' OK ' ) ; <nl> + <nl> + swoole_process : : kill ( $ pid ) ; <nl> + } ; <nl> + <nl> + $ pm - > childFunc = function ( ) use ( $ pm , $ port ) <nl> + { <nl> + ini_set ( ' swoole . display_errors ' , ' Off ' ) ; <nl> + ini_set ( ' display_errors ' , ' Off ' ) ; <nl> + $ serv = new swoole_server ( " 127 . 0 . 0 . 1 " , $ port ) ; <nl> + $ serv - > set ( array ( <nl> + " worker_num " = > 1 , <nl> + ' task_worker_num ' = > 1 , <nl> + ' log_file ' = > ' / dev / null ' , <nl> + ' enable_coroutine ' = > true , <nl> + ) ) ; <nl> + $ serv - > on ( " WorkerStart " , function ( \ swoole_server $ serv ) use ( $ pm ) <nl> + { <nl> + $ pm - > wakeup ( ) ; <nl> + } ) ; <nl> + $ serv - > on ( ' receive ' , function ( swoole_server $ serv , $ fd , $ rid , $ data ) <nl> + { <nl> + if ( $ data = = ' array - 01 ' ) <nl> + { <nl> + $ res = $ serv - > taskwait ( [ ' type ' = > ' array ' , ' value ' = > $ data ] ) ; <nl> + if ( ! empty ( $ res [ ' name ' ] ) ) <nl> + { <nl> + $ serv - > send ( $ fd , ' OK ' ) ; <nl> + } <nl> + else <nl> + { <nl> + $ serv - > send ( $ fd , ' ERR ' ) ; <nl> + } <nl> + } <nl> + elseif ( $ data = = ' array - 02 ' ) <nl> + { <nl> + $ res = $ serv - > taskwait ( [ ' type ' = > ' string ' , ' value ' = > $ data ] ) ; <nl> + if ( $ res = = " hello world \ n " ) <nl> + { <nl> + $ serv - > send ( $ fd , ' OK ' ) ; <nl> + } <nl> + else <nl> + { <nl> + $ serv - > send ( $ fd , ' ERR ' ) ; <nl> + } <nl> + } <nl> + elseif ( $ data = = ' string - 01 ' ) <nl> + { <nl> + $ res = $ serv - > taskwait ( ' array ' ) ; <nl> + if ( ! empty ( $ res [ ' name ' ] ) ) <nl> + { <nl> + $ serv - > send ( $ fd , ' OK ' ) ; <nl> + } <nl> + else <nl> + { <nl> + $ serv - > send ( $ fd , ' ERR ' ) ; <nl> + } <nl> + } <nl> + elseif ( $ data = = ' string - 02 ' ) <nl> + { <nl> + $ res = $ serv - > taskwait ( ' string ' ) ; <nl> + if ( $ res = = " hello world \ n " ) <nl> + { <nl> + $ serv - > send ( $ fd , ' OK ' ) ; <nl> + } <nl> + else <nl> + { <nl> + $ serv - > send ( $ fd , ' ERR ' ) ; <nl> + } <nl> + } <nl> + elseif ( $ data = = ' timeout ' ) <nl> + { <nl> + $ res = $ serv - > taskwait ( ' timeout ' , 0 . 2 ) ; <nl> + if ( $ res = = = false ) <nl> + { <nl> + $ res = $ serv - > taskwait ( ' string ' , 0 . 2 ) ; <nl> + if ( $ res = = = " hello world \ n " ) <nl> + { <nl> + $ serv - > send ( $ fd , ' OK ' ) ; <nl> + return ; <nl> + } <nl> + } <nl> + $ serv - > send ( $ fd , ' ERR ' ) ; <nl> + } <nl> + } ) ; <nl> + <nl> + $ serv - > on ( ' task ' , function ( swoole_server $ serv , $ task_id , $ worker_id , $ data ) <nl> + { <nl> + if ( is_array ( $ data ) ) <nl> + { <nl> + if ( $ data [ ' type ' ] = = ' array ' ) <nl> + { <nl> + return array ( ' name ' = > ' rango ' , ' year ' = > 1987 ) ; <nl> + } <nl> + else <nl> + { <nl> + return " hello world \ n " ; <nl> + } <nl> + } <nl> + else <nl> + { <nl> + if ( $ data = = ' array ' ) <nl> + { <nl> + return array ( ' name ' = > ' rango ' , ' year ' = > 1987 ) ; <nl> + } <nl> + elseif ( $ data = = ' string ' ) <nl> + { <nl> + return " hello world \ n " ; <nl> + } <nl> + elseif ( $ data = = ' timeout ' ) <nl> + { <nl> + usleep ( 300000 ) ; <nl> + return " task timeout \ n " ; <nl> + } <nl> + } <nl> + } ) ; <nl> + <nl> + $ serv - > on ( ' finish ' , function ( swoole_server $ serv , $ fd , $ rid , $ data ) <nl> + { <nl> + <nl> + } ) ; <nl> + $ serv - > start ( ) ; <nl> + } ; <nl> + <nl> + $ pm - > childFirst ( ) ; <nl> + $ pm - > run ( ) ; <nl> + ? > <nl> + - - EXPECT - - <nl> | Merge remote - tracking branch ' origin / master ' | swoole/swoole-src | a75e84a2786686023e584fdedfa4c56e527225e8 | 2018-07-27T11:20:14Z |
mmm a / tools / internal_ci / macos / grpc_run_bazel_isolated_tests . sh <nl> ppp b / tools / internal_ci / macos / grpc_run_bazel_isolated_tests . sh <nl> cd $ ( dirname $ 0 ) / . . / . . / . . <nl> # The " local " execution strategy is required because the test runs sudo and that doesn ' t work in a sandboxed environment ( the default on mac ) <nl> tools / bazel test $ RUN_TESTS_FLAGS - - spawn_strategy = local - - genrule_strategy = local - - test_output = all - - copt = " - DGRPC_CFSTREAM = 1 " / / test / cpp / end2end : cfstream_test <nl> <nl> + # Missing the / var / db / ntp - kod file may breaks the ntp synchronization . <nl> + # Create the file and change the ownership to root before NTP sync . <nl> + # TODO ( yulin - liang ) : investigate how to run time_jump_test without needing to mess with the system time directly . <nl> + # See b / 166245303 <nl> + sudo touch / var / db / ntp - kod <nl> + sudo chown root : wheel / var / db / ntp - kod <nl> # Make sure time is in sync before running time_jump_test because the test does <nl> # NTP sync before exiting . Bazel gets confused if test end time < start time . <nl> sudo sntp - sS pool . ntp . org <nl> | Merge pull request from yulin - liang / flaky - cfstream | grpc/grpc | 749024c2c8dd66239adda533c47417f2fe487089 | 2020-08-31T18:30:55Z |
mmm a / core / func_ref . cpp <nl> ppp b / core / func_ref . cpp <nl> void FuncRef : : _bind_methods ( ) { <nl> mi . arguments . push_back ( PropertyInfo ( Variant : : NIL , " arg " + itos ( i ) ) ) ; <nl> defargs . push_back ( Variant ( ) ) ; <nl> } <nl> - ObjectTypeDB : : bind_native_method ( METHOD_FLAGS_DEFAULT , " call_func " , & FuncRef : : call_func , mi , defargs ) ; <nl> + ObjectTypeDB : : bind_native_method ( METHOD_FLAGS_DEFAULT , " call_func : Variant " , & FuncRef : : call_func , mi , defargs ) ; <nl> <nl> } <nl> <nl> mmm a / doc / base / classes . xml <nl> ppp b / doc / base / classes . xml <nl> <nl> < argument index = " 1 " name = " signal " type = " String " > <nl> < / argument > <nl> < description > <nl> - Stop the function execution and return the current state . Call resume on the state to resume execution . This makes the state invalid . <nl> + Stop the function execution and return the current state . Call [ method GDFunctionState . resume ] on the state to resume execution . This invalidates the state . <nl> Returns anything that was passed to the resume function call . If passed an object and a signal , the execution is resumed when the object ' s signal is emmited . <nl> < / description > <nl> < / method > <nl> <nl> < / class > <nl> < class name = " FuncRef " inherits = " Reference " category = " Core " > <nl> < brief_description > <nl> + Reference to a function in an object . <nl> < / brief_description > <nl> < description > <nl> + In GDScript , functions are not [ i ] first - class objects [ / i ] . This means it is impossible to store them directly as variables , return them from another function , or pass them as arguments . <nl> + However , by creating a [ FuncRef ] using the [ method @ GDScript . funcref ] function , a reference to a function in a given object can be created , passed around and called . <nl> < / description > <nl> < methods > <nl> < method name = " call_func " > <nl> <nl> < argument index = " 9 " name = " arg9 " type = " Variant " default = " NULL " > <nl> < / argument > <nl> < description > <nl> + Call the referenced function with the given arguments . The argument count must correspond to the required number of arguments in the function . Returns the return value of the function call . <nl> < / description > <nl> < / method > <nl> < method name = " set_function " > <nl> < argument index = " 0 " name = " name " type = " String " > <nl> < / argument > <nl> < description > <nl> + Set the name of the function to call on the object , without parentheses or any parameters . <nl> < / description > <nl> < / method > <nl> < method name = " set_instance " > <nl> < argument index = " 0 " name = " instance " type = " Object " > <nl> < / argument > <nl> < description > <nl> + Set the object on which to call the referenced function . This object must be of a type actually inheriting from [ Object ] , not a built - in type such as [ int ] , [ Vector2 ] or [ Dictionary ] . <nl> < / description > <nl> < / method > <nl> < / methods > <nl> <nl> < / class > <nl> < class name = " GDFunctionState " inherits = " Reference " category = " Core " > <nl> < brief_description > <nl> + State of a function call after yielding . <nl> < / brief_description > <nl> < description > <nl> + Calling [ method @ GDScript . yield ] within a function will cause that function to yield and return its current state as an object of this type . The yielded function call can then be resumed later by calling [ method resume ] on this state object . <nl> < / description > <nl> < methods > <nl> < method name = " is_valid " qualifiers = " const " > <nl> < return type = " bool " > <nl> < / return > <nl> < description > <nl> - Should put children to the top left corner instead of center of the container . <nl> + Check whether the function call may be resumed . This is not the case if the function state was already resumed . <nl> < / description > <nl> < / method > <nl> < method name = " resume " > <nl> <nl> < argument index = " 0 " name = " arg " type = " Variant " default = " NULL " > <nl> < / argument > <nl> < description > <nl> + Resume execution of the yielded function call . <nl> + If handed an argument , return the argument from the [ method @ GDScript . yield ] call in the yielded function call . You can pass e . g . an [ Array ] to hand multiple arguments . <nl> + This function returns what the resumed function call returns , possibly another function state if yielded again . <nl> < / description > <nl> < / method > <nl> < / methods > <nl> <nl> < / class > <nl> < class name = " InstancePlaceholder " inherits = " Node " category = " Core " > <nl> < brief_description > <nl> + Placeholder for the root [ Node ] of a [ PackedScene ] . <nl> < / brief_description > <nl> < description > <nl> + Turning on the option [ b ] Load As Placeholder [ / b ] for an instanced scene in the editor causes it to be replaced by an InstacePlaceholder when running the game . This makes it possible to delay actually loading the scene until calling [ method replace_by_instance ] . This is useful to avoid loading large scenes all at once by loading parts of it selectively . <nl> + The InstancePlaceholder does not have a transform . This causes any child nodes to be positioned relatively to the Viewport from point ( 0 , 0 ) , rather than their parent as displayed in the editor . Replacing the placeholder with a scene with a transform will transform children relatively to their parent again . <nl> < / description > <nl> < methods > <nl> < method name = " get_instance_path " qualifiers = " const " > <nl> < return type = " String " > <nl> < / return > <nl> < description > <nl> + Retrieve the path to the [ PackedScene ] resource file that is loaded by default when calling [ method replace_by_instance ] . <nl> < / description > <nl> < / method > <nl> < method name = " replace_by_instance " > <nl> < argument index = " 0 " name = " custom_scene " type = " PackedScene " default = " NULL " > <nl> < / argument > <nl> < description > <nl> + Replace this placeholder by the scene handed as an argument , or the original scene if no argument is given . As for all resources , the scene is loaded only if it ' s not loaded already . By manually loading the scene beforehand , delays caused by this function can be avoided . <nl> < / description > <nl> < / method > <nl> < / methods > <nl> <nl> < / class > <nl> < class name = " RID " category = " Built - In Types " > <nl> < brief_description > <nl> + Handle for a [ Resource ] ' s unique ID . <nl> < / brief_description > <nl> < description > <nl> + The RID type is used to access the unique integer ID of a resource . They are opaque , so they do not grant access to the associated resource by themselves . They are used by and with the low - level Server classes such as [ VisualServer ] . <nl> < / description > <nl> < methods > <nl> < method name = " RID " > <nl> <nl> < argument index = " 0 " name = " from " type = " Object " > <nl> < / argument > <nl> < description > <nl> + Create a new RID instance with the ID of a given resource . When not handed a valid resource , silently stores the unused ID 0 . <nl> < / description > <nl> < / method > <nl> < method name = " get_id " > <nl> < return type = " int " > <nl> < / return > <nl> < description > <nl> + Retrieve the ID of the referenced resource . <nl> < / description > <nl> < / method > <nl> < / methods > <nl> <nl> < return type = " RID " > <nl> < / return > <nl> < description > <nl> + Retrieve the [ RID ] of this world ' s canvas resource . Used by the [ VisualServer ] for 2D drawing . <nl> < / description > <nl> < / method > <nl> < method name = " get_direct_space_state " > <nl> < return type = " Physics2DDirectSpaceState " > <nl> < / return > <nl> < description > <nl> + Retrieve the state of this world ' s physics space . This allows arbitrary querying for collision . <nl> < / description > <nl> < / method > <nl> < method name = " get_sound_space " > <nl> < return type = " RID " > <nl> < / return > <nl> < description > <nl> + Retrieve the [ RID ] of this world ' s sound space resource . Used by the [ SpatialSound2DServer ] for 2D spatial audio . <nl> < / description > <nl> < / method > <nl> < method name = " get_space " > <nl> < return type = " RID " > <nl> < / return > <nl> < description > <nl> + Retrieve the [ RID ] of this world ' s physics space resource . Used by the [ Physics2DServer ] for 2D physics , treating it as both a space and an area . <nl> < / description > <nl> < / method > <nl> < / methods > <nl> mmm a / modules / gdscript / gd_editor . cpp <nl> ppp b / modules / gdscript / gd_editor . cpp <nl> void GDScriptLanguage : : get_public_functions ( List < MethodInfo > * p_functions ) const <nl> } <nl> { <nl> MethodInfo mi ; <nl> - mi . name = " yield " ; <nl> + mi . name = " yield : GDFunctionState " ; <nl> mi . arguments . push_back ( PropertyInfo ( Variant : : OBJECT , " object " ) ) ; <nl> mi . arguments . push_back ( PropertyInfo ( Variant : : STRING , " signal " ) ) ; <nl> mi . default_arguments . push_back ( Variant : : NIL ) ; <nl> | Merge pull request from eska014 / class - doc | godotengine/godot | 2b5198b23dde370563719f57d158f4f342263be2 | 2016-07-30T19:52:18Z |
mmm a / dbms / src / Interpreters / InterpreterCreateQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterCreateQuery . cpp <nl> namespace ErrorCodes <nl> extern const int DUPLICATE_COLUMN ; <nl> extern const int READONLY ; <nl> extern const int ILLEGAL_COLUMN ; <nl> + extern const int QUERY_IS_PROHIBITED ; <nl> } <nl> <nl> <nl> void InterpreterCreateQuery : : checkAccess ( const ASTCreateQuery & create ) <nl> <nl> const Settings & settings = context . getSettingsRef ( ) ; <nl> auto readonly = settings . readonly ; <nl> + auto allow_ddl = settings . allow_ddl ; <nl> <nl> - if ( ! readonly ) <nl> - { <nl> + if ( ! readonly & & allow_ddl ) <nl> return ; <nl> - } <nl> <nl> / / / CREATE | ATTACH DATABASE <nl> if ( ! create . database . empty ( ) & & create . table . empty ( ) ) <nl> { <nl> - throw Exception ( " Cannot create database in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + if ( readonly ) <nl> + throw Exception ( " Cannot create database in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + <nl> + throw Exception ( " Cannot create database . DDL queries are prohibited for the user " , ErrorCodes : : QUERY_IS_PROHIBITED ) ; <nl> } <nl> <nl> if ( create . is_temporary & & readonly > = 2 ) <nl> - { <nl> return ; <nl> - } <nl> <nl> - throw Exception ( " Cannot create table in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + if ( readonly ) <nl> + throw Exception ( " Cannot create table in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + <nl> + throw Exception ( " Cannot create table . DDL queries are prohibited for the user " , ErrorCodes : : QUERY_IS_PROHIBITED ) ; <nl> } <nl> } <nl> mmm a / dbms / src / Interpreters / InterpreterDropQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterDropQuery . cpp <nl> namespace ErrorCodes <nl> extern const int LOGICAL_ERROR ; <nl> extern const int SYNTAX_ERROR ; <nl> extern const int UNKNOWN_TABLE ; <nl> + extern const int QUERY_IS_PROHIBITED ; <nl> } <nl> <nl> <nl> void InterpreterDropQuery : : checkAccess ( const ASTDropQuery & drop ) <nl> { <nl> const Settings & settings = context . getSettingsRef ( ) ; <nl> auto readonly = settings . readonly ; <nl> + bool allow_ddl = settings . allow_ddl ; <nl> <nl> / / / It ' s allowed to drop temporary tables . <nl> - if ( ! readonly | | ( drop . database . empty ( ) & & context . tryGetExternalTable ( drop . table ) & & readonly > = 2 ) ) <nl> - { <nl> + if ( ( ! readonly & & allow_ddl ) | | ( drop . database . empty ( ) & & context . tryGetExternalTable ( drop . table ) & & readonly > = 2 ) ) <nl> return ; <nl> - } <nl> <nl> - throw Exception ( " Cannot drop table in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + if ( readonly ) <nl> + throw Exception ( " Cannot drop table in readonly mode " , ErrorCodes : : READONLY ) ; <nl> + <nl> + throw Exception ( " Cannot drop table . DDL queries are prohibited for the user " , ErrorCodes : : QUERY_IS_PROHIBITED ) ; <nl> } <nl> <nl> } <nl> mmm a / dbms / src / Interpreters / InterpreterFactory . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterFactory . cpp <nl> namespace ErrorCodes <nl> { <nl> extern const int READONLY ; <nl> extern const int UNKNOWN_TYPE_OF_QUERY ; <nl> + extern const int QUERY_IS_PROHIBITED ; <nl> } <nl> <nl> <nl> - static void throwIfReadOnly ( Context & context ) <nl> + static void throwIfNoAccess ( Context & context ) <nl> { <nl> if ( context . getSettingsRef ( ) . readonly ) <nl> { <nl> static void throwIfReadOnly ( Context & context ) <nl> else <nl> throw Exception ( " Cannot execute query in readonly mode " , ErrorCodes : : READONLY ) ; <nl> } <nl> + else if ( ! context . getSettingsRef ( ) . allow_ddl ) <nl> + throw Exception ( " Cannot execute query . DDL queries are prohibited for the user " , ErrorCodes : : QUERY_IS_PROHIBITED ) ; <nl> } <nl> <nl> <nl> std : : unique_ptr < IInterpreter > InterpreterFactory : : get ( ASTPtr & query , Context & <nl> } <nl> else if ( typeid_cast < ASTCreateQuery * > ( query . get ( ) ) ) <nl> { <nl> - / / / readonly is checked inside InterpreterCreateQuery <nl> + / / / readonly and allow_ddl are checked inside InterpreterCreateQuery <nl> return std : : make_unique < InterpreterCreateQuery > ( query , context ) ; <nl> } <nl> else if ( typeid_cast < ASTDropQuery * > ( query . get ( ) ) ) <nl> { <nl> - / / / readonly is checked inside InterpreterDropQuery <nl> + / / / readonly and allow_ddl are checked inside InterpreterDropQuery <nl> return std : : make_unique < InterpreterDropQuery > ( query , context ) ; <nl> } <nl> else if ( typeid_cast < ASTRenameQuery * > ( query . get ( ) ) ) <nl> { <nl> - throwIfReadOnly ( context ) ; <nl> + throwIfNoAccess ( context ) ; <nl> return std : : make_unique < InterpreterRenameQuery > ( query , context ) ; <nl> } <nl> else if ( typeid_cast < ASTShowTablesQuery * > ( query . get ( ) ) ) <nl> std : : unique_ptr < IInterpreter > InterpreterFactory : : get ( ASTPtr & query , Context & <nl> } <nl> else if ( typeid_cast < ASTOptimizeQuery * > ( query . get ( ) ) ) <nl> { <nl> - throwIfReadOnly ( context ) ; <nl> + throwIfNoAccess ( context ) ; <nl> return std : : make_unique < InterpreterOptimizeQuery > ( query , context ) ; <nl> } <nl> else if ( typeid_cast < ASTExistsQuery * > ( query . get ( ) ) ) <nl> std : : unique_ptr < IInterpreter > InterpreterFactory : : get ( ASTPtr & query , Context & <nl> } <nl> else if ( typeid_cast < ASTAlterQuery * > ( query . get ( ) ) ) <nl> { <nl> - throwIfReadOnly ( context ) ; <nl> + throwIfNoAccess ( context ) ; <nl> return std : : make_unique < InterpreterAlterQuery > ( query , context ) ; <nl> } <nl> else if ( typeid_cast < ASTCheckQuery * > ( query . get ( ) ) ) <nl> std : : unique_ptr < IInterpreter > InterpreterFactory : : get ( ASTPtr & query , Context & <nl> } <nl> else if ( typeid_cast < ASTSystemQuery * > ( query . get ( ) ) ) <nl> { <nl> - throwIfReadOnly ( context ) ; <nl> + throwIfNoAccess ( context ) ; <nl> return std : : make_unique < InterpreterSystemQuery > ( query , context ) ; <nl> } <nl> else <nl> mmm a / dbms / src / Interpreters / InterpreterSetQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterSetQuery . cpp <nl> namespace DB <nl> namespace ErrorCodes <nl> { <nl> extern const int READONLY ; <nl> + extern const int QUERY_IS_PROHIBITED ; <nl> } <nl> <nl> <nl> void InterpreterSetQuery : : checkAccess ( const ASTSetQuery & ast ) <nl> <nl> const Settings & settings = context . getSettingsRef ( ) ; <nl> auto readonly = settings . readonly ; <nl> + auto allow_ddl = settings . allow_ddl ; <nl> <nl> for ( const auto & change : ast . changes ) <nl> { <nl> void InterpreterSetQuery : : checkAccess ( const ASTSetQuery & ast ) <nl> / / / Setting isn ' t checked if value wasn ' t changed . <nl> if ( ! settings . tryGet ( change . name , value ) | | applyVisitor ( FieldVisitorToString ( ) , change . value ) ! = value ) <nl> { <nl> + <nl> + if ( ! allow_ddl & & change . name = = " allow_ddl " ) <nl> + throw Exception ( " Cannot modify ' allow_ddl ' setting when DDL queries are not allowed " , ErrorCodes : : QUERY_IS_PROHIBITED ) ; <nl> + <nl> if ( readonly = = 1 ) <nl> throw Exception ( " Cannot execute SET query in readonly mode " , ErrorCodes : : READONLY ) ; <nl> <nl> mmm a / dbms / src / Interpreters / Settings . h <nl> ppp b / dbms / src / Interpreters / Settings . h <nl> struct Settings <nl> M ( SettingBool , asterisk_left_columns_only , 0 , " If it is set to true , the asterisk only return left of join query . " ) \ <nl> M ( SettingUInt64 , http_max_multipart_form_data_size , 1024 * 1024 * 1024 , " Limit on size of multipart / form - data content . This setting cannot be parsed from URL parameters and should be set in user profile . Note that content is parsed and external tables are created in memory before start of query execution . And this is the only limit that has effect on that stage ( limits on max memory usage and max execution time have no effect while reading HTTP form data ) . " ) \ <nl> M ( SettingBool , calculate_text_stack_trace , 1 , " Calculate text stack trace in case of exceptions during query execution . This is the default . It requires symbol lookups that may slow down fuzzing tests when huge amount of wrong queries are executed . In normal cases you should not disable this option . " ) \ <nl> + M ( SettingBool , allow_ddl , true , " If it is set to true , then a user is allowed to executed DDL queries . " ) \ <nl> <nl> <nl> # define DECLARE ( TYPE , NAME , DEFAULT , DESCRIPTION ) \ <nl> new file mode 100644 <nl> index 00000000000 . . e69de29bb2d <nl> new file mode 100755 <nl> index 00000000000 . . 2f66cc96a35 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00716_allow_ddl . sql <nl> <nl> + SET send_logs_level = ' none ' ; <nl> + SET allow_ddl = 0 ; <nl> + <nl> + CREATE DATABASE some_db ; - - { serverError 392 } <nl> + CREATE TABLE test . some_table ( a Int32 ) ENGINE = Memory ; - - { serverError 392 } <nl> + ALTER TABLE test . some_table DELETE WHERE 1 ; - - { serverError 392 } <nl> + RENAME TABLE test . some_table TO test . some_table1 ; - - { serverError 392 } <nl> + SET allow_ddl = 1 ; - - { serverError 392 } <nl> | add setting allow_ddl | ClickHouse/ClickHouse | c1ed0bb86a21bce44018b605ce5ae619876c36c6 | 2018-09-11T18:37:19Z |
mmm a / js / common / modules / graph . js <nl> ppp b / js / common / modules / graph . js <nl> Vertex . prototype . determinePredecessors = function ( source , options ) { <nl> current_vertex = this . _graph . getVertex ( current_vertex_id ) ; <nl> <nl> if ( current_vertex_id = = = this . getId ( ) ) { <nl> - require ( " console " ) . log ( " FOUND YOU ! " ) ; <nl> return_value = predecessors ; <nl> break ; <nl> } else { <nl> Vertex . prototype . outDegree = function ( ) { <nl> / / / <nl> / / / @ FUN { @ FA { vertex } . measurement ( @ FA { measurement } ) } <nl> / / / <nl> - / / / Calculates the eccentricity or closeness of the vertex <nl> + / / / Calculates the eccentricity , betweenness or closeness of the vertex <nl> / / / <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> Vertex . prototype . measurement = function ( measurement ) { <nl> var graph = this . _graph , <nl> source = this , <nl> - vertices , <nl> - value , <nl> - options ; <nl> + value ; <nl> <nl> if ( measurement = = = " betweenness " ) { <nl> - options = { grouped : true , threshold : true } ; <nl> - <nl> - value = graph . geodesics ( options ) . reduce ( function ( count , geodesic_group ) { <nl> + value = graph . geodesics ( { <nl> + grouped : true , <nl> + threshold : true <nl> + } ) . reduce ( function ( count , geodesic_group ) { <nl> var included = geodesic_group . filter ( function ( geodesic ) { <nl> return geodesic . slice ( 1 , - 1 ) . indexOf ( source . getId ( ) ) > - 1 ; <nl> } ) ; <nl> <nl> return ( included ? count + ( included . length / geodesic_group . length ) : count ) ; <nl> } , 0 ) ; <nl> - } else { <nl> - vertices = graph . _vertices . toArray ( ) ; <nl> - <nl> - value = vertices . reduce ( function ( calculated , target ) { <nl> + } else if ( measurement = = = " eccentricity " ) { <nl> + value = graph . _vertices . toArray ( ) . reduce ( function ( calculated , target ) { <nl> var distance = source . distanceTo ( graph . getVertex ( target . _id ) ) ; <nl> - <nl> - switch ( measurement ) { <nl> - case " eccentricity " : <nl> - calculated = Math . max ( calculated , distance ) ; <nl> - break ; <nl> - case " closeness " : <nl> - calculated + = distance ; <nl> - break ; <nl> - default : <nl> - throw " Unknown Measurement ' " + measurement + " ' " ; <nl> - } <nl> - <nl> - return calculated ; <nl> + return Math . max ( calculated , distance ) ; <nl> } , 0 ) ; <nl> + } else if ( measurement = = = " closeness " ) { <nl> + value = graph . _vertices . toArray ( ) . reduce ( function ( calculated , target ) { <nl> + var distance = source . distanceTo ( graph . getVertex ( target . _id ) ) ; <nl> + return calculated + distance ; <nl> + } , 0 ) ; <nl> + } else { <nl> + throw " Unknown Measurement ' " + measurement + " ' " ; <nl> } <nl> <nl> return value ; <nl> new file mode 100644 <nl> index 00000000000 . . 779fab30a2c <nl> mmm / dev / null <nl> ppp b / js / common / test - data / gephi / edges . csv <nl> <nl> + Source , Target <nl> + 1 , 3 <nl> + 10 , 8 <nl> + 11 , 14 <nl> + 12 , 18 <nl> + 13 , 6 <nl> + 14 , 12 <nl> + 15 , 19 <nl> + 16 , 19 <nl> + 17 , 19 <nl> + 18 , 15 <nl> + 2 , 20 <nl> + 20 , 19 <nl> + 3 , 14 <nl> + 4 , 16 <nl> + 5 , 10 <nl> + 6 , 19 <nl> + 7 , 2 <nl> + 8 , 1 <nl> + 9 , 2 <nl> new file mode 100644 <nl> index 00000000000 . . 4b56e000f2c <nl> Binary files / dev / null and b / js / common / test - data / gephi / source . gephi differ <nl> new file mode 100644 <nl> index 00000000000 . . 2a220f9247d <nl> mmm / dev / null <nl> ppp b / js / common / test - data / gephi / vertices . csv <nl> <nl> + Id , Degree , Eccentricity , Closeness Centrality , Betweenness Centrality <nl> + 1 , 2 , 9 . 0 , 5 . 2631578947368425 , 48 . 0 <nl> + 2 , 3 , 11 . 0 , 4 . 842105263157895 , 35 . 0 <nl> + 3 , 2 , 8 . 0 , 4 . 631578947368421 , 60 . 0 <nl> + 4 , 1 , 11 . 0 , 5 . 2631578947368425 , 0 . 0 <nl> + 5 , 1 , 12 . 0 , 7 . 7894736842105265 , 0 . 0 <nl> + 6 , 2 , 10 . 0 , 4 . 315789473684211 , 18 . 0 <nl> + 7 , 1 , 12 . 0 , 5 . 7894736842105265 , 0 . 0 <nl> + 8 , 2 , 10 . 0 , 6 . 0 , 34 . 0 <nl> + 9 , 1 , 12 . 0 , 5 . 7894736842105265 , 0 . 0 <nl> + 10 , 2 , 11 . 0 , 6 . 842105263157895 , 18 . 0 <nl> + 11 , 1 , 8 . 0 , 5 . 052631578947368 , 0 . 0 <nl> + 12 , 2 , 6 . 0 , 3 . 789473684210526 , 84 . 0 <nl> + 13 , 1 , 11 . 0 , 5 . 2631578947368425 , 0 . 0 <nl> + 14 , 3 , 7 . 0 , 4 . 105263157894737 , 83 . 0 <nl> + 15 , 2 , 8 . 0 , 3 . 473684210526316 , 90 . 0 <nl> + 16 , 2 , 10 . 0 , 4 . 315789473684211 , 18 . 0 <nl> + 17 , 1 , 10 . 0 , 4 . 421052631578948 , 0 . 0 <nl> + 18 , 2 , 7 . 0 , 3 . 5789473684210527 , 88 . 0 <nl> + 19 , 5 , 9 . 0 , 3 . 473684210526316 , 118 . 0 <nl> + 20 , 2 , 10 . 0 , 4 . 105263157894737 , 48 . 0 <nl> mmm a / js / common / test - data / gephi50 / edges . csv <nl> ppp b / js / common / test - data / gephi50 / edges . csv <nl> <nl> - Id , Source , Target <nl> - 1 , 1 , 26 <nl> - 2 , 3 , 17 <nl> - 3 , 3 , 39 <nl> - 4 , 4 , 8 <nl> - 5 , 4 , 17 <nl> - 6 , 4 , 43 <nl> - 7 , 4 , 44 <nl> - 8 , 5 , 17 <nl> - 9 , 5 , 27 <nl> - 10 , 6 , 38 <nl> - 11 , 7 , 50 <nl> - 12 , 8 , 32 <nl> - 13 , 8 , 35 <nl> - 14 , 8 , 48 <nl> - 15 , 9 , 42 <nl> - 16 , 10 , 19 <nl> - 17 , 10 , 20 <nl> - 18 , 10 , 39 <nl> - 19 , 10 , 50 <nl> - 20 , 11 , 16 <nl> - 21 , 12 , 24 <nl> - 22 , 12 , 28 <nl> - 23 , 12 , 37 <nl> - 24 , 14 , 24 <nl> - 25 , 14 , 26 <nl> - 26 , 14 , 36 <nl> - 27 , 14 , 48 <nl> - 28 , 15 , 21 <nl> - 29 , 15 , 38 <nl> - 30 , 15 , 50 <nl> - 31 , 16 , 37 <nl> - 32 , 16 , 49 <nl> - 33 , 17 , 30 <nl> - 34 , 17 , 40 <nl> - 35 , 17 , 47 <nl> - 36 , 18 , 28 <nl> - 37 , 19 , 37 <nl> - 38 , 20 , 38 <nl> - 39 , 20 , 42 <nl> - 40 , 20 , 45 <nl> - 41 , 21 , 26 <nl> - 42 , 21 , 48 <nl> - 43 , 22 , 31 <nl> - 44 , 23 , 37 <nl> - 45 , 23 , 40 <nl> - 46 , 24 , 27 <nl> - 47 , 24 , 46 <nl> - 48 , 25 , 29 <nl> - 49 , 26 , 31 <nl> - 50 , 27 , 50 <nl> - 51 , 28 , 45 <nl> - 52 , 28 , 48 <nl> - 53 , 29 , 36 <nl> - 54 , 29 , 49 <nl> - 55 , 30 , 46 <nl> - 56 , 32 , 44 <nl> - 57 , 33 , 43 <nl> - 58 , 34 , 49 <nl> - 59 , 37 , 47 <nl> - 60 , 38 , 45 <nl> - 61 , 40 , 50 <nl> - 62 , 42 , 47 <nl> + Id , Source , Target , Type <nl> + 1 , 1 , 26 , Undirected <nl> + 2 , 3 , 17 , Undirected <nl> + 3 , 3 , 39 , Undirected <nl> + 4 , 4 , 8 , Undirected <nl> + 5 , 4 , 17 , Undirected <nl> + 6 , 4 , 43 , Undirected <nl> + 7 , 4 , 44 , Undirected <nl> + 8 , 5 , 17 , Undirected <nl> + 9 , 5 , 27 , Undirected <nl> + 10 , 6 , 38 , Undirected <nl> + 11 , 7 , 50 , Undirected <nl> + 12 , 8 , 32 , Undirected <nl> + 13 , 8 , 35 , Undirected <nl> + 14 , 8 , 48 , Undirected <nl> + 15 , 9 , 42 , Undirected <nl> + 16 , 10 , 19 , Undirected <nl> + 17 , 10 , 20 , Undirected <nl> + 18 , 10 , 39 , Undirected <nl> + 19 , 10 , 50 , Undirected <nl> + 20 , 11 , 16 , Undirected <nl> + 21 , 12 , 24 , Undirected <nl> + 22 , 12 , 28 , Undirected <nl> + 23 , 12 , 37 , Undirected <nl> + 24 , 14 , 24 , Undirected <nl> + 25 , 14 , 26 , Undirected <nl> + 26 , 14 , 36 , Undirected <nl> + 27 , 14 , 48 , Undirected <nl> + 28 , 15 , 21 , Undirected <nl> + 29 , 15 , 38 , Undirected <nl> + 30 , 15 , 50 , Undirected <nl> + 31 , 16 , 37 , Undirected <nl> + 32 , 16 , 49 , Undirected <nl> + 33 , 17 , 30 , Undirected <nl> + 34 , 17 , 40 , Undirected <nl> + 35 , 17 , 47 , Undirected <nl> + 36 , 18 , 28 , Undirected <nl> + 37 , 19 , 37 , Undirected <nl> + 38 , 20 , 38 , Undirected <nl> + 39 , 20 , 42 , Undirected <nl> + 40 , 20 , 45 , Undirected <nl> + 41 , 21 , 26 , Undirected <nl> + 42 , 21 , 48 , Undirected <nl> + 43 , 22 , 31 , Undirected <nl> + 44 , 23 , 37 , Undirected <nl> + 45 , 23 , 40 , Undirected <nl> + 46 , 24 , 27 , Undirected <nl> + 47 , 24 , 46 , Undirected <nl> + 48 , 25 , 29 , Undirected <nl> + 49 , 26 , 31 , Undirected <nl> + 50 , 27 , 50 , Undirected <nl> + 51 , 28 , 45 , Undirected <nl> + 52 , 28 , 48 , Undirected <nl> + 53 , 29 , 36 , Undirected <nl> + 54 , 29 , 49 , Undirected <nl> + 55 , 30 , 46 , Undirected <nl> + 56 , 32 , 44 , Undirected <nl> + 57 , 33 , 43 , Undirected <nl> + 58 , 34 , 49 , Undirected <nl> + 59 , 37 , 47 , Undirected <nl> + 60 , 38 , 45 , Undirected <nl> + 61 , 40 , 50 , Undirected <nl> + 62 , 42 , 47 , Undirected <nl> Binary files a / js / common / test - data / gephi50 / source . gephi and b / js / common / test - data / gephi50 / source . gephi differ <nl> mmm a / js / common / tests / execute - shortest - path . js <nl> ppp b / js / common / tests / execute - shortest - path . js <nl> function main ( args ) { <nl> <nl> console . log ( " Starting Tests " ) ; <nl> <nl> - start_time = new Date ( ) ; <nl> - Helper . process ( base_path + " generated_testcases . csv " , function ( row ) { <nl> + iterator = function ( row ) { <nl> v1 = graph . getVertex ( row [ 0 ] ) ; <nl> v2 = graph . getVertex ( row [ 1 ] ) ; <nl> <nl> function main ( args ) { <nl> pathes = v1 . pathTo ( v2 , { cached : caching } ) ; <nl> } <nl> } <nl> - } ) ; <nl> + } <nl> + start_time = new Date ( ) ; <nl> + Helper . process ( base_path + " generated_testcases . csv " , iterator ) ; <nl> end_time = new Date ( ) ; <nl> console . log ( ( end_time - start_time ) + " ms " ) ; <nl> <nl> new file mode 100644 <nl> index 00000000000 . . 87d00d41c23 <nl> mmm / dev / null <nl> ppp b / js / common / tests / infinite - shortest - path . js <nl> <nl> + / * jslint indent : 2 , <nl> + nomen : true , <nl> + maxlen : 80 , <nl> + sloppy : true * / <nl> + / * global require , <nl> + db , <nl> + assertEqual , assertTrue , <nl> + print , <nl> + PRINT_OBJECT , <nl> + console , <nl> + AvocadoCollection , AvocadoEdgesCollection , <nl> + processCsvFile * / <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief test the graph class <nl> + / / / <nl> + / / / @ file <nl> + / / / <nl> + / / / DISCLAIMER <nl> + / / / <nl> + / / / Copyright 2010 - 2012 triagens GmbH , Cologne , Germany <nl> + / / / <nl> + / / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / / you may not use this file except in compliance with the License . <nl> + / / / You may obtain a copy of the License at <nl> + / / / <nl> + / / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / / <nl> + / / / Unless required by applicable law or agreed to in writing , software <nl> + / / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / / See the License for the specific language governing permissions and <nl> + / / / limitations under the License . <nl> + / / / <nl> + / / / Copyright holder is triAGENS GmbH , Cologne , Germany <nl> + / / / <nl> + / / / @ author Lucas Dohmen <nl> + / / / @ author Copyright 2012 , triAGENS GmbH , Cologne , Germany <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + function main ( args ) { <nl> + var Graph = require ( " graph " ) . Graph , <nl> + graph_name = " UnitTestsCollectionGraph " , <nl> + vertex = " UnitTestsCollectionVertex " , <nl> + edge = " UnitTestsCollectionEdge " , <nl> + graph = null , <nl> + base_path = args [ 1 ] + " / " , <nl> + v1 , <nl> + v2 , <nl> + e , <nl> + pathes , <nl> + results = [ ] , <nl> + neo4j_results = [ ] , <nl> + single_result = { } , <nl> + console = require ( " console " ) , <nl> + Helper = require ( " test - helper " ) . Helper , <nl> + counter , <nl> + i , <nl> + caching = false ; <nl> + <nl> + if ( args [ 2 ] = = = " true " ) { <nl> + caching = true ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / set up <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + try { <nl> + try { <nl> + / / Drop the graph if it exsits <nl> + graph = new Graph ( graph_name ) ; <nl> + print ( " FOUND : " ) ; <nl> + PRINT_OBJECT ( graph ) ; <nl> + graph . drop ( ) ; <nl> + } catch ( err1 ) { <nl> + } <nl> + <nl> + graph = new Graph ( graph_name , vertex , edge ) ; <nl> + } catch ( err2 ) { <nl> + console . error ( " [ FAILED ] setup failed : " + err2 ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / compare with Neo4j on a given network <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + console . log ( " Importing " ) ; <nl> + <nl> + Helper . process ( base_path + " generated_edges . csv " , function ( row ) { <nl> + v1 = graph . getOrAddVertex ( row [ 1 ] ) ; <nl> + v2 = graph . getOrAddVertex ( row [ 2 ] ) ; <nl> + e = graph . addEdge ( v1 , v2 ) ; <nl> + } ) ; <nl> + <nl> + console . log ( " Starting Tests " ) ; <nl> + <nl> + processor = function ( row ) { <nl> + v1 = graph . getVertex ( row [ 0 ] ) ; <nl> + v2 = graph . getVertex ( row [ 1 ] ) ; <nl> + <nl> + if ( v1 ! = = null & & v2 ! = = null ) { <nl> + pathes = v1 . pathTo ( v2 , { cached : caching } ) ; <nl> + } <nl> + } ; <nl> + <nl> + while ( true ) { <nl> + Helper . process ( base_path + " generated_testcases . csv " , processor ) ; <nl> + console . log ( " Round Finished " ) ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / tear down <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + try { <nl> + if ( graph ! = = null ) { <nl> + graph . drop ( ) ; <nl> + } <nl> + } catch ( err ) { <nl> + console . error ( " [ FAILED ] tear - down failed : " + err ) ; <nl> + } <nl> + } <nl> mmm a / js / common / tests / shell - graph - measurement . js <nl> ppp b / js / common / tests / shell - graph - measurement . js <nl> function normalizedSuite ( ) { <nl> <nl> eccentricity = graph . normalizedMeasurement ( " eccentricity " ) ; <nl> <nl> - assertEqual ( eccentricity [ v1 . getId ( ) ] . toPrecision ( 1 ) , ' 0 . 67 ' ) ; <nl> + assertEqual ( eccentricity [ v1 . getId ( ) ] . toPrecision ( 1 ) , ' 0 . 7 ' ) ; <nl> assertEqual ( eccentricity [ v2 . getId ( ) ] . toPrecision ( 1 ) , ' 1 ' ) ; <nl> assertEqual ( eccentricity [ v3 . getId ( ) ] . toPrecision ( 1 ) , ' 1 ' ) ; <nl> assertEqual ( eccentricity [ v4 . getId ( ) ] . toPrecision ( 1 ) , ' 1 ' ) ; <nl> - assertEqual ( eccentricity [ v5 . getId ( ) ] . toPrecision ( 1 ) , ' 0 . 67 ' ) ; <nl> + assertEqual ( eccentricity [ v5 . getId ( ) ] . toPrecision ( 1 ) , ' 0 . 7 ' ) ; <nl> } <nl> } ; <nl> } <nl> similarity index 86 % <nl> rename from js / common / tests / shell - slow - tests . js <nl> rename to js / common / tests / shell - integration - tests . js <nl> mmm a / js / common / tests / shell - slow - tests . js <nl> ppp b / js / common / tests / shell - integration - tests . js <nl> function dijkstraSuite ( ) { <nl> / / / @ brief test suite : Measurements ( Comparison with Gephi ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - function measurementSuite ( ) { <nl> + function centralitySuite ( ) { <nl> var Graph = require ( " graph " ) . Graph , <nl> graph_name = " UnitTestsCollectionGraph " , <nl> vertex = " UnitTestsCollectionVertex " , <nl> function measurementSuite ( ) { <nl> } , <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief compare with Gephi on a network of 50 <nl> + / / / @ brief compare with Gephi on a generated network <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - testComparisonWithGephi50 : function ( ) { <nl> - var base_path = " js / common / test - data / gephi50 / " , <nl> - console = require ( " console " ) ; <nl> + testComparisonWithGephi : function ( ) { <nl> + var base_path = " js / common / test - data / gephi / " , <nl> + console = require ( " console " ) , <nl> + number_of_edges = 0 ; <nl> <nl> Helper . process ( base_path + " vertices . csv " , function ( row ) { <nl> var vertex = graph . addVertex ( row [ 0 ] , { <nl> - in_degree : row [ 1 ] , <nl> - out_degree : row [ 2 ] , <nl> - degree : row [ 3 ] , <nl> - eccentricity : row [ 4 ] , <nl> - closeness : row [ 5 ] , <nl> - betweenness : row [ 6 ] <nl> + degree : row [ 1 ] , <nl> + eccentricity : row [ 2 ] , <nl> + closeness : row [ 3 ] , <nl> + betweenness : row [ 4 ] <nl> } ) ; <nl> } ) ; <nl> <nl> Helper . process ( base_path + " edges . csv " , function ( row ) { <nl> - v1 = graph . getVertex ( row [ 1 ] ) ; <nl> - v2 = graph . getVertex ( row [ 2 ] ) ; <nl> - e = graph . addEdge ( v1 , v2 , row [ 0 ] ) ; <nl> + v1 = graph . getVertex ( row [ 0 ] ) ; <nl> + v2 = graph . getVertex ( row [ 1 ] ) ; <nl> + e = graph . addEdge ( v1 , v2 ) ; <nl> + number_of_edges + = 1 ; <nl> } ) ; <nl> <nl> - assertEqual ( graph . order ( ) , 50 ) ; <nl> - assertEqual ( graph . size ( ) , 62 ) ; <nl> - <nl> graph . _vertices . toArray ( ) . forEach ( function ( raw_vertex ) { <nl> var vertex = graph . getVertex ( raw_vertex . _id ) ; <nl> <nl> assertEqual ( vertex . getProperty ( " degree " ) , vertex . degree ( ) ) ; <nl> - assertEqual ( vertex . getProperty ( " in_degree " ) , vertex . inDegree ( ) ) ; <nl> - assertEqual ( vertex . getProperty ( " out_degree " ) , vertex . outDegree ( ) ) ; <nl> - / / assertEqual ( parseFloat ( vertex . getProperty ( " eccentricity " ) ) . toPrecision ( 21 ) , <nl> - / / vertex . measurement ( " eccentricity " ) . toPrecision ( 21 ) ) ; <nl> - / / console . log ( vertex . getProperty ( " closeness " ) ) ; <nl> - console . log ( " Reference : " + vertex . getProperty ( " closeness " ) ) ; <nl> - console . log ( " Implementation : " + vertex . measurement ( " closeness " ) ) ; <nl> + assertEqual ( parseFloat ( vertex . getProperty ( " eccentricity " ) ) , <nl> + vertex . measurement ( " eccentricity " ) ) ; <nl> + assertEqual ( parseFloat ( vertex . getProperty ( " betweenness " ) ) , <nl> + vertex . measurement ( " betweenness " ) ) ; <nl> + assertEqual ( parseFloat ( vertex . getProperty ( " closeness " ) ) , <nl> + vertex . measurement ( " closeness " ) / number_of_edges ) ; <nl> } ) ; <nl> - <nl> - graph . normalizedMeasurement ( ) <nl> - <nl> } <nl> } ; <nl> } <nl> function measurementSuite ( ) { <nl> / / / @ brief executes the test suites <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - / / jsunity . run ( dijkstraSuite ) ; <nl> - jsunity . run ( measurementSuite ) ; <nl> + jsunity . run ( dijkstraSuite ) ; <nl> + jsunity . run ( centralitySuite ) ; <nl> <nl> return jsunity . done ( ) ; <nl> deleted file mode 100644 <nl> index bd770767136 . . 00000000000 <nl> mmm a / js / common / tests / shell - slow - tests - cached . js <nl> ppp / dev / null <nl> <nl> - / * jslint indent : 2 , <nl> - nomen : true , <nl> - maxlen : 80 , <nl> - sloppy : true * / <nl> - / * global require , <nl> - db , <nl> - assertEqual , assertTrue , <nl> - print , <nl> - PRINT_OBJECT , <nl> - console , <nl> - AvocadoCollection , AvocadoEdgesCollection , <nl> - processCsvFile * / <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief test the graph class <nl> - / / / <nl> - / / / @ file <nl> - / / / <nl> - / / / DISCLAIMER <nl> - / / / <nl> - / / / Copyright 2010 - 2012 triagens GmbH , Cologne , Germany <nl> - / / / <nl> - / / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - / / / you may not use this file except in compliance with the License . <nl> - / / / You may obtain a copy of the License at <nl> - / / / <nl> - / / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - / / / <nl> - / / / Unless required by applicable law or agreed to in writing , software <nl> - / / / distributed under the License is distributed on an " AS IS " BASIS , <nl> - / / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - / / / See the License for the specific language governing permissions and <nl> - / / / limitations under the License . <nl> - / / / <nl> - / / / Copyright holder is triAGENS GmbH , Cologne , Germany <nl> - / / / <nl> - / / / @ author Dr . Frank Celler , Lucas Dohmen <nl> - / / / @ author Copyright 2012 , triAGENS GmbH , Cologne , Germany <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - var jsunity = require ( " jsunity " ) , <nl> - Helper = require ( " test - helper " ) . Helper ; <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - / / - - SECTION - - collection methods <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief test suite : Dijkstra <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - function cachedDijkstraSuite ( ) { <nl> - var Graph = require ( " graph " ) . Graph , <nl> - graph_name = " UnitTestsCollectionGraph " , <nl> - vertex = " UnitTestsCollectionVertex " , <nl> - edge = " UnitTestsCollectionEdge " , <nl> - graph = null ; <nl> - <nl> - return { <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief set up <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - setUp : function ( ) { <nl> - try { <nl> - try { <nl> - / / Drop the graph if it exsits <nl> - graph = new Graph ( graph_name ) ; <nl> - print ( " FOUND : " ) ; <nl> - PRINT_OBJECT ( graph ) ; <nl> - graph . drop ( ) ; <nl> - } catch ( err1 ) { <nl> - } <nl> - <nl> - graph = new Graph ( graph_name , vertex , edge ) ; <nl> - } catch ( err2 ) { <nl> - console . error ( " [ FAILED ] setup failed : " + err2 ) ; <nl> - } <nl> - } , <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief tear down <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - tearDown : function ( ) { <nl> - try { <nl> - if ( graph ! = = null ) { <nl> - graph . drop ( ) ; <nl> - } <nl> - } catch ( err ) { <nl> - console . error ( " [ FAILED ] tear - down failed : " + err ) ; <nl> - } <nl> - } , <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief compare with Neo4j on a network of size 500 <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - testComparisonWithNeo4j500 : function ( ) { <nl> - var base_path = " js / common / test - data / random500 / " , <nl> - v1 , <nl> - v2 , <nl> - e , <nl> - pathes , <nl> - results = [ ] , <nl> - neo4j_results = [ ] , <nl> - single_result = { } , <nl> - counter ; <nl> - <nl> - Helper . process ( base_path + " generated_edges . csv " , function ( row ) { <nl> - v1 = graph . getOrAddVertex ( row [ 1 ] ) ; <nl> - v2 = graph . getOrAddVertex ( row [ 2 ] ) ; <nl> - e = graph . addEdge ( v1 , v2 ) ; <nl> - } ) ; <nl> - <nl> - Helper . process ( base_path + " generated_testcases . csv " , function ( row ) { <nl> - v1 = graph . getVertex ( row [ 0 ] ) ; <nl> - v2 = graph . getVertex ( row [ 1 ] ) ; <nl> - if ( v1 ! = = null & & v2 ! = = null ) { <nl> - pathes = v1 . pathTo ( v2 , { cached : true } ) ; <nl> - single_result = { <nl> - ' from ' : v1 . getId ( ) , <nl> - ' to ' : v2 . getId ( ) , <nl> - ' path_length ' : pathes [ 0 ] . length , <nl> - ' number_of_pathes ' : pathes . length <nl> - } ; <nl> - results . push ( single_result ) ; <nl> - } <nl> - } ) ; <nl> - <nl> - require ( ' console ' ) . log ( " Second Run ( should be cached ) : " ) ; <nl> - <nl> - Helper . process ( base_path + " generated_testcases . csv " , function ( row ) { <nl> - v1 = graph . getVertex ( row [ 0 ] ) ; <nl> - v2 = graph . getVertex ( row [ 1 ] ) ; <nl> - if ( v1 ! = = null & & v2 ! = = null ) { <nl> - pathes = v1 . pathTo ( v2 , { cached : true } ) ; <nl> - single_result = { <nl> - ' from ' : v1 . getId ( ) , <nl> - ' to ' : v2 . getId ( ) , <nl> - ' path_length ' : pathes [ 0 ] . length , <nl> - ' number_of_pathes ' : pathes . length <nl> - } ; <nl> - results . push ( single_result ) ; <nl> - } <nl> - } ) ; <nl> - <nl> - v1 = " " ; <nl> - v2 = " " ; <nl> - Helper . process ( base_path + " neo4j - dijkstra . csv " , function ( row ) { <nl> - counter + = 1 ; <nl> - if ( ! ( v1 = = = row [ 0 ] & & v2 = = = row [ row . length - 1 ] ) ) { <nl> - v1 = row [ 0 ] ; <nl> - v2 = row [ row . length - 1 ] ; <nl> - <nl> - single_result = { <nl> - ' from ' : v1 , <nl> - ' to ' : v2 , <nl> - ' path_length ' : row . length <nl> - } ; <nl> - if ( neo4j_results . length > 0 ) { <nl> - neo4j_results [ neo4j_results . length - 1 ] . number_of_pathes = counter ; <nl> - } <nl> - counter = 0 ; <nl> - neo4j_results . push ( single_result ) ; <nl> - } <nl> - } ) ; <nl> - neo4j_results [ 0 ] . number_of_pathes + = 1 ; <nl> - neo4j_results [ neo4j_results . length - 1 ] . number_of_pathes = counter + 1 ; <nl> - <nl> - for ( counter = 0 ; counter < neo4j_results . length ; counter + = 1 ) { <nl> - assertEqual ( results [ counter ] . from , <nl> - neo4j_results [ counter ] . from ) ; <nl> - <nl> - assertEqual ( results [ counter ] . to , <nl> - neo4j_results [ counter ] . to ) ; <nl> - <nl> - assertEqual ( results [ counter ] . path_length , <nl> - neo4j_results [ counter ] . path_length ) ; <nl> - <nl> - assertEqual ( results [ counter ] . number_of_pathes , <nl> - neo4j_results [ counter ] . number_of_pathes ) ; <nl> - } <nl> - } <nl> - } ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief executes the test suites <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - jsunity . run ( cachedDijkstraSuite ) ; <nl> - return jsunity . done ( ) ; <nl> | Some minor fixes . | arangodb/arangodb | 5fa6eb84783dc4406eda24ee10699f576369045c | 2012-08-14T22:51:14Z |
mmm a / toolsrc / src / commands_available_commands . cpp <nl> ppp b / toolsrc / src / commands_available_commands . cpp <nl> namespace vcpkg : : Commands <nl> const std : : vector < PackageNameAndFunction < CommandTypeA > > & get_available_commands_type_a ( ) <nl> { <nl> static std : : vector < PackageNameAndFunction < CommandTypeA > > t = { <nl> - { " install " , & Install : : perform_and_exit } , <nl> + { " install " , & Install : : perform_and_exit } , <nl> { " ci " , & CI : : perform_and_exit } , <nl> - { " remove " , & Remove : : perform_and_exit } , <nl> - { " build " , & Build : : perform_and_exit } , <nl> - { " env " , & Env : : perform_and_exit } , <nl> - { " build - external " , & BuildExternal : : perform_and_exit } <nl> + { " remove " , & Remove : : perform_and_exit } , <nl> + { " build " , & Build : : perform_and_exit } , <nl> + { " env " , & Env : : perform_and_exit } , <nl> + { " build - external " , & BuildExternal : : perform_and_exit } <nl> } ; <nl> return t ; <nl> } <nl> namespace vcpkg : : Commands <nl> const std : : vector < PackageNameAndFunction < CommandTypeB > > & get_available_commands_type_b ( ) <nl> { <nl> static std : : vector < PackageNameAndFunction < CommandTypeB > > t = { <nl> - { " / ? " , & Help : : perform_and_exit } , <nl> - { " help " , & Help : : perform_and_exit } , <nl> - { " search " , & Search : : perform_and_exit } , <nl> - { " list " , & List : : perform_and_exit } , <nl> - { " integrate " , & Integrate : : perform_and_exit } , <nl> - { " owns " , & Owns : : perform_and_exit } , <nl> - { " update " , & Update : : perform_and_exit } , <nl> - { " depend - info " , & DependInfo : : perform_and_exit } , <nl> - { " edit " , & Edit : : perform_and_exit } , <nl> - { " create " , & Create : : perform_and_exit } , <nl> - { " import " , & Import : : perform_and_exit } , <nl> - { " cache " , & Cache : : perform_and_exit } , <nl> - { " portsdiff " , & PortsDiff : : perform_and_exit } <nl> + { " / ? " , & Help : : perform_and_exit } , <nl> + { " help " , & Help : : perform_and_exit } , <nl> + { " search " , & Search : : perform_and_exit } , <nl> + { " list " , & List : : perform_and_exit } , <nl> + { " integrate " , & Integrate : : perform_and_exit } , <nl> + { " owns " , & Owns : : perform_and_exit } , <nl> + { " update " , & Update : : perform_and_exit } , <nl> + { " depend - info " , & DependInfo : : perform_and_exit } , <nl> + { " edit " , & Edit : : perform_and_exit } , <nl> + { " create " , & Create : : perform_and_exit } , <nl> + { " import " , & Import : : perform_and_exit } , <nl> + { " cache " , & Cache : : perform_and_exit } , <nl> + { " portsdiff " , & PortsDiff : : perform_and_exit } <nl> } ; <nl> return t ; <nl> } <nl> namespace vcpkg : : Commands <nl> const std : : vector < PackageNameAndFunction < CommandTypeC > > & get_available_commands_type_c ( ) <nl> { <nl> static std : : vector < PackageNameAndFunction < CommandTypeC > > t = { <nl> - { " version " , & Version : : perform_and_exit } , <nl> - { " contact " , & Contact : : perform_and_exit } , <nl> - { " hash " , & Hash : : perform_and_exit } , <nl> + { " version " , & Version : : perform_and_exit } , <nl> + { " contact " , & Contact : : perform_and_exit } , <nl> + { " hash " , & Hash : : perform_and_exit } , <nl> } ; <nl> return t ; <nl> } <nl> | Formatting | microsoft/vcpkg | f306e8770fac464db20e536eb847d90a2c85d8c0 | 2017-04-10T19:58:19Z |
mmm a / src / mongo / util / concurrency / qlock . h <nl> ppp b / src / mongo / util / concurrency / qlock . h <nl> namespace mongo { <nl> boost : : mutex m ; <nl> Z r , w , R , W ; <nl> int greed ; / / > 0 if someone wants to acquire a write lock <nl> - int greedyWrites ; <nl> - int stopped ; / / greed stopped ? <nl> + int greedyWrites ; / / 0 = no , 1 = true <nl> + int greedSuspended ; <nl> void _stop_greed ( ) ; / / we are already inlock for these underscore methods <nl> void _lock_W ( ) ; <nl> public : <nl> - QLock ( ) : greedyWrites ( 1 ) , greed ( 0 ) , stopped ( 0 ) { } <nl> + QLock ( ) : greedyWrites ( 1 ) , greed ( 0 ) , greedSuspended ( 0 ) { } <nl> void lock_r ( ) ; <nl> void lock_w ( ) ; <nl> void lock_R ( ) ; <nl> namespace mongo { <nl> } ; <nl> <nl> inline void QLock : : _stop_greed ( ) { <nl> - if ( + + stopped = = 1 ) / / recursion on stop_greed / start_greed is ok <nl> + if ( + + greedSuspended = = 1 ) / / recursion on stop_greed / start_greed is ok <nl> greedyWrites = 0 ; <nl> } <nl> inline void QLock : : stop_greed ( ) { <nl> namespace mongo { <nl> <nl> inline void QLock : : start_greed ( ) { <nl> boost : : mutex : : scoped_lock lk ( m ) ; <nl> - if ( - - stopped = = 0 ) <nl> + if ( - - greedSuspended = = 0 ) <nl> greedyWrites = 1 ; <nl> } <nl> <nl> | SERVER - 4328 better variable name | mongodb/mongo | 2ca325c8818c2cb8c86889cf59264bdff7f3dd59 | 2012-02-29T18:07:02Z |
mmm a / src / x64 / codegen - x64 . cc <nl> ppp b / src / x64 / codegen - x64 . cc <nl> void CodeGenerator : : LoadReference ( Reference * ref ) { <nl> } else { <nl> / / Anything else is a runtime error . <nl> Load ( e ) ; <nl> - / / frame_ - > CallRuntime ( Runtime : : kThrowReferenceError , 1 ) ; <nl> + frame_ - > CallRuntime ( Runtime : : kThrowReferenceError , 1 ) ; <nl> } <nl> <nl> in_spilled_code_ = was_in_spilled_code ; <nl> mmm a / test / mjsunit / mjsunit . status <nl> ppp b / test / mjsunit / mjsunit . status <nl> debug - ignore - breakpoints : CRASH | | FAIL <nl> debug - setbreakpoint : CRASH | | FAIL <nl> debug - step - stub - callfunction : CRASH | | FAIL <nl> debug - step : CRASH | | FAIL <nl> - invalid - lhs : PASS | | CRASH | | FAIL <nl> debug - stepin - constructor : CRASH | | FAIL <nl> debug - stepin - function - call : CRASH | | FAIL <nl> debug - stepin - accessor : CRASH | | FAIL <nl> | X64 : Fix bug that showed up in mjsunit / invalid - lhs . js | v8/v8 | 1ed7462166f86916fdb1f685291e551c862595d1 | 2009-07-28T14:11:09Z |
mmm a / atom / browser / api / trackable_object . h <nl> ppp b / atom / browser / api / trackable_object . h <nl> <nl> <nl> # include " atom / browser / api / event_emitter . h " <nl> # include " atom / common / id_weak_map . h " <nl> + # include " base / memory / scoped_ptr . h " <nl> <nl> namespace base { <nl> class SupportsUserData ; <nl> class TrackableObject : public TrackableObjectBase { <nl> public : <nl> / / Finds out the TrackableObject from its ID in weak map . <nl> static T * FromWeakMapID ( v8 : : Isolate * isolate , int32_t id ) { <nl> - v8 : : MaybeLocal < v8 : : Object > object = weak_map_ . Get ( isolate , id ) ; <nl> + if ( ! weak_map_ ) <nl> + return nullptr ; <nl> + <nl> + v8 : : MaybeLocal < v8 : : Object > object = weak_map_ - > Get ( isolate , id ) ; <nl> if ( object . IsEmpty ( ) ) <nl> return nullptr ; <nl> <nl> class TrackableObject : public TrackableObjectBase { <nl> <nl> / / Returns all objects in this class ' s weak map . <nl> static std : : vector < v8 : : Local < v8 : : Object > > GetAll ( v8 : : Isolate * isolate ) { <nl> - return weak_map_ . Values ( isolate ) ; <nl> + if ( weak_map_ ) <nl> + return weak_map_ - > Values ( isolate ) ; <nl> + else <nl> + return std : : vector < v8 : : Local < v8 : : Object > > ( ) ; <nl> } <nl> <nl> TrackableObject ( ) { <nl> class TrackableObject : public TrackableObjectBase { <nl> <nl> / / Removes this instance from the weak map . <nl> void RemoveFromWeakMap ( ) { <nl> - if ( weak_map_ . Has ( weak_map_id ( ) ) ) <nl> - weak_map_ . Remove ( weak_map_id ( ) ) ; <nl> + if ( weak_map_ & & weak_map_ - > Has ( weak_map_id ( ) ) ) <nl> + weak_map_ - > Remove ( weak_map_id ( ) ) ; <nl> } <nl> <nl> protected : <nl> class TrackableObject : public TrackableObjectBase { <nl> } <nl> <nl> void AfterInit ( v8 : : Isolate * isolate ) override { <nl> - weak_map_id_ = weak_map_ . Add ( isolate , GetWrapper ( isolate ) ) ; <nl> + if ( ! weak_map_ ) <nl> + weak_map_ . reset ( new atom : : IDWeakMap ) ; <nl> + weak_map_id_ = weak_map_ - > Add ( isolate , GetWrapper ( isolate ) ) ; <nl> TrackableObjectBase : : AfterInit ( isolate ) ; <nl> } <nl> <nl> private : <nl> / / Releases all weak references in weak map , called when app is terminating . <nl> static void ReleaseAllWeakReferences ( ) { <nl> - weak_map_ . Clear ( ) ; <nl> + weak_map_ . reset ( ) ; <nl> } <nl> <nl> - static atom : : IDWeakMap weak_map_ ; <nl> + static scoped_ptr < atom : : IDWeakMap > weak_map_ ; <nl> <nl> DISALLOW_COPY_AND_ASSIGN ( TrackableObject ) ; <nl> } ; <nl> <nl> template < typename T > <nl> - atom : : IDWeakMap TrackableObject < T > : : weak_map_ ; <nl> + scoped_ptr < atom : : IDWeakMap > TrackableObject < T > : : weak_map_ ; <nl> <nl> } / / namespace mate <nl> <nl> | Merge pull request from atom / no - heap - stl | electron/electron | 6c5dde60a355af8b84fd82e888e05c69938aa540 | 2015-07-14T09:48:05Z |
mmm a / imgui_widgets . cpp <nl> ppp b / imgui_widgets . cpp <nl> bool ImGui : : InputTextEx ( const char * label , const char * hint , char * buf , int buf_ <nl> if ( g . ActiveId = = id & & io . MouseClicked [ 0 ] & & ! init_state & & ! init_make_active ) / / - V560 <nl> clear_active_id = true ; <nl> <nl> - / / When read - only we always use the live data passed to the function <nl> - / / FIXME - OPT : Because our selection / cursor code currently needs the wide text we need to convert it when active , which is not ideal : ( <nl> - if ( is_readonly & & state ! = NULL ) <nl> - { <nl> - const bool will_render_cursor = ( g . ActiveId = = id ) | | ( user_scroll_active ) ; <nl> - const bool will_render_selection = state - > HasSelection ( ) & & ( RENDER_SELECTION_WHEN_INACTIVE | | will_render_cursor ) ; <nl> - if ( will_render_cursor | | will_render_selection ) <nl> - { <nl> - const char * buf_end = NULL ; <nl> - state - > TextW . resize ( buf_size + 1 ) ; <nl> - state - > CurLenW = ImTextStrFromUtf8 ( state - > TextW . Data , state - > TextW . Size , buf , NULL , & buf_end ) ; <nl> - state - > CurLenA = ( int ) ( buf_end - buf ) ; <nl> - state - > CursorClamp ( ) ; <nl> - } <nl> - } <nl> - <nl> / / Lock the decision of whether we are going to take the path displaying the cursor or selection <nl> const bool render_cursor = ( g . ActiveId = = id ) | | ( state & & user_scroll_active ) ; <nl> - const bool render_selection = state & & state - > HasSelection ( ) & & ( RENDER_SELECTION_WHEN_INACTIVE | | render_cursor ) ; <nl> + bool render_selection = state & & state - > HasSelection ( ) & & ( RENDER_SELECTION_WHEN_INACTIVE | | render_cursor ) ; <nl> bool value_changed = false ; <nl> bool enter_pressed = false ; <nl> <nl> + / / When read - only we always use the live data passed to the function <nl> + / / FIXME - OPT : Because our selection / cursor code currently needs the wide text we need to convert it when active , which is not ideal : ( <nl> + if ( is_readonly & & state ! = NULL & & ( render_cursor | | render_selection ) ) <nl> + { <nl> + const char * buf_end = NULL ; <nl> + state - > TextW . resize ( buf_size + 1 ) ; <nl> + state - > CurLenW = ImTextStrFromUtf8 ( state - > TextW . Data , state - > TextW . Size , buf , NULL , & buf_end ) ; <nl> + state - > CurLenA = ( int ) ( buf_end - buf ) ; <nl> + state - > CursorClamp ( ) ; <nl> + render_selection & = state - > HasSelection ( ) ; <nl> + } <nl> + <nl> / / Select the buffer to render . <nl> const bool buf_display_from_state = ( render_cursor | | render_selection | | g . ActiveId = = id ) & & ! is_readonly & & state & & state - > TextAIsValid ; <nl> const bool is_displaying_hint = ( hint ! = NULL & & ( buf_display_from_state ? state - > TextA . Data : buf ) [ 0 ] = = 0 ) ; <nl> | InputText : Simplify read - only code path . | ocornut/imgui | abb7d7b18a9c9f722e941c84f5c6ed9456b44a9d | 2019-03-25T14:50:23Z |
mmm a / protobuf . bzl <nl> ppp b / protobuf . bzl <nl> def _proto_gen_impl ( ctx ) : <nl> if ctx . attr . gen_py : <nl> args + = [ " - - python_out = " + ctx . var [ " GENDIR " ] + " / " + gen_dir ] <nl> <nl> + inputs = srcs + deps <nl> if ctx . executable . plugin : <nl> plugin = ctx . executable . plugin <nl> lang = ctx . attr . plugin_language <nl> def _proto_gen_impl ( ctx ) : <nl> outdir = " , " . join ( ctx . attr . plugin_options ) + " : " + outdir <nl> args + = [ " - - plugin = protoc - gen - % s = % s " % ( lang , plugin . path ) ] <nl> args + = [ " - - % s_out = % s " % ( lang , outdir ) ] <nl> + inputs + = [ plugin ] <nl> <nl> if args : <nl> ctx . action ( <nl> - inputs = srcs + deps , <nl> + inputs = inputs , <nl> outputs = ctx . outputs . outs , <nl> arguments = args + import_flags + [ s . path for s in srcs ] , <nl> executable = ctx . executable . protoc , <nl> | Merge pull request from fweikert / patch - 1 | protocolbuffers/protobuf | afaa827860cb72b2d5298547d3e2ad4c9ca52a1c | 2016-10-12T17:48:22Z |
mmm a / tensorflow / python / ops / state_ops . py <nl> ppp b / tensorflow / python / ops / state_ops . py <nl> def scatter_nd_add ( ref , indices , updates , use_locking = False , name = None ) : <nl> updates : A ` Tensor ` . Must have the same type as ` ref ` . <nl> A tensor of updated values to add to ref . <nl> use_locking : An optional ` bool ` . Defaults to ` False ` . <nl> - An optional bool . Defaults to True . If True , the assignment will <nl> - be protected by a lock ; otherwise the behavior is undefined , <nl> - but may exhibit less contention . <nl> + If True , the assignment will be protected by a lock ; <nl> + otherwise the behavior is undefined , but may exhibit less contention . <nl> name : A name for the operation ( optional ) . <nl> <nl> Returns : <nl> | fix typo in scatter_nd_add docstring | tensorflow/tensorflow | 16f454f95e9d9823145d6b00a7e007afd0ea569b | 2018-12-11T02:03:05Z |
mmm a / lib / Parse / ParseExpr . cpp <nl> ppp b / lib / Parse / ParseExpr . cpp <nl> Parser : : parseTrailingClosures ( bool isExprBasic , SourceRange calleeRange , <nl> if ( ! Tok . is ( tok : : code_complete ) ) <nl> break ; <nl> <nl> + / / FIXME : Additional trailing closure completion on newline positions . <nl> + / / let foo = SomeThing { <nl> + / / . . . <nl> + / / } <nl> + / / < HERE > <nl> + / / This was previously enabled , but it failed to suggest ' foo ' because <nl> + / / the token was considered a part of the initializer . <nl> + if ( Tok . isAtStartOfLine ( ) ) <nl> + break ; <nl> + <nl> / / If the current completion mode doesn ' t support trailing closure <nl> / / completion , leave the token here and let " postfix completion " to <nl> / / handle it . <nl> mmm a / test / IDE / complete_multiple_trailingclosure . swift <nl> ppp b / test / IDE / complete_multiple_trailingclosure . swift <nl> <nl> / / RUN : % target - swift - ide - test - code - completion - source - filename % s - code - completion - token = INIT_FALLBACK_2 | % FileCheck % s - check - prefix = INIT_FALLBACK <nl> / / RUN : % target - swift - ide - test - code - completion - source - filename % s - code - completion - token = MEMBERDECL_SAMELINE | % FileCheck % s - check - prefix = MEMBERDECL_SAMELINE <nl> / / RUN : % target - swift - ide - test - code - completion - source - filename % s - code - completion - token = MEMBERDECL_NEWLINE | % FileCheck % s - check - prefix = MEMBERDECL_NEWLINE <nl> + / / RUN : % target - swift - ide - test - code - completion - source - filename % s - code - completion - token = INITIALIZED_VARDECL_SAMELINE | % FileCheck % s - check - prefix = INITIALIZED_VARDECL_SAMELINE <nl> + / / RUN : % target - swift - ide - test - code - completion - source - filename % s - code - completion - token = INITIALIZED_VARDECL_NEWLINE | % FileCheck % s - check - prefix = INITIALIZED_VARDECL_NEWLINE <nl> <nl> func globalFunc1 ( fn1 : ( ) - > Int , fn2 : ( ) - > String ) { } <nl> func testGlobalFunc ( ) { <nl> func testGlobalFunc ( ) { <nl> / / GLOBALFUNC_SAMELINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / GLOBALFUNC_SAMELINE : End completions <nl> <nl> - / / GLOBALFUNC_NEWLINE : Begin completions , 1 items <nl> - / / GLOBALFUNC_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / GLOBALFUNC_NEWLINE : Begin completions <nl> + / / FIXME - GLOBALFUNC_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / GLOBALFUNC_NEWLINE : End completions <nl> <nl> globalFunc1 ( ) <nl> func testMethod ( value : MyStruct ) { <nl> / / METHOD_SAMELINE : End completions <nl> <nl> / / METHOD_NEWLINE : Begin completions <nl> - / / METHOD_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ( ) - > String ) ? { | } # } [ # ( ( ) - > String ) ? # ] ; <nl> + / / FIXME - METHOD_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ( ) - > String ) ? { | } # } [ # ( ( ) - > String ) ? # ] ; <nl> / / METHOD_NEWLINE - DAG : Keyword [ class ] / None : class ; <nl> / / METHOD_NEWLINE - DAG : Keyword [ if ] / None : if ; <nl> / / METHOD_NEWLINE - DAG : Keyword [ try ] / None : try ; <nl> func testOverloadedInit ( ) { <nl> / / INIT_OVERLOADED_SAMELINE : End completions <nl> <nl> / / INIT_OVERLOADED_NEWLINE : Begin completions <nl> - / / INIT_OVERLOADED_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> - / / INIT_OVERLOADED_NEWLINE - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / FIXME - INIT_OVERLOADED_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / FIXME - INIT_OVERLOADED_NEWLINE - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_OVERLOADED_NEWLINE - DAG : Keyword [ class ] / None : class ; <nl> / / INIT_OVERLOADED_NEWLINE - DAG : Keyword [ if ] / None : if ; <nl> / / INIT_OVERLOADED_NEWLINE - DAG : Keyword [ try ] / None : try ; <nl> func testOptionalInit ( ) { <nl> / / INIT_OPTIONAL_SAMELINE : End completions <nl> <nl> / / INIT_OPTIONAL_NEWLINE : Begin completions <nl> - / / INIT_OPTIONAL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> - / / INIT_OPTIONAL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / FIXME - INIT_OPTIONAL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / FIXME - INIT_OPTIONAL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_OPTIONAL_NEWLINE - DAG : Keyword [ class ] / None : class ; <nl> / / INIT_OPTIONAL_NEWLINE - DAG : Keyword [ if ] / None : if ; <nl> / / INIT_OPTIONAL_NEWLINE - DAG : Keyword [ try ] / None : try ; <nl> func testOptionalInit ( ) { <nl> / / INIT_REQUIRED_SAMELINE_1 - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_REQUIRED_SAMELINE_1 : End completions <nl> <nl> - / / INIT_REQUIRED_NEWLINE_1 : Begin completions , 1 items <nl> - / / INIT_REQUIRED_NEWLINE_1 - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / INIT_REQUIRED_NEWLINE_1 : Begin completions <nl> + / / FIXME - INIT_REQUIRED_NEWLINE_1 - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_REQUIRED_NEWLINE_1 : End completions <nl> <nl> / / missing ' fn3 ' . <nl> func testOptionalInit ( ) { <nl> / / INIT_REQUIRED_SAMELINE_2 - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_REQUIRED_SAMELINE_2 : End completions <nl> <nl> - / / INIT_REQUIRED_NEWLINE_2 : Begin completions , 1 items <nl> - / / INIT_REQUIRED_NEWLINE_2 - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / INIT_REQUIRED_NEWLINE_2 : Begin completions <nl> + / / FIXME - INIT_REQUIRED_NEWLINE_2 - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> / / INIT_REQUIRED_NEWLINE_2 : End completions <nl> <nl> / / Call is completed . <nl> struct TestNominalMember : P { <nl> / / MEMBERDECL_SAMELINE : End completions <nl> <nl> / / MEMBERDECL_NEWLINE : Begin completions <nl> - / / MEMBERDECL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ( ) - > String ) ? { | } # } [ # ( ( ) - > String ) ? # ] ; name = fn2 : ( ( ) - > String ) ? <nl> + / / FIXME - MEMBERDECL_NEWLINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ( ) - > String ) ? { | } # } [ # ( ( ) - > String ) ? # ] ; name = fn2 : ( ( ) - > String ) ? <nl> / / MEMBERDECL_NEWLINE - DAG : Keyword [ enum ] / None : enum ; name = enum <nl> / / MEMBERDECL_NEWLINE - DAG : Keyword [ func ] / None : func ; name = func <nl> / / MEMBERDECL_NEWLINE - DAG : Keyword [ private ] / None : private ; name = private <nl> struct TestNominalMember : P { <nl> / / MEMBERDECL_NEWLINE - DAG : Decl [ InstanceMethod ] / Super : func foo ( ) { | } ; name = foo ( ) <nl> / / MEMBERDECL_NEWLINE : End completions <nl> } <nl> + <nl> + func testInitializedVarDecl ( ) { <nl> + let localVal = TestStruct { <nl> + 1 <nl> + } # ^ INITIALIZED_VARDECL_SAMELINE ^ # <nl> + # ^ INITIALIZED_VARDECL_NEWLINE ^ # <nl> + / / INITIALIZED_VARDECL_SAMELINE : Begin completions , 4 items <nl> + / / INITIALIZED_VARDECL_SAMELINE - NOT : localVal <nl> + / / INITIALIZED_VARDECL_SAMELINE - DAG : Pattern / ExprSpecific : { # fn2 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / INITIALIZED_VARDECL_SAMELINE - DAG : Pattern / ExprSpecific : { # fn3 : ( ) - > String { | } # } [ # ( ) - > String # ] ; <nl> + / / INITIALIZED_VARDECL_SAMELINE - DAG : Decl [ InstanceMethod ] / CurrNominal : . testStructMethod ( ) [ # Void # ] ; <nl> + / / INITIALIZED_VARDECL_SAMELINE - DAG : Keyword [ self ] / CurrNominal : . self [ # TestStruct # ] ; <nl> + / / INITIALIZED_VARDECL_SAMELINE - NOT : localVal <nl> + / / INITIALIZED_VARDECL_SAMELINE : End completions <nl> + <nl> + / / INITIALIZED_VARDECL_NEWLINE : Begin completions <nl> + / / INITIALIZED_VARDECL_NEWLINE - DAG : Decl [ LocalVar ] / Local : localVal [ # TestStruct # ] ; <nl> + / / INITIALIZED_VARDECL_NEWLINE : End completions <nl> + } <nl> | [ CodeCompletion ] Disable multi trailing closure completion at newline | apple/swift | 5936ddb2171c07e35ab4d0f066274ff8fa48c9a0 | 2020-08-03T18:58:22Z |
mmm a / Marlin / src / inc / Version . h <nl> ppp b / Marlin / src / inc / Version . h <nl> <nl> * version was tagged . <nl> * / <nl> # ifndef STRING_DISTRIBUTION_DATE <nl> - # define STRING_DISTRIBUTION_DATE " 2020 - 06 - 07 " <nl> + # define STRING_DISTRIBUTION_DATE " 2020 - 06 - 08 " <nl> # endif <nl> <nl> / * * <nl> | [ cron ] Bump distribution date ( 2020 - 06 - 08 ) | MarlinFirmware/Marlin | 968979f42db67767539022166ac1114ec932a69c | 2020-06-08T00:06:48Z |
mmm a / Jenkinsfile <nl> ppp b / Jenkinsfile <nl> try { <nl> } <nl> } <nl> } , <nl> + ' Scala : GPU ' : { <nl> + node ( ' mxnetlinux - gpu ' ) { <nl> + ws ( ' workspace / ut - scala - gpu ' ) { <nl> + init_git ( ) <nl> + unpack_lib ( ' gpu ' ) <nl> + timeout ( time : max_time , unit : ' MINUTES ' ) { <nl> + sh " ci / build . py - - nvidiadocker - - build - - platform ubuntu_gpu / work / runtime_functions . sh unittest_ubuntu_gpu_scala " <nl> + } <nl> + } <nl> + } <nl> + } , <nl> ' Perl : CPU ' : { <nl> node ( ' mxnetlinux - cpu ' ) { <nl> ws ( ' workspace / ut - perl - cpu ' ) { <nl> mmm a / ci / docker / runtime_functions . sh <nl> ppp b / ci / docker / runtime_functions . sh <nl> unittest_ubuntu_cpu_scala ( ) { <nl> make scalatest USE_BLAS = openblas <nl> } <nl> <nl> + unittest_ubuntu_gpu_scala ( ) { <nl> + set - ex <nl> + make scalapkg USE_OPENCV = 1 USE_BLAS = openblas USE_CUDA = 1 USE_CUDA_PATH = / usr / local / cuda USE_CUDNN = 1 <nl> + make scalatest USE_OPENCV = 1 USE_BLAS = openblas USE_CUDA = 1 USE_CUDA_PATH = / usr / local / cuda USE_CUDNN = 1 SCALA_TEST_ON_GPU = 1 <nl> + } <nl> + <nl> unittest_ubuntu_cpugpu_perl ( ) { <nl> set - ex <nl> . / perl - package / test . sh <nl> | [ MXNET - 256 ] Add CI Test for GPU ( ) | apache/incubator-mxnet | eb94089a7859148ea2b197b5461c8efcb700571a | 2018-04-03T17:38:46Z |
mmm a / cereal <nl> ppp b / cereal <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 3d09a7508f9497d77c401d96f8086494a188d786 <nl> + Subproject commit f1a9b228c6086eb444d60defb2d43d64ec1e2a94 <nl> mmm a / selfdrive / controls / controlsd . py <nl> ppp b / selfdrive / controls / controlsd . py <nl> def update_events ( self , CS ) : <nl> self . events . add ( EventName . relayMalfunction ) <nl> if self . sm [ ' plan ' ] . fcw : <nl> self . events . add ( EventName . fcw ) <nl> - if self . sm [ ' model ' ] . frameDropPerc > 2 and not SIMULATION : <nl> - self . events . add ( EventName . modeldLagging ) <nl> if not self . sm . alive [ ' frontFrame ' ] and ( self . sm . frame > 5 / DT_CTRL ) and not SIMULATION : <nl> - self . events . add ( EventName . cameraMalfunction ) <nl> + self . events . add ( EventName . cameraMalfunction ) <nl> + <nl> + if self . sm [ ' model ' ] . frameDropPerc > 20 and not SIMULATION : <nl> + self . events . add ( EventName . modeldLagging ) <nl> + elif self . sm [ ' model ' ] . frameDropPerc > 2 and not SIMULATION : <nl> + self . events . add ( EventName . modelLagWarning ) <nl> <nl> # Only allow engagement with brake pressed when stopped behind another stopped car <nl> if CS . brakePressed and self . sm [ ' plan ' ] . vTargetFuture > = STARTING_TARGET_SPEED \ <nl> mmm a / selfdrive / controls / lib / events . py <nl> ppp b / selfdrive / controls / lib / events . py <nl> def wrong_car_mode_alert ( CP : car . CarParams , sm : messaging . SubMaster , metric : boo <nl> Priority . LOW , VisualAlert . steerRequired , AudibleAlert . chimePrompt , 1 . , 1 . , 1 . ) , <nl> } , <nl> <nl> + EventName . modelLagWarning : { <nl> + ET . WARNING : Alert ( <nl> + " TAKE CONTROL " , <nl> + " Driving Model Lagging " , <nl> + AlertStatus . userPrompt , AlertSize . mid , <nl> + Priority . LOW , VisualAlert . steerRequired , AudibleAlert . chimePrompt , 1 . , 1 . , 1 . ) , <nl> + } , <nl> + <nl> EventName . fanMalfunction : { <nl> ET . PERMANENT : NormalPermanentAlert ( " Fan Malfunction " , " Contact Support " ) , <nl> } , <nl> | model lag warning ( ) | commaai/openpilot | 2d7a194f9fd5e5b26b55e3aa9e33efc95c97be6e | 2020-11-23T21:42:18Z |
mmm a / taichi / inc / constants . h <nl> ppp b / taichi / inc / constants . h <nl> constexpr int taichi_max_gpu_block_dim = 1024 ; <nl> constexpr std : : size_t taichi_global_tmp_buffer_size = 1024 * 1024 ; <nl> constexpr int taichi_max_num_mem_requests = 1024 * 64 ; <nl> constexpr std : : size_t taichi_page_size = 4096 ; <nl> + <nl> + template < typename T , typename G > <nl> + T taichi_union_cast_with_different_sizes ( G g ) { <nl> + union { <nl> + T t ; <nl> + G g ; <nl> + } u ; <nl> + u . g = g ; <nl> + return u . t ; <nl> + } <nl> + <nl> + template < typename T , typename G > <nl> + T taichi_union_cast ( G g ) { <nl> + static_assert ( sizeof ( T ) = = sizeof ( G ) ) ; <nl> + return taichi_union_cast_with_different_sizes < T > ( g ) ; <nl> + } <nl> mmm a / taichi / jit / jit_arch_cpu . cpp <nl> ppp b / taichi / jit / jit_arch_cpu . cpp <nl> class JITModuleCPU : public JITModule { <nl> <nl> void * lookup_function ( const std : : string & name ) override ; <nl> <nl> + uint64 fetch_result_u64 ( ) override { <nl> + / / TODO : move this to a new class e . g . " RuntimeEnvironment " <nl> + return * ( uint64 * ) get_current_program ( ) . result_buffer ; <nl> + } <nl> + <nl> bool direct_dispatch ( ) const override { <nl> return true ; <nl> } <nl> mmm a / taichi / jit / jit_arch_cuda . cpp <nl> ppp b / taichi / jit / jit_arch_cuda . cpp <nl> class JITModuleCUDA : public JITModule { <nl> cuda_context - > launch ( func , name , arg_pointers , grid_dim , block_dim ) ; <nl> } <nl> <nl> + uint64 fetch_result_u64 ( ) override { <nl> + uint64 ret ; <nl> + check_cuda_error ( cudaMemcpy ( & ret , get_current_program ( ) . result_buffer , <nl> + sizeof ( ret ) , cudaMemcpyDeviceToHost ) ) ; <nl> + return ret ; <nl> + } <nl> + <nl> bool direct_dispatch ( ) const override { <nl> return false ; <nl> } <nl> mmm a / taichi / jit / jit_module . h <nl> ppp b / taichi / jit / jit_module . h <nl> <nl> <nl> # include < memory > <nl> # include < functional > <nl> + # include " taichi / inc / constants . h " <nl> # include " taichi / llvm / llvm_fwd . h " <nl> # include " taichi / lang_util . h " <nl> # include " taichi / program / profiler . h " <nl> class JITModule { <nl> / / ( e . g . cudaLaunch ) ? <nl> virtual bool direct_dispatch ( ) const = 0 ; <nl> <nl> + virtual uint64 fetch_result_u64 ( ) = 0 ; <nl> + <nl> + template < typename T > <nl> + T fetch_result ( ) { <nl> + static_assert ( sizeof ( T ) < = sizeof ( uint64 ) ) ; <nl> + return taichi_union_cast < T > ( fetch_result_u64 ( ) ) ; <nl> + } <nl> + <nl> virtual ~ JITModule ( ) { <nl> } <nl> } ; <nl> mmm a / taichi / program / program . cpp <nl> ppp b / taichi / program / program . cpp <nl> Program : : Program ( Arch arch ) { <nl> } <nl> # endif <nl> <nl> + result_buffer = nullptr ; <nl> current_kernel = nullptr ; <nl> sync = true ; <nl> llvm_runtime = nullptr ; <nl> FunctionType Program : : compile ( Kernel & kernel ) { <nl> / / For CPU and CUDA archs only <nl> void Program : : initialize_runtime_system ( StructCompiler * scomp ) { <nl> / / auto tlctx = llvm_context_host . get ( ) ; <nl> + result_buffer = taichi_allocate_aligned ( this , 8 , 8 ) ; <nl> TaichiLLVMContext * tlctx ; <nl> if ( config . arch = = Arch : : cuda ) { <nl> tlctx = llvm_context_host . get ( ) ; <nl> void Program : : initialize_runtime_system ( StructCompiler * scomp ) { <nl> TI_TRACE ( " Allocating data structure of size { } B " , scomp - > root_size ) ; <nl> <nl> runtime - > call < void * , void * , std : : size_t , void * , void * > ( <nl> - " runtime_initialize " , & llvm_runtime , this , ( std : : size_t ) scomp - > root_size , <nl> + " runtime_initialize " , result_buffer , this , ( std : : size_t ) scomp - > root_size , <nl> ( void * ) & taichi_allocate_aligned , ( void * ) std : : printf ) ; <nl> + <nl> + TI_TRACE ( " Runtime initialized " ) ; <nl> + llvm_runtime = runtime - > fetch_result < void * > ( ) ; <nl> TI_TRACE ( " Runtime initialized " ) ; <nl> <nl> auto mem_req_queue = tlctx - > lookup_function < void * ( void * ) > ( <nl> void Program : : initialize_runtime_system ( StructCompiler * scomp ) { <nl> } <nl> } <nl> <nl> - <nl> if ( arch_use_host_memory ( config . arch ) ) { <nl> runtime - > call < void * , void * , void * > ( " Runtime_initialize_thread_pool " , <nl> llvm_runtime , & thread_pool , <nl> mmm a / taichi / program / program . h <nl> ppp b / taichi / program / program . h <nl> class Program { <nl> static std : : atomic < int > num_instances ; <nl> ThreadPool thread_pool ; <nl> std : : unique_ptr < MemoryPool > memory_pool ; <nl> + void * result_buffer ; / / TODO : move this <nl> <nl> std : : vector < std : : unique_ptr < Kernel > > functions ; <nl> <nl> mmm a / taichi / runtime / context . h <nl> ppp b / taichi / runtime / context . h <nl> struct Context { <nl> static constexpr size_t extra_args_size = sizeof ( extra_args ) ; <nl> <nl> # if defined ( TI_RUNTIME_HOST ) <nl> - template < typename T , typename G > <nl> - static T union_cast_with_different_sizes ( G g ) { <nl> - union { <nl> - T t ; <nl> - G g ; <nl> - } u ; <nl> - u . g = g ; <nl> - return u . t ; <nl> - } <nl> - <nl> template < typename T > <nl> T get_arg ( int i ) { <nl> - return union_cast_with_different_sizes < T > ( args [ i ] ) ; <nl> + return taichi_union_cast_with_different_sizes < T > ( args [ i ] ) ; <nl> } <nl> <nl> template < typename T > <nl> void set_arg ( int i , T v ) { <nl> - args [ i ] = union_cast_with_different_sizes < uint64 > ( v ) ; <nl> + args [ i ] = taichi_union_cast_with_different_sizes < uint64 > ( v ) ; <nl> } <nl> # endif <nl> } ; <nl> mmm a / taichi / runtime / runtime . cpp <nl> ppp b / taichi / runtime / runtime . cpp <nl> void initialize_rand_state ( RandState * state , u32 i ) { <nl> struct NodeManager ; <nl> <nl> struct Runtime { <nl> + Ptr result_buffer ; <nl> vm_allocator_type vm_allocator ; <nl> assert_failed_type assert_failed ; <nl> host_printf_type host_printf ; <nl> struct Runtime { <nl> void ( * profiler_start ) ( Ptr , Ptr ) ; <nl> void ( * profiler_stop ) ( Ptr ) ; <nl> <nl> + template < typename T > <nl> + void set_result ( T t ) { <nl> + * ( u64 * ) result_buffer = taichi_union_cast < uint64 > ( t ) ; <nl> + } <nl> + <nl> template < typename T , typename . . . Args > <nl> T * create ( Args & & . . . args ) { <nl> auto ptr = ( T * ) request_allocate_aligned ( sizeof ( T ) , 4096 ) ; <nl> Ptr Runtime : : request_allocate_aligned ( std : : size_t size , std : : size_t alignment ) { <nl> return r - > ptr ; <nl> } <nl> <nl> - void runtime_initialize ( Runtime * * runtime_ptr , <nl> + void runtime_initialize ( Ptr result_buffer , <nl> Ptr prog , <nl> uint64_t root_size , <nl> void * _vm_allocator , <nl> void runtime_initialize ( Runtime * * runtime_ptr , <nl> / / bootstrap <nl> auto vm_allocator = ( vm_allocator_type ) _vm_allocator ; <nl> auto host_printf = ( host_printf_type ) _host_printf ; <nl> - * runtime_ptr = ( Runtime * ) vm_allocator ( prog , sizeof ( Runtime ) , 128 ) ; <nl> - Runtime * runtime = * runtime_ptr ; <nl> + Runtime * runtime = ( Runtime * ) vm_allocator ( prog , sizeof ( Runtime ) , 128 ) ; <nl> + runtime - > result_buffer = result_buffer ; <nl> + runtime - > set_result ( runtime ) ; <nl> runtime - > vm_allocator = vm_allocator ; <nl> runtime - > host_printf = host_printf ; <nl> runtime - > prog = prog ; <nl> | fetch result without unified memorysupport | taichi-dev/taichi | e4519dd752b31e0b4d354c39501267faa33ef68a | 2020-02-29T02:06:26Z |
mmm a / jstests / replsets / sync1 . js <nl> ppp b / jstests / replsets / sync1 . js <nl> doTest = function ( signal ) { <nl> <nl> sleep ( 5000 ) ; <nl> <nl> - / / yay ! there are out - of - date nodes <nl> var max1 ; <nl> var max2 ; <nl> var count = 0 ; <nl> doTest = function ( signal ) { <nl> break ; <nl> } <nl> <nl> - print ( " \ nsync1 . js * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * part 8 " ) ; <nl> - <nl> - if ( max1 . z = = ( inserts - 1 ) & & max2 . z = = ( inserts - 1 ) ) { <nl> - print ( " \ nsync1 . js try increasing # if inserts and running again " ) ; <nl> - replTest . stopSet ( signal ) ; <nl> - return ; <nl> - } <nl> - <nl> / / wait for a new master to be elected <nl> sleep ( 5000 ) ; <nl> var newMaster ; <nl> | update rs test | mongodb/mongo | 9b8a7788ab7fe1d2ece7aaf6958b8d7de9110628 | 2010-08-23T15:38:39Z |
mmm a / arangosh / V8Client / V8ClientConnection . cpp <nl> ppp b / arangosh / V8Client / V8ClientConnection . cpp <nl> using namespace std ; <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> V8ClientConnection : : V8ClientConnection ( Endpoint * endpoint , <nl> - string databaseName , <nl> - const string & username , <nl> - const string & password , <nl> + std : : string databaseName , <nl> + std : : string const & username , <nl> + std : : string const & password , <nl> double requestTimeout , <nl> double connectTimeout , <nl> size_t numRetries , <nl> V8ClientConnection : : ~ V8ClientConnection ( ) { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> string V8ClientConnection : : rewriteLocation ( void * data , <nl> - const string & location ) { <nl> + std : : string const & location ) { <nl> V8ClientConnection * c = static_cast < V8ClientConnection * > ( data ) ; <nl> <nl> TRI_ASSERT ( c ! = nullptr ) ; <nl> bool V8ClientConnection : : isConnected ( ) { <nl> return _connection - > isConnected ( ) ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief set the current operation to interrupted <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + void V8ClientConnection : : setInterrupted ( bool value ) { <nl> + _connection - > setInterrupted ( value ) ; <nl> + } <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns the current database name <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const string & V8ClientConnection : : getDatabaseName ( ) { <nl> + std : : string const & V8ClientConnection : : getDatabaseName ( ) { <nl> return _databaseName ; <nl> } <nl> <nl> void V8ClientConnection : : setDatabaseName ( std : : string const & databaseName ) { <nl> / / / @ brief returns the version and build number of the arango server <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const string & V8ClientConnection : : getVersion ( ) { <nl> + std : : string const & V8ClientConnection : : getVersion ( ) { <nl> return _version ; <nl> } <nl> <nl> const string & V8ClientConnection : : getVersion ( ) { <nl> / / / @ brief returns the server mode <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const string & V8ClientConnection : : getMode ( ) { <nl> + std : : string const & V8ClientConnection : : getMode ( ) { <nl> return _mode ; <nl> } <nl> <nl> int V8ClientConnection : : getLastHttpReturnCode ( ) { <nl> / / / @ brief get the last error message <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & V8ClientConnection : : getErrorMessage ( ) { <nl> + std : : string const & V8ClientConnection : : getErrorMessage ( ) { <nl> return _lastErrorMessage ; <nl> } <nl> <nl> v8 : : Handle < v8 : : Value > V8ClientConnection : : requestData ( v8 : : Isolate * isolate , <nl> v8 : : Handle < v8 : : Value > V8ClientConnection : : handleResult ( v8 : : Isolate * isolate ) { <nl> v8 : : EscapableHandleScope scope ( isolate ) ; <nl> <nl> + if ( _httpResult = = nullptr ) { <nl> + return scope . Escape < v8 : : Value > ( v8 : : Undefined ( isolate ) ) ; <nl> + } <nl> + <nl> if ( ! _httpResult - > isComplete ( ) ) { <nl> / / not complete <nl> _lastErrorMessage = _client - > getErrorMessage ( ) ; <nl> mmm a / arangosh / V8Client / V8ClientConnection . h <nl> ppp b / arangosh / V8Client / V8ClientConnection . h <nl> namespace triagens { <nl> <nl> V8ClientConnection ( triagens : : rest : : Endpoint * , <nl> std : : string , <nl> - const std : : string & , <nl> - const std : : string & , <nl> + std : : string const & , <nl> + std : : string const & , <nl> double , <nl> double , <nl> size_t , <nl> namespace triagens { <nl> / / / @ brief request location rewriter ( injects database name ) <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - static std : : string rewriteLocation ( void * , const std : : string & ) ; <nl> + static std : : string rewriteLocation ( void * , std : : string const & ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns true if it is connected <nl> namespace triagens { <nl> <nl> bool isConnected ( ) ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief set the current operation to interrupted <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + void setInterrupted ( bool ) ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns the current database name <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getDatabaseName ( ) ; <nl> + std : : string const & getDatabaseName ( ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief set the current database name <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - void setDatabaseName ( const std : : string & ) ; <nl> + void setDatabaseName ( std : : string const & ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns the version and build number of the arango server <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getVersion ( ) ; <nl> + std : : string const & getVersion ( ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns the server mode <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getMode ( ) ; <nl> + std : : string const & getMode ( ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief get the last http return code <nl> namespace triagens { <nl> / / / @ return string the error message <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getErrorMessage ( ) ; <nl> + std : : string const & getErrorMessage ( ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief get the endpoint string <nl> namespace triagens { <nl> / / / @ return string <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string getEndpointSpecification ( ) ; <nl> + std : : string getEndpointSpecification ( ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief get the simple http client <nl> mmm a / arangosh / V8Client / arangosh . cpp <nl> ppp b / arangosh / V8Client / arangosh . cpp <nl> static void RunShell ( v8 : : Isolate * isolate , v8 : : Handle < v8 : : Context > context , boo <nl> v8 : : Context : : Scope contextScope ( context ) ; <nl> v8 : : Local < v8 : : String > name ( TRI_V8_ASCII_STRING ( TRI_V8_SHELL_COMMAND_NAME ) ) ; <nl> <nl> + auto cc = ClientConnection ; <nl> + <nl> V8LineEditor console ( isolate , context , " . arangosh . history " ) ; <nl> + console . setSignalFunction ( [ & cc ] ( ) { <nl> + if ( cc ! = nullptr ) { <nl> + cc - > setInterrupted ( true ) ; <nl> + } <nl> + } ) ; <nl> + <nl> console . open ( BaseClient . autoComplete ( ) ) ; <nl> <nl> uint64_t nrCommands = 0 ; <nl> static void RunShell ( v8 : : Isolate * isolate , v8 : : Handle < v8 : : Context > context , boo <nl> / / this will change the prompt for the next round <nl> promptError = true ; <nl> } <nl> + <nl> + ClientConnection - > setInterrupted ( false ) ; <nl> <nl> BaseClient . stopPager ( ) ; <nl> BaseClient . printLine ( " " ) ; <nl> mmm a / lib / SimpleHttpClient / ClientConnection . cpp <nl> ppp b / lib / SimpleHttpClient / ClientConnection . cpp <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> return false ; <nl> } <nl> <nl> + / / wait for at most 0 . 5 seconds for poll / select to complete <nl> + / / if it takes longer , break each poll / select into smaller chunks so we can <nl> + / / interrupt the whole process if it takes too long in total <nl> + static double const POLL_DURATION = 0 . 5 ; <nl> auto const fd = TRI_get_fd_or_handle_of_socket ( _socket ) ; <nl> double start = TRI_microtime ( ) ; <nl> int res ; <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> poller . events = ( isWrite ? POLLOUT : POLLIN ) ; <nl> <nl> while ( true ) { / / will be left by break <nl> - res = poll ( & poller , 1 , towait ) ; <nl> + res = poll ( & poller , 1 , towait > static_cast < int > ( POLL_DURATION * 1000 . 0 ) ? static_cast < int > ( POLL_DURATION * 1000 . 0 ) : towait ) ; <nl> if ( res = = - 1 & & errno = = EINTR ) { <nl> if ( ! nowait ) { <nl> double end = TRI_microtime ( ) ; <nl> towait - = static_cast < int > ( ( end - start ) * 1000 . 0 ) ; <nl> start = end ; <nl> - if ( towait < 0 ) { / / Should not happen , but there might be rounding <nl> + if ( towait < = 0 ) { / / Should not happen , but there might be rounding <nl> / / errors , so just to prevent a poll call with <nl> / / negative timeout . . . <nl> res = 0 ; <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> } <nl> continue ; <nl> } <nl> + <nl> + if ( res = = 0 ) { <nl> + if ( isInterrupted ( ) ) { <nl> + _errorDetails = std : : string ( " command locally aborted " ) ; <nl> + TRI_set_errno ( TRI_ERROR_REQUEST_CANCELED ) ; <nl> + return false ; <nl> + } <nl> + double end = TRI_microtime ( ) ; <nl> + towait - = static_cast < int > ( ( end - start ) * 1000 . 0 ) ; <nl> + if ( towait < = 0 ) { <nl> + break ; <nl> + } <nl> + start = end ; <nl> + continue ; <nl> + } <nl> + <nl> break ; <nl> } <nl> / / Now res can be : <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> return false ; <nl> } <nl> <nl> - fd_set fdset ; <nl> - <nl> / / handle interrupt <nl> - do { <nl> + do { <nl> + retry : <nl> + fd_set fdset ; <nl> FD_ZERO ( & fdset ) ; <nl> FD_SET ( fd , & fdset ) ; <nl> <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> <nl> int sockn = ( int ) ( fd + 1 ) ; <nl> <nl> + double waitTimeout = timeout ; <nl> + if ( waitTimeout > POLL_DURATION ) { <nl> + waitTimeout = POLL_DURATION ; <nl> + } <nl> + <nl> struct timeval t ; <nl> - t . tv_sec = ( long ) timeout ; <nl> - t . tv_usec = ( long ) ( ( timeout - ( double ) t . tv_sec ) * 1000000 . 0 ) ; <nl> + t . tv_sec = ( long ) waitTimeout ; <nl> + t . tv_usec = ( long ) ( ( waitTimeout - ( double ) t . tv_sec ) * 1000000 . 0 ) ; <nl> <nl> res = select ( sockn , readFds , writeFds , nullptr , & t ) ; <nl> <nl> bool ClientConnection : : prepare ( double timeout , bool isWrite ) const { <nl> timeout = timeout - ( end - start ) ; <nl> start = end ; <nl> } <nl> - } while ( res = = - 1 & & errno = = EINTR & & timeout > 0 . 0 ) ; <nl> + else if ( res = = 0 ) { <nl> + if ( isInterrupted ( ) ) { <nl> + _errorDetails = std : : string ( " command locally aborted " ) ; <nl> + TRI_set_errno ( TRI_ERROR_REQUEST_CANCELED ) ; <nl> + return false ; <nl> + } <nl> + double end = TRI_microtime ( ) ; <nl> + timeout = timeout - ( end - start ) ; <nl> + if ( timeout < = 0 . 0 ) { <nl> + break ; <nl> + } <nl> + start = end ; <nl> + goto retry ; <nl> + } <nl> + } <nl> + while ( res = = - 1 & & errno = = EINTR & & timeout > 0 . 0 ) ; <nl> # endif <nl> <nl> if ( res > 0 ) { <nl> mmm a / lib / SimpleHttpClient / GeneralClientConnection . cpp <nl> ppp b / lib / SimpleHttpClient / GeneralClientConnection . cpp <nl> GeneralClientConnection : : GeneralClientConnection ( Endpoint * endpoint , <nl> _connectTimeout ( connectTimeout ) , <nl> _connectRetries ( connectRetries ) , <nl> _numConnectRetries ( 0 ) , <nl> - _isConnected ( false ) { <nl> + _isConnected ( false ) , <nl> + _isInterrupted ( false ) { <nl> <nl> } <nl> <nl> GeneralClientConnection * GeneralClientConnection : : factory ( Endpoint * endpoint , <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> bool GeneralClientConnection : : connect ( ) { <nl> + _isInterrupted = false ; <nl> disconnect ( ) ; <nl> <nl> if ( _numConnectRetries < _connectRetries + 1 ) { <nl> void GeneralClientConnection : : disconnect ( ) { <nl> } <nl> <nl> _isConnected = false ; <nl> + _isInterrupted = false ; <nl> _numConnectRetries = 0 ; <nl> } <nl> <nl> mmm a / lib / SimpleHttpClient / GeneralClientConnection . h <nl> ppp b / lib / SimpleHttpClient / GeneralClientConnection . h <nl> <nl> # define ARANGODB_SIMPLE_HTTP_CLIENT_GENERAL_CLIENT_CONNECTION_H 1 <nl> <nl> # include " Basics / Common . h " <nl> - <nl> # include " Basics / StringBuffer . h " <nl> # include " Rest / Endpoint . h " <nl> <nl> namespace triagens { <nl> / / / @ brief return the endpoint <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getErrorDetails ( ) const { <nl> + std : : string const & getErrorDetails ( ) const { <nl> return _errorDetails ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief whether or not the current operation should be interrupted <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + bool isInterrupted ( ) const { <nl> + return _isInterrupted ; <nl> + } <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief interrupt the current operation <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + void setInterrupted ( bool value ) { <nl> + _isInterrupted = value ; <nl> + } <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / - - SECTION - - protected virtual methods <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> namespace triagens { <nl> <nl> bool _isConnected ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief whether or not the current operation should be interrupted <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + bool _isInterrupted ; <nl> + <nl> } ; <nl> } <nl> } <nl> mmm a / lib / SimpleHttpClient / SimpleHttpClient . cpp <nl> ppp b / lib / SimpleHttpClient / SimpleHttpClient . cpp <nl> namespace triagens { <nl> " ' ' " + <nl> _connection - > getErrorDetails ( ) + <nl> " ' " ) ; <nl> + <nl> + if ( _connection - > isInterrupted ( ) ) { <nl> + this - > close ( ) ; <nl> + delete _result ; <nl> + _result = nullptr ; <nl> + setErrorMessage ( " Command locally aborted " ) ; <nl> + return nullptr ; <nl> + } <nl> this - > close ( ) ; / / this sets the state to IN_CONNECT for a retry <nl> break ; <nl> } <nl> mmm a / lib / SimpleHttpClient / SimpleHttpClient . h <nl> ppp b / lib / SimpleHttpClient / SimpleHttpClient . h <nl> namespace triagens { <nl> / / / @ param password password <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - void setUserNamePassword ( const std : : string & prefix , <nl> - const std : : string & username , <nl> - const std : : string & password ) ; <nl> + void setUserNamePassword ( std : : string const & prefix , <nl> + std : : string const & username , <nl> + std : : string const & password ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief allows rewriting locations <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> void setLocationRewriter ( void * data , <nl> - std : : string ( * func ) ( void * , const std : : string & ) ) { <nl> + std : : string ( * func ) ( void * , std : : string const & ) ) { <nl> _locationRewriter . data = data ; <nl> _locationRewriter . func = func ; <nl> } <nl> namespace triagens { <nl> / / / @ brief returns the current error message <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - const std : : string & getErrorMessage ( ) const { <nl> + std : : string const & getErrorMessage ( ) const { <nl> return _errorMessage ; <nl> } <nl> <nl> namespace triagens { <nl> / / / @ brief register and dump an error message <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - void setErrorMessage ( const std : : string & message , <nl> + void setErrorMessage ( std : : string const & message , <nl> bool forceWarn = false ) { <nl> _errorMessage = message ; <nl> <nl> mmm a / lib / Utilities / LineEditor . cpp <nl> ppp b / lib / Utilities / LineEditor . cpp <nl> using namespace arangodb ; <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> LineEditor : : LineEditor ( ) <nl> - : _shell ( nullptr ) { <nl> + : _shell ( nullptr ) , <nl> + _signalFunc ( nullptr ) { <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void LineEditor : : addHistory ( const std : : string & line ) { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> void LineEditor : : signal ( ) { <nl> + if ( _signalFunc ! = nullptr ) { <nl> + _signalFunc ( ) ; <nl> + } <nl> _shell - > signal ( ) ; <nl> } <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief register a callback function to be executed on signal receipt <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + void LineEditor : : setSignalFunction ( std : : function < void ( ) > const & func ) { <nl> + _signalFunc = func ; <nl> + } <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / - - SECTION - - END - OF - FILE <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> mmm a / lib / Utilities / LineEditor . h <nl> ppp b / lib / Utilities / LineEditor . h <nl> <nl> # define ARANGODB_UTILITIES_LINE_EDITOR_H 1 <nl> <nl> # include " Basics / Common . h " <nl> + # include < functional > <nl> <nl> namespace arangodb { <nl> class ShellBase ; <nl> namespace arangodb { <nl> <nl> void signal ( ) ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief register a callback function to be executed on signal receipt <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + void setSignalFunction ( std : : function < void ( ) > const & ) ; <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / - - SECTION - - protected variables <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> namespace arangodb { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> ShellBase * _shell ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief callback function to be executed on signal receipt <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + std : : function < void ( ) > _signalFunc ; <nl> } ; <nl> } <nl> <nl> mmm a / lib / V8 / V8LineEditor . cpp <nl> ppp b / lib / V8 / V8LineEditor . cpp <nl> static std : : atomic < V8LineEditor * > SINGLETON ( nullptr ) ; <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> # ifdef _WIN32 <nl> + <nl> static bool SignalHandler ( DWORD eventType ) { <nl> - switch ( eventType ) { <nl> - case CTRL_BREAK_EVENT : <nl> - case CTRL_C_EVENT : <nl> - case CTRL_CLOSE_EVENT : <nl> - case CTRL_LOGOFF_EVENT : <nl> - case CTRL_SHUTDOWN_EVENT : { <nl> + switch ( eventType ) { <nl> + case CTRL_BREAK_EVENT : <nl> + case CTRL_C_EVENT : <nl> + case CTRL_CLOSE_EVENT : <nl> + case CTRL_LOGOFF_EVENT : <nl> + case CTRL_SHUTDOWN_EVENT : { <nl> / / get the instance of the console <nl> auto instance = SINGLETON . load ( ) ; <nl> <nl> static bool SignalHandler ( DWORD eventType ) { <nl> <nl> instance - > signal ( ) ; <nl> } <nl> - <nl> + <nl> + return true ; <nl> + } <nl> + default : { <nl> return true ; <nl> - } <nl> - default : { <nl> - return true ; <nl> - } <nl> - } <nl> - <nl> + } <nl> + } <nl> } <nl> + <nl> # else <nl> + <nl> static void SignalHandler ( int signal ) { <nl> <nl> / / get the instance of the console <nl> static void SignalHandler ( int signal ) { <nl> instance - > signal ( ) ; <nl> } <nl> } <nl> + <nl> # endif <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> mmm a / lib / V8 / v8 - utils . cpp <nl> ppp b / lib / V8 / v8 - utils . cpp <nl> TRI_Utf8ValueNFC : : ~ TRI_Utf8ValueNFC ( ) { <nl> <nl> static void CreateErrorObject ( v8 : : Isolate * isolate , <nl> int errorNumber , <nl> - string const & message ) { <nl> + std : : string const & message ) { <nl> if ( errorNumber = = TRI_ERROR_OUT_OF_MEMORY ) { <nl> LOG_ERROR ( " encountered out - of - memory error " ) ; <nl> } <nl> static void CreateErrorObject ( v8 : : Isolate * isolate , <nl> <nl> if ( err . IsEmpty ( ) ) { <nl> isolate - > ThrowException ( v8 : : Object : : New ( isolate ) ) ; <nl> - return ; <nl> + return ; <nl> } <nl> <nl> v8 : : Handle < v8 : : Object > errorObject = err - > ToObject ( ) ; <nl> <nl> if ( errorObject . IsEmpty ( ) ) { <nl> isolate - > ThrowException ( v8 : : Object : : New ( isolate ) ) ; <nl> - return ; <nl> + return ; <nl> } <nl> <nl> errorObject - > Set ( TRI_V8_ASCII_STRING ( " errorNum " ) , v8 : : Number : : New ( isolate , errorNumber ) ) ; <nl> v8 : : Handle < v8 : : Value > TRI_ExecuteJavaScriptString ( v8 : : Isolate * isolate , <nl> / / / @ brief creates an error in a javascript object , based on error number only <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - void TRI_CreateErrorObject ( v8 : : Isolate * isolate , int errorNumber ) { <nl> + void TRI_CreateErrorObject ( v8 : : Isolate * isolate , int errorNumber ) { <nl> v8 : : HandleScope scope ( isolate ) ; <nl> <nl> CreateErrorObject ( isolate , errorNumber , TRI_errno_string ( errorNumber ) ) ; <nl> void TRI_CreateErrorObject ( v8 : : Isolate * isolate , int errorNumber ) { <nl> <nl> void TRI_CreateErrorObject ( v8 : : Isolate * isolate , <nl> int errorNumber , <nl> - string const & message ) { <nl> + std : : string const & message ) { <nl> v8 : : HandleScope scope ( isolate ) ; <nl> CreateErrorObject ( isolate , errorNumber , message ) ; <nl> } <nl> void TRI_CreateErrorObject ( v8 : : Isolate * isolate , <nl> <nl> void TRI_CreateErrorObject ( v8 : : Isolate * isolate , <nl> int errorNumber , <nl> - string const & message , <nl> + std : : string const & message , <nl> bool autoPrepend ) { <nl> v8 : : HandleScope scope ( isolate ) ; <nl> <nl> | issue : allow aborting waiting HTTP requests from the ArangoShell | arangodb/arangodb | cf7fa63a53b42e71483f2d76449e61dc0147fdac | 2015-12-03T17:55:51Z |
mmm a / tensorflow / core / distributed_runtime / worker_cache_wrapper . h <nl> ppp b / tensorflow / core / distributed_runtime / worker_cache_wrapper . h <nl> class WorkerCacheWrapper : public WorkerCacheInterface { <nl> <nl> / / Updates * workers with strings naming the remote worker tasks to <nl> / / which open channels have been established . <nl> - virtual void ListWorkers ( std : : vector < string > * workers ) const { <nl> + void ListWorkers ( std : : vector < string > * workers ) const override { <nl> return wrapped_ - > ListWorkers ( workers ) ; <nl> } <nl> - virtual void ListWorkersInJob ( const string & job_name , <nl> - std : : vector < string > * workers ) const { <nl> + void ListWorkersInJob ( const string & job_name , <nl> + std : : vector < string > * workers ) const override { <nl> return wrapped_ - > ListWorkersInJob ( job_name , workers ) ; <nl> } <nl> <nl> class WorkerCacheWrapper : public WorkerCacheInterface { <nl> / / or can be constructed , returns a pointer to a WorkerInterface object <nl> / / wrapping that channel . The returned value must be destroyed by <nl> / / calling ` this - > ReleaseWorker ( target , ret ) ` <nl> - virtual WorkerInterface * GetOrCreateWorker ( const string & target ) { <nl> + WorkerInterface * GetOrCreateWorker ( const string & target ) override { <nl> return wrapped_ - > GetOrCreateWorker ( target ) ; <nl> } <nl> <nl> class WorkerCacheWrapper : public WorkerCacheInterface { <nl> / / TODO ( jeff , sanjay ) : Consider moving target into WorkerInterface . <nl> / / TODO ( jeff , sanjay ) : Unify all worker - cache impls and factor out a <nl> / / per - rpc - subsystem WorkerInterface creator . <nl> - virtual void ReleaseWorker ( const string & target , WorkerInterface * worker ) { <nl> + void ReleaseWorker ( const string & target , WorkerInterface * worker ) override { <nl> return wrapped_ - > ReleaseWorker ( target , worker ) ; <nl> } <nl> <nl> class WorkerCacheWrapper : public WorkerCacheInterface { <nl> / / within its local environment . Returns true if * locality <nl> / / was set , using only locally cached data . Returns false <nl> / / if status data for that device was not available . Never blocks . <nl> - virtual bool GetDeviceLocalityNonBlocking ( const string & device , <nl> - DeviceLocality * locality ) { <nl> + bool GetDeviceLocalityNonBlocking ( const string & device , <nl> + DeviceLocality * locality ) override { <nl> return wrapped_ - > GetDeviceLocalityNonBlocking ( device , locality ) ; <nl> } <nl> <nl> / / Set * locality with the DeviceLocality of the specified remote device <nl> / / within its local environment . Callback gets Status : : OK if * locality <nl> / / was set . <nl> - virtual void GetDeviceLocalityAsync ( const string & device , <nl> - DeviceLocality * locality , <nl> - StatusCallback done ) { <nl> + void GetDeviceLocalityAsync ( const string & device , DeviceLocality * locality , <nl> + StatusCallback done ) override { <nl> return wrapped_ - > GetDeviceLocalityAsync ( device , locality , std : : move ( done ) ) ; <nl> } <nl> <nl> / / Start / stop logging activity . <nl> - virtual void SetLogging ( bool active ) { wrapped_ - > SetLogging ( active ) ; } <nl> + void SetLogging ( bool active ) override { wrapped_ - > SetLogging ( active ) ; } <nl> <nl> / / Discard any saved log data . <nl> - virtual void ClearLogs ( ) { wrapped_ - > ClearLogs ( ) ; } <nl> + void ClearLogs ( ) override { wrapped_ - > ClearLogs ( ) ; } <nl> <nl> / / Return logs for the identified step in * ss . Any returned data will no <nl> / / longer be stored . <nl> - virtual bool RetrieveLogs ( int64 step_id , StepStats * ss ) { <nl> + bool RetrieveLogs ( int64 step_id , StepStats * ss ) override { <nl> return wrapped_ - > RetrieveLogs ( step_id , ss ) ; <nl> } <nl> <nl> | Fix compiler warnings in worker_cache_wrapper . h . | tensorflow/tensorflow | b1c8e44cdd85488bc07565f13411a6aef6d238cc | 2019-07-31T16:15:51Z |
mmm a / jstests / replsets / indexbg_drop . js <nl> ppp b / jstests / replsets / indexbg_drop . js <nl> masterDB . runCommand ( { dropIndexes : collection , index : " * " } ) ; <nl> jsTest . log ( " Waiting on replication " ) ; <nl> replTest . awaitReplication ( ) ; <nl> <nl> + print ( " index list on master : " ) ; <nl> masterDB . system . indexes . find ( ) . forEach ( printjson ) ; <nl> - secondDB . system . indexes . find ( ) . forEach ( printjson ) ; <nl> <nl> - assert . eq ( 1 , secondDB . system . indexes . count ( ) ) ; <nl> + / / we need to assert . soon because the drop only marks the index for removal <nl> + / / the removal itself is asynchronous and may take another moment before it happens <nl> + var i = 0 ; <nl> + assert . soon ( function ( ) { <nl> + print ( " index list on secondary ( run " + i + " ) : " ) ; <nl> + secondDB . system . indexes . find ( ) . forEach ( printjson ) ; <nl> + <nl> + i + + ; <nl> + return 1 = = = secondDB . system . indexes . count ( ) ; <nl> + } , " secondary did not drop index " <nl> + ) ; <nl> <nl> replTest . stopSet ( ) ; <nl> | fix indexbg_drops . js to waiting for the index to drop via assert . soon ( ) | mongodb/mongo | 45ac2c3e3a4dc67751383b3f2c3f974ecd8d0c06 | 2014-01-23T21:52:13Z |
mmm a / dbms / include / DB / Storages / StorageMergeTree . h <nl> ppp b / dbms / include / DB / Storages / StorageMergeTree . h <nl> friend class MergeTreeBlockOutputStream ; <nl> bool has_force_restore_data_flag , <nl> const MergeTreeSettings & settings_ ) ; <nl> <nl> - / * * Определяет , какие куски нужно объединять , и объединяет их . <nl> - * Если aggressive - выбрать куски , не обращая внимание на соотношение размеров и их новизну ( для запроса OPTIMIZE ) . <nl> - * Возвращает , получилось ли что - нибудь объединить . <nl> + / * * Determines what parts should be merged and merges it . <nl> + * If aggressive - when selects parts don ' t takes into account their ratio size and novelty ( used for OPTIMIZE query ) . <nl> + * Returns true if merge is finished successfully . <nl> * / <nl> bool merge ( size_t aio_threshold , bool aggressive , const String & partition , bool final ) ; <nl> <nl> mmm a / doc / reference_en . html <nl> ppp b / doc / reference_en . html <nl> < h4 > Synchronicity of ALTER queries < / h4 > <nl> <nl> = = = OPTIMIZE = = = <nl> <nl> - % % OPTIMIZE TABLE [ db . ] name % % <nl> + % % OPTIMIZE TABLE [ db . ] name [ PARTITION partition ] [ FINAL ] % % <nl> <nl> Asks the table engine to do something for optimization . <nl> Supported only by * MergeTree engines , in which this query initializes a non - scheduled merge of data parts . <nl> + If PARTITION is specified , then only specified partition will be optimized . <nl> + If FINAL is specified , then optimization will be performed even if data inside the partition already optimized ( i . e . all data is in single part ) . <nl> <nl> <nl> = = = INSERT = = = <nl> mmm a / doc / reference_ru . html <nl> ppp b / doc / reference_ru . html <nl> < h4 > Синхронность запросов ALTER < / h4 > <nl> <nl> = = = OPTIMIZE = = = <nl> <nl> - % % OPTIMIZE TABLE [ db . ] name % % <nl> + % % OPTIMIZE TABLE [ db . ] name [ PARTITION partition ] [ FINAL ] % % <nl> <nl> Просит движок таблицы сделать что - нибудь , что может привести к более оптимальной работе . <nl> Поддерживается только движками * MergeTree , в котором выполнение этого запроса инициирует внеочередное слияние кусков данных . <nl> + Если указан PARTITION , то оптимизация будет производиться только для указаной партиции . <nl> + Если указан FINAL , то оптимизация будет производиться даже когда все данные уже лежат в одном куске . <nl> <nl> <nl> = = = INSERT = = = <nl> | Add more docs for OPTIMIZE . [ # CLICKHOUSE - 3 ] | ClickHouse/ClickHouse | 74cd2c2334bef572d0bef3857c69cfb1d467c485 | 2017-01-24T18:26:29Z |
mmm a / stdlib / public / core / String . swift <nl> ppp b / stdlib / public / core / String . swift <nl> extension String { <nl> / / make UTF - 16 array beforehand <nl> let codeUnits = Array ( self . utf16 ) . withUnsafeBufferPointer { <nl> ( uChars : UnsafeBufferPointer < UInt16 > ) - > Array < UInt16 > in <nl> - var result = Array < UInt16 > ( repeating : 0 , count : uChars . count ) <nl> - let len = result . withUnsafeMutableBufferPointer { <nl> - ( output ) - > Int in <nl> - var err = __swift_stdlib_U_ZERO_ERROR <nl> - return Int ( truncatingIfNeeded : <nl> + var length : Int = 0 <nl> + let result = Array < UInt16 > ( unsafeUninitializedCapacity : uChars . count ) { <nl> + buffer , initializedCount in <nl> + var error = __swift_stdlib_U_ZERO_ERROR <nl> + length = Int ( truncatingIfNeeded : <nl> __swift_stdlib_u_strToLower ( <nl> - output . baseAddress . _unsafelyUnwrappedUnchecked , <nl> - Int32 ( output . count ) , <nl> + buffer . baseAddress . _unsafelyUnwrappedUnchecked , <nl> + Int32 ( buffer . count ) , <nl> uChars . baseAddress . _unsafelyUnwrappedUnchecked , <nl> Int32 ( uChars . count ) , <nl> " " , <nl> - & err ) ) <nl> + & error ) ) <nl> + initializedCount = min ( length , uChars . count ) <nl> } <nl> - if len > uChars . count { <nl> - var err = __swift_stdlib_U_ZERO_ERROR <nl> - result = Array < UInt16 > ( repeating : 0 , count : len ) <nl> - result . withUnsafeMutableBufferPointer { <nl> - output - > Void in <nl> + if length > uChars . count { <nl> + var error = __swift_stdlib_U_ZERO_ERROR <nl> + return Array < UInt16 > ( unsafeUninitializedCapacity : length ) { <nl> + buffer , initializedCount in <nl> __swift_stdlib_u_strToLower ( <nl> - output . baseAddress . _unsafelyUnwrappedUnchecked , <nl> - Int32 ( output . count ) , <nl> + buffer . baseAddress . _unsafelyUnwrappedUnchecked , <nl> + Int32 ( buffer . count ) , <nl> uChars . baseAddress . _unsafelyUnwrappedUnchecked , <nl> Int32 ( uChars . count ) , <nl> " " , <nl> - & err ) <nl> + & error ) <nl> + initializedCount = length <nl> } <nl> } <nl> return result <nl> extension String { <nl> / / make UTF - 16 array beforehand <nl> let codeUnits = Array ( self . utf16 ) . withUnsafeBufferPointer { <nl> ( uChars : UnsafeBufferPointer < UInt16 > ) - > Array < UInt16 > in <nl> - var result = Array < UInt16 > ( repeating : 0 , count : uChars . count ) <nl> - let len = result . withUnsafeMutableBufferPointer { <nl> - ( output ) - > Int in <nl> + var length : Int = 0 <nl> + let result = Array < UInt16 > ( unsafeUninitializedCapacity : uChars . count ) { <nl> + buffer , initializedCount in <nl> var err = __swift_stdlib_U_ZERO_ERROR <nl> - return Int ( truncatingIfNeeded : <nl> + length = Int ( truncatingIfNeeded : <nl> __swift_stdlib_u_strToUpper ( <nl> - output . baseAddress . _unsafelyUnwrappedUnchecked , <nl> - Int32 ( output . count ) , <nl> + buffer . baseAddress . _unsafelyUnwrappedUnchecked , <nl> + Int32 ( buffer . count ) , <nl> uChars . baseAddress . _unsafelyUnwrappedUnchecked , <nl> Int32 ( uChars . count ) , <nl> " " , <nl> & err ) ) <nl> + initializedCount = min ( length , uChars . count ) <nl> } <nl> - if len > uChars . count { <nl> + if length > uChars . count { <nl> var err = __swift_stdlib_U_ZERO_ERROR <nl> - result = Array < UInt16 > ( repeating : 0 , count : len ) <nl> - result . withUnsafeMutableBufferPointer { <nl> - output - > Void in <nl> + return Array < UInt16 > ( unsafeUninitializedCapacity : length ) { <nl> + buffer , initializedCount in <nl> __swift_stdlib_u_strToUpper ( <nl> - output . baseAddress . _unsafelyUnwrappedUnchecked , <nl> - Int32 ( output . count ) , <nl> + buffer . baseAddress . _unsafelyUnwrappedUnchecked , <nl> + Int32 ( buffer . count ) , <nl> uChars . baseAddress . _unsafelyUnwrappedUnchecked , <nl> Int32 ( uChars . count ) , <nl> " " , <nl> & err ) <nl> + initializedCount = length <nl> } <nl> } <nl> return result <nl> | Merge remote - tracking branch ' origin / master ' into master - next | apple/swift | 90d7a9d797e5c0b6bb4418ca6c769bc6d8619e33 | 2020-06-09T13:59:35Z |
mmm a / BUILD . gn <nl> ppp b / BUILD . gn <nl> npm_action ( " atom_browserify_sandbox " ) { <nl> ] <nl> <nl> inputs = [ <nl> + # FIXME ( zcbenz ) : The dependencies of these files are not listed here , so <nl> + # the generated file will be out - dated when dependencies are modified . <nl> + # Use a script to generate all dependencies and put them here . <nl> " lib / sandboxed_renderer / init . js " , <nl> " lib / sandboxed_renderer / api / exports / electron . js " , <nl> " lib / sandboxed_renderer / api / exports / fs . js " , <nl> mmm a / atom / renderer / api / atom_api_web_frame . cc <nl> ppp b / atom / renderer / api / atom_api_web_frame . cc <nl> void WebFrame : : SetLayoutZoomLevelLimits ( double min_level , double max_level ) { <nl> } <nl> <nl> v8 : : Local < v8 : : Value > WebFrame : : RegisterEmbedderCustomElement ( <nl> + v8 : : Local < v8 : : Object > context , <nl> const base : : string16 & name , <nl> v8 : : Local < v8 : : Object > options ) { <nl> + v8 : : Context : : Scope context_scope ( context - > CreationContext ( ) ) ; <nl> return web_frame_ - > GetDocument ( ) . RegisterEmbedderCustomElement ( <nl> blink : : WebString : : FromUTF16 ( name ) , options ) ; <nl> } <nl> mmm a / atom / renderer / api / atom_api_web_frame . h <nl> ppp b / atom / renderer / api / atom_api_web_frame . h <nl> class WebFrame : public mate : : Wrappable < WebFrame > { <nl> void SetLayoutZoomLevelLimits ( double min_level , double max_level ) ; <nl> <nl> v8 : : Local < v8 : : Value > RegisterEmbedderCustomElement ( <nl> + v8 : : Local < v8 : : Object > context , <nl> const base : : string16 & name , <nl> v8 : : Local < v8 : : Object > options ) ; <nl> int GetWebFrameId ( v8 : : Local < v8 : : Value > content_window ) ; <nl> mmm a / lib / isolated_renderer / init . js <nl> ppp b / lib / isolated_renderer / init . js <nl> <nl> <nl> / * global nodeProcess , isolatedWorld * / <nl> <nl> + window . isolatedWorld = isolatedWorld <nl> + <nl> / / Note : Don ' t use " process " , as it will be replaced by browserify ' s one . <nl> const v8Util = nodeProcess . atomBinding ( ' v8_util ' ) <nl> <nl> + const setupWebView = v8Util . getHiddenValue ( isolatedWorld , ' setup - webview ' ) <nl> + if ( setupWebView ) { <nl> + setupWebView ( window ) <nl> + } <nl> + <nl> const isolatedWorldArgs = v8Util . getHiddenValue ( isolatedWorld , ' isolated - world - args ' ) <nl> const { ipcRenderer , guestInstanceId , hiddenPage , openerId , usesNativeWindowOpen } = isolatedWorldArgs <nl> <nl> mmm a / lib / renderer / init . js <nl> ppp b / lib / renderer / init . js <nl> if ( window . location . protocol = = = ' chrome - devtools : ' ) { <nl> <nl> / / Load webview tag implementation . <nl> if ( webviewTag & & guestInstanceId = = null ) { <nl> - require ( ' @ electron / internal / renderer / web - view / web - view ' ) <nl> - require ( ' @ electron / internal / renderer / web - view / web - view - attributes ' ) <nl> + const { setupWebView } = require ( ' @ electron / internal / renderer / web - view / web - view ' ) <nl> + if ( contextIsolation ) { <nl> + v8Util . setHiddenValue ( window , ' setup - webview ' , setupWebView ) <nl> + } else { <nl> + setupWebView ( window ) <nl> + } <nl> } <nl> } <nl> <nl> mmm a / lib / renderer / web - view / web - view - attributes . js <nl> ppp b / lib / renderer / web - view / web - view - attributes . js <nl> <nl> ' use strict ' <nl> <nl> const ipcRenderer = require ( ' @ electron / internal / renderer / ipc - renderer - internal ' ) <nl> - const WebViewImpl = require ( ' @ electron / internal / renderer / web - view / web - view ' ) <nl> + const { WebViewImpl } = require ( ' @ electron / internal / renderer / web - view / web - view ' ) <nl> const webViewConstants = require ( ' @ electron / internal / renderer / web - view / web - view - constants ' ) <nl> const errorUtils = require ( ' @ electron / internal / common / error - utils ' ) <nl> <nl> class PartitionAttribute extends WebViewAttribute { <nl> <nl> / / The partition cannot change if the webview has already navigated . <nl> if ( ! this . webViewImpl . beforeFirstNavigation ) { <nl> - window . console . error ( webViewConstants . ERROR_MSG_ALREADY_NAVIGATED ) <nl> + console . error ( webViewConstants . ERROR_MSG_ALREADY_NAVIGATED ) <nl> this . setValueIgnoreMutation ( oldValue ) <nl> return <nl> } <nl> if ( newValue = = = ' persist : ' ) { <nl> this . validPartitionId = false <nl> - window . console . error ( webViewConstants . ERROR_MSG_INVALID_PARTITION_ATTRIBUTE ) <nl> + console . error ( webViewConstants . ERROR_MSG_INVALID_PARTITION_ATTRIBUTE ) <nl> } <nl> } <nl> } <nl> mmm a / lib / renderer / web - view / web - view . js <nl> ppp b / lib / renderer / web - view / web - view . js <nl> class WebViewImpl { <nl> } <nl> <nl> / / Registers < webview > custom element . <nl> - const registerWebViewElement = function ( ) { <nl> - const proto = Object . create ( HTMLObjectElement . prototype ) <nl> + const registerWebViewElement = ( window ) = > { <nl> + const proto = Object . create ( window . HTMLObjectElement . prototype ) <nl> proto . createdCallback = function ( ) { <nl> return new WebViewImpl ( this ) <nl> } <nl> const registerWebViewElement = function ( ) { <nl> this . contentWindow . focus ( ) <nl> } <nl> <nl> - window . WebView = webFrame . registerEmbedderCustomElement ( ' webview ' , { <nl> + window . WebView = webFrame . registerEmbedderCustomElement ( window , ' webview ' , { <nl> prototype : proto <nl> } ) <nl> <nl> const registerWebViewElement = function ( ) { <nl> delete proto . attributeChangedCallback <nl> } <nl> <nl> - const useCapture = true <nl> + const setupWebView = ( window ) = > { <nl> + require ( ' @ electron / internal / renderer / web - view / web - view - attributes ' ) <nl> <nl> - const listener = function ( event ) { <nl> - if ( document . readyState = = = ' loading ' ) { <nl> - return <nl> - } <nl> - registerWebViewElement ( ) <nl> - window . removeEventListener ( event . type , listener , useCapture ) <nl> + const useCapture = true <nl> + window . addEventListener ( ' readystatechange ' , function listener ( event ) { <nl> + if ( document . readyState = = = ' loading ' ) { <nl> + return <nl> + } <nl> + registerWebViewElement ( window ) <nl> + window . removeEventListener ( event . type , listener , useCapture ) <nl> + } , useCapture ) <nl> } <nl> <nl> - window . addEventListener ( ' readystatechange ' , listener , true ) <nl> - <nl> - module . exports = WebViewImpl <nl> + module . exports = { setupWebView , WebViewImpl } <nl> mmm a / lib / sandboxed_renderer / init . js <nl> ppp b / lib / sandboxed_renderer / init . js <nl> if ( binding . guestInstanceId ) { <nl> <nl> if ( ! process . guestInstanceId & & preloadProcess . argv . includes ( ' - - webview - tag = true ' ) ) { <nl> / / don ' t allow recursive ` < webview > ` <nl> - require ( ' @ electron / internal / renderer / web - view / web - view ' ) <nl> - require ( ' @ electron / internal / renderer / web - view / web - view - attributes ' ) <nl> + require ( ' @ electron / internal / renderer / web - view / web - view ' ) . setupWebView ( window ) <nl> } <nl> <nl> / / Wrap the script into a function executed in global scope . It won ' t have <nl> new file mode 100644 <nl> index 000000000000 . . 7088d346c8ef <nl> mmm / dev / null <nl> ppp b / spec / fixtures / module / isolated - ping . js <nl> <nl> + const { ipcRenderer } = require ( ' electron ' ) <nl> + ipcRenderer . send ( ' pong ' ) <nl> new file mode 100644 <nl> index 000000000000 . . 824118b572cf <nl> mmm / dev / null <nl> ppp b / spec / fixtures / pages / webview - isolated . html <nl> <nl> + < html > <nl> + < body > <nl> + < webview preload = " . . / module / isolated - ping . js " src = " about : blank " / > <nl> + < / body > <nl> + < / html > <nl> mmm a / spec / webview - spec . js <nl> ppp b / spec / webview - spec . js <nl> describe ( ' < webview > tag ' , function ( ) { <nl> await emittedOnce ( ipcMain , ' pong ' ) <nl> } ) <nl> <nl> + it ( ' works with contextIsolation ' , async ( ) = > { <nl> + const w = await openTheWindow ( { <nl> + show : false , <nl> + webPreferences : { <nl> + webviewTag : true , <nl> + contextIsolation : true <nl> + } <nl> + } ) <nl> + w . loadFile ( path . join ( fixtures , ' pages ' , ' webview - isolated . html ' ) ) <nl> + await emittedOnce ( ipcMain , ' pong ' ) <nl> + } ) <nl> + <nl> it ( ' is disabled when nodeIntegration is disabled ' , async ( ) = > { <nl> const w = await openTheWindow ( { <nl> show : false , <nl> | fix : register webview in main world when using contextIsolation ( ) | electron/electron | 8584c2f14b8be9e5b806330f16b1ad705e778d5e | 2018-12-14T06:38:35Z |
mmm a / docs / index . md <nl> ppp b / docs / index . md <nl> Caffe aims to provide computer vision scientists and practitioners with a * * clea <nl> For example , network structure is easily specified in separate config files , with no mess of hard - coded parameters in the code . <nl> <nl> At the same time , Caffe fits industry needs , with blazing fast C + + / CUDA code for GPU computation . <nl> - Caffe is currently the fastest GPU CNN implementation publicly available , and is able to process more than * * 40 million images per day * * with a single K40 or Titan NVidia Card ( 20 million images per day on a single Tesla K20 NVidia Card ) \ * . Currently , caffe can process 192 images per second during training and 500 images per second during test ( using K40 or Titan ) \ * . <nl> + Caffe is currently the fastest GPU CNN implementation publicly available , and is able to process more than * * 40 million images per day * * with a single K40 or Titan NVidia Card ( 20 million images per day on a single Tesla K20 NVidia Card ) \ * . Currently , caffe can process 192 images per second during training and 500 images per second during test ( using K40 or Titan ) ( see [ Performance , Hardware tips ] ( / perfomance_hardware . html ) ) \ * . <nl> <nl> Caffe also provides * * seamless switching between CPU and GPU * * , which allows one to train models with fast GPUs and then deploy them on non - GPU clusters with one line of code : ` Caffe : : set_mode ( Caffe : : CPU ) ` . <nl> Even in CPU mode , computing predictions on an image takes only 20 ms when images are processed in batch mode . While in GPU mode , computing predictions on an image takes only 2 ms when images are processed in batch mode . <nl> | Added Link in index . md to perfomance_hardware . md | BVLC/caffe | 9ec6ca0bde863eaa333fbc3c1aa13cbe845b4c23 | 2014-04-03T00:03:25Z |
mmm a / src / mongo / db / commands / find_cmd . cpp <nl> ppp b / src / mongo / db / commands / find_cmd . cpp <nl> const auto kTermField = " term " _sd ; <nl> / * * <nl> * A command for running . find ( ) queries . <nl> * / <nl> - class FindCmd : public BasicCommand { <nl> + class FindCmd final : public Command { <nl> public : <nl> - FindCmd ( ) : BasicCommand ( " find " ) { } <nl> + FindCmd ( ) : Command ( " find " ) { } <nl> <nl> - bool supportsWriteConcern ( const BSONObj & cmd ) const override { <nl> - return false ; <nl> + std : : unique_ptr < CommandInvocation > parse ( OperationContext * opCtx , <nl> + const OpMsgRequest & opMsgRequest ) override { <nl> + / / TODO : Parse into a QueryRequest here . <nl> + return std : : make_unique < Invocation > ( this , opMsgRequest , opMsgRequest . getDatabase ( ) ) ; <nl> } <nl> <nl> - AllowedOnSecondary secondaryAllowed ( ServiceContext * ) const override { <nl> + AllowedOnSecondary secondaryAllowed ( ServiceContext * context ) const override { <nl> return AllowedOnSecondary : : kOptIn ; <nl> } <nl> <nl> class FindCmd : public BasicCommand { <nl> return false ; <nl> } <nl> <nl> - bool supportsReadConcern ( const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - repl : : ReadConcernLevel level ) const final { <nl> - return true ; <nl> - } <nl> - <nl> std : : string help ( ) const override { <nl> return " query for documents " ; <nl> } <nl> class FindCmd : public BasicCommand { <nl> return false ; <nl> } <nl> <nl> - Status checkAuthForOperation ( OperationContext * opCtx , <nl> - const std : : string & dbname , <nl> - const BSONObj & cmdObj ) const override { <nl> - AuthorizationSession * authSession = AuthorizationSession : : get ( opCtx - > getClient ( ) ) ; <nl> + class Invocation final : public CommandInvocation { <nl> + public : <nl> + Invocation ( const FindCmd * definition , const OpMsgRequest & request , StringData dbName ) <nl> + : CommandInvocation ( definition ) , _request ( request ) , _dbName ( dbName ) { } <nl> <nl> - if ( ! authSession - > isAuthorizedToParseNamespaceElement ( cmdObj . firstElement ( ) ) ) { <nl> - return Status ( ErrorCodes : : Unauthorized , " Unauthorized " ) ; <nl> + private : <nl> + bool supportsWriteConcern ( ) const override { <nl> + return false ; <nl> } <nl> <nl> - const auto hasTerm = cmdObj . hasField ( kTermField ) ; <nl> - return authSession - > checkAuthForFind ( <nl> - AutoGetCollection : : resolveNamespaceStringOrUUID ( <nl> - opCtx , CommandHelpers : : parseNsOrUUID ( dbname , cmdObj ) ) , <nl> - hasTerm ) ; <nl> - } <nl> + bool supportsReadConcern ( repl : : ReadConcernLevel level ) const final { <nl> + return true ; <nl> + } <nl> <nl> - Status explain ( OperationContext * opCtx , <nl> - const OpMsgRequest & request , <nl> - ExplainOptions : : Verbosity verbosity , <nl> - BSONObjBuilder * out ) const override { <nl> - std : : string dbname = request . getDatabase ( ) . toString ( ) ; <nl> - const BSONObj & cmdObj = request . body ; <nl> - / / Acquire locks and resolve possible UUID . The RAII object is optional , because in the case <nl> - / / of a view , the locks need to be released . <nl> - boost : : optional < AutoGetCollectionForReadCommand > ctx ; <nl> - ctx . emplace ( opCtx , <nl> - CommandHelpers : : parseNsOrUUID ( dbname , cmdObj ) , <nl> - AutoGetCollection : : ViewMode : : kViewsPermitted ) ; <nl> - const auto nss = ctx - > getNss ( ) ; <nl> - <nl> - / / Parse the command BSON to a QueryRequest . <nl> - const bool isExplain = true ; <nl> - auto qrStatus = QueryRequest : : makeFromFindCommand ( nss , cmdObj , isExplain ) ; <nl> - if ( ! qrStatus . isOK ( ) ) { <nl> - return qrStatus . getStatus ( ) ; <nl> + NamespaceString ns ( ) const override { <nl> + / / TODO get the ns from the parsed QueryRequest . <nl> + return NamespaceString ( CommandHelpers : : parseNsFromCommand ( _dbName , _request . body ) ) ; <nl> } <nl> <nl> - / / Finish the parsing step by using the QueryRequest to create a CanonicalQuery . <nl> - const ExtensionsCallbackReal extensionsCallback ( opCtx , & nss ) ; <nl> - const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> - auto statusWithCQ = <nl> - CanonicalQuery : : canonicalize ( opCtx , <nl> - std : : move ( qrStatus . getValue ( ) ) , <nl> - expCtx , <nl> - extensionsCallback , <nl> - MatchExpressionParser : : kAllowAllSpecialFeatures ) ; <nl> - if ( ! statusWithCQ . isOK ( ) ) { <nl> - return statusWithCQ . getStatus ( ) ; <nl> + void doCheckAuthorization ( OperationContext * opCtx ) const final { <nl> + AuthorizationSession * authSession = AuthorizationSession : : get ( opCtx - > getClient ( ) ) ; <nl> + <nl> + uassert ( ErrorCodes : : Unauthorized , <nl> + " Unauthorized " , <nl> + authSession - > isAuthorizedToParseNamespaceElement ( _request . body . firstElement ( ) ) ) ; <nl> + <nl> + const auto hasTerm = _request . body . hasField ( kTermField ) ; <nl> + uassertStatusOK ( authSession - > checkAuthForFind ( <nl> + AutoGetCollection : : resolveNamespaceStringOrUUID ( <nl> + opCtx , CommandHelpers : : parseNsOrUUID ( _dbName , _request . body ) ) , <nl> + hasTerm ) ) ; <nl> } <nl> - std : : unique_ptr < CanonicalQuery > cq = std : : move ( statusWithCQ . getValue ( ) ) ; <nl> - <nl> - if ( ctx - > getView ( ) ) { <nl> - / / Relinquish locks . The aggregation command will re - acquire them . <nl> - ctx . reset ( ) ; <nl> - <nl> - / / Convert the find command into an aggregation using $ match ( and other stages , as <nl> - / / necessary ) , if possible . <nl> - const auto & qr = cq - > getQueryRequest ( ) ; <nl> - auto viewAggregationCommand = qr . asAggregationCommand ( ) ; <nl> - if ( ! viewAggregationCommand . isOK ( ) ) <nl> - return viewAggregationCommand . getStatus ( ) ; <nl> - <nl> - / / Create the agg request equivalent of the find operation , with the explain verbosity <nl> - / / included . <nl> - auto aggRequest = AggregationRequest : : parseFromBSON ( <nl> - nss , viewAggregationCommand . getValue ( ) , verbosity ) ; <nl> - if ( ! aggRequest . isOK ( ) ) { <nl> - return aggRequest . getStatus ( ) ; <nl> - } <nl> <nl> - try { <nl> - return runAggregate ( <nl> - opCtx , nss , aggRequest . getValue ( ) , viewAggregationCommand . getValue ( ) , * out ) ; <nl> - } catch ( DBException & error ) { <nl> - if ( error . code ( ) = = ErrorCodes : : InvalidPipelineOperator ) { <nl> - return { ErrorCodes : : InvalidPipelineOperator , <nl> - str : : stream ( ) < < " Unsupported in view pipeline : " < < error . what ( ) } ; <nl> + void explain ( OperationContext * opCtx , <nl> + ExplainOptions : : Verbosity verbosity , <nl> + BSONObjBuilder * result ) override { <nl> + / / Acquire locks and resolve possible UUID . The RAII object is optional , because in the <nl> + / / case of a view , the locks need to be released . <nl> + boost : : optional < AutoGetCollectionForReadCommand > ctx ; <nl> + ctx . emplace ( opCtx , <nl> + CommandHelpers : : parseNsOrUUID ( _dbName , _request . body ) , <nl> + AutoGetCollection : : ViewMode : : kViewsPermitted ) ; <nl> + const auto nss = ctx - > getNss ( ) ; <nl> + <nl> + / / Parse the command BSON to a QueryRequest . <nl> + const bool isExplain = true ; <nl> + auto qr = <nl> + uassertStatusOK ( QueryRequest : : makeFromFindCommand ( nss , _request . body , isExplain ) ) ; <nl> + <nl> + / / Finish the parsing step by using the QueryRequest to create a CanonicalQuery . <nl> + const ExtensionsCallbackReal extensionsCallback ( opCtx , & nss ) ; <nl> + const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> + auto cq = uassertStatusOK ( <nl> + CanonicalQuery : : canonicalize ( opCtx , <nl> + std : : move ( qr ) , <nl> + expCtx , <nl> + extensionsCallback , <nl> + MatchExpressionParser : : kAllowAllSpecialFeatures ) ) ; <nl> + <nl> + if ( ctx - > getView ( ) ) { <nl> + / / Relinquish locks . The aggregation command will re - acquire them . <nl> + ctx . reset ( ) ; <nl> + <nl> + / / Convert the find command into an aggregation using $ match ( and other stages , as <nl> + / / necessary ) , if possible . <nl> + const auto & qr = cq - > getQueryRequest ( ) ; <nl> + auto viewAggregationCommand = uassertStatusOK ( qr . asAggregationCommand ( ) ) ; <nl> + <nl> + / / Create the agg request equivalent of the find operation , with the explain <nl> + / / verbosity included . <nl> + auto aggRequest = uassertStatusOK ( <nl> + AggregationRequest : : parseFromBSON ( nss , viewAggregationCommand , verbosity ) ) ; <nl> + <nl> + try { <nl> + uassertStatusOK ( <nl> + runAggregate ( opCtx , nss , aggRequest , viewAggregationCommand , * result ) ) ; <nl> + } catch ( DBException & error ) { <nl> + if ( error . code ( ) = = ErrorCodes : : InvalidPipelineOperator ) { <nl> + uasserted ( ErrorCodes : : InvalidPipelineOperator , <nl> + str : : stream ( ) < < " Unsupported in view pipeline : " <nl> + < < error . what ( ) ) ; <nl> + } <nl> + throw ; <nl> } <nl> - return error . toStatus ( ) ; <nl> + return ; <nl> } <nl> - } <nl> <nl> - / / The collection may be NULL . If so , getExecutor ( ) should handle it by returning an <nl> - / / execution tree with an EOFStage . <nl> - Collection * const collection = ctx - > getCollection ( ) ; <nl> + / / The collection may be NULL . If so , getExecutor ( ) should handle it by returning an <nl> + / / execution tree with an EOFStage . <nl> + Collection * const collection = ctx - > getCollection ( ) ; <nl> <nl> - / / We have a parsed query . Time to get the execution plan for it . <nl> - auto statusWithPlanExecutor = getExecutorFind ( opCtx , collection , nss , std : : move ( cq ) ) ; <nl> - if ( ! statusWithPlanExecutor . isOK ( ) ) { <nl> - return statusWithPlanExecutor . getStatus ( ) ; <nl> - } <nl> - auto exec = std : : move ( statusWithPlanExecutor . getValue ( ) ) ; <nl> + / / We have a parsed query . Time to get the execution plan for it . <nl> + auto exec = uassertStatusOK ( getExecutorFind ( opCtx , collection , nss , std : : move ( cq ) ) ) ; <nl> <nl> - / / Got the execution tree . Explain it . <nl> - Explain : : explainStages ( exec . get ( ) , collection , verbosity , out ) ; <nl> - return Status : : OK ( ) ; <nl> - } <nl> - <nl> - / * * <nl> - * Runs a query using the following steps : <nl> - * - - Parsing . <nl> - * - - Acquire locks . <nl> - * - - Plan query , obtaining an executor that can run it . <nl> - * - - Generate the first batch . <nl> - * - - Save state for getMore , transferring ownership of the executor to a ClientCursor . <nl> - * - - Generate response to send to the client . <nl> - * / <nl> - bool run ( OperationContext * opCtx , <nl> - const std : : string & dbname , <nl> - const BSONObj & cmdObj , <nl> - BSONObjBuilder & result ) override { <nl> - / / Although it is a command , a find command gets counted as a query . <nl> - globalOpCounters . gotQuery ( ) ; <nl> - <nl> - / / Parse the command BSON to a QueryRequest . <nl> - const bool isExplain = false ; <nl> - / / Pass parseNs to makeFromFindCommand in case cmdObj does not have a UUID . <nl> - auto qrStatus = QueryRequest : : makeFromFindCommand ( <nl> - NamespaceString ( parseNs ( dbname , cmdObj ) ) , cmdObj , isExplain ) ; <nl> - uassertStatusOK ( qrStatus . getStatus ( ) ) ; <nl> - <nl> - auto replCoord = repl : : ReplicationCoordinator : : get ( opCtx ) ; <nl> - auto & qr = qrStatus . getValue ( ) ; <nl> - const auto session = OperationContextSession : : get ( opCtx ) ; <nl> - uassert ( ErrorCodes : : InvalidOptions , <nl> - " It is illegal to open a tailable cursor in a transaction " , <nl> - session = = nullptr | | ! ( session - > inMultiDocumentTransaction ( ) & & qr - > isTailable ( ) ) ) ; <nl> - <nl> - / / Validate term before acquiring locks , if provided . <nl> - if ( auto term = qr - > getReplicationTerm ( ) ) { <nl> - Status status = replCoord - > updateTerm ( opCtx , * term ) ; <nl> - / / Note : updateTerm returns ok if term stayed the same . <nl> - uassertStatusOK ( status ) ; <nl> + / / Got the execution tree . Explain it . <nl> + Explain : : explainStages ( exec . get ( ) , collection , verbosity , result ) ; <nl> } <nl> <nl> - / / Acquire locks . If the query is on a view , we release our locks and convert the query <nl> - / / request into an aggregation command . <nl> - boost : : optional < AutoGetCollectionForReadCommand > ctx ; <nl> - ctx . emplace ( opCtx , <nl> - CommandHelpers : : parseNsOrUUID ( dbname , cmdObj ) , <nl> - AutoGetCollection : : ViewMode : : kViewsPermitted ) ; <nl> - const auto & nss = ctx - > getNss ( ) ; <nl> - <nl> - qr - > refreshNSS ( opCtx ) ; <nl> - <nl> - / / Check whether we are allowed to read from this node after acquiring our locks . <nl> - uassertStatusOK ( replCoord - > checkCanServeReadsFor ( <nl> - opCtx , nss , ReadPreferenceSetting : : get ( opCtx ) . canRunOnSecondary ( ) ) ) ; <nl> - <nl> - / / Fill out curop information . <nl> - / / <nl> - / / We pass negative values for ' ntoreturn ' and ' ntoskip ' to indicate that these values <nl> - / / should be omitted from the log line . Limit and skip information is already present in the <nl> - / / find command parameters , so these fields are redundant . <nl> - const int ntoreturn = - 1 ; <nl> - const int ntoskip = - 1 ; <nl> - beginQueryOp ( opCtx , nss , cmdObj , ntoreturn , ntoskip ) ; <nl> - <nl> - / / Finish the parsing step by using the QueryRequest to create a CanonicalQuery . <nl> - const ExtensionsCallbackReal extensionsCallback ( opCtx , & nss ) ; <nl> - const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> - auto statusWithCQ = <nl> - CanonicalQuery : : canonicalize ( opCtx , <nl> - std : : move ( qr ) , <nl> - expCtx , <nl> - extensionsCallback , <nl> - MatchExpressionParser : : kAllowAllSpecialFeatures ) ; <nl> - uassertStatusOK ( statusWithCQ . getStatus ( ) ) ; <nl> - std : : unique_ptr < CanonicalQuery > cq = std : : move ( statusWithCQ . getValue ( ) ) ; <nl> - <nl> - if ( ctx - > getView ( ) ) { <nl> - / / Relinquish locks . The aggregation command will re - acquire them . <nl> - ctx . reset ( ) ; <nl> - <nl> - / / Convert the find command into an aggregation using $ match ( and other stages , as <nl> - / / necessary ) , if possible . <nl> - const auto & qr = cq - > getQueryRequest ( ) ; <nl> - auto viewAggregationCommand = qr . asAggregationCommand ( ) ; <nl> - uassertStatusOK ( viewAggregationCommand . getStatus ( ) ) ; <nl> - <nl> - BSONObj aggResult = CommandHelpers : : runCommandDirectly ( <nl> - opCtx , <nl> - OpMsgRequest : : fromDBAndBody ( dbname , std : : move ( viewAggregationCommand . getValue ( ) ) ) ) ; <nl> - auto status = getStatusFromCommandResult ( aggResult ) ; <nl> - if ( status . code ( ) = = ErrorCodes : : InvalidPipelineOperator ) { <nl> - uasserted ( ErrorCodes : : InvalidPipelineOperator , <nl> - str : : stream ( ) < < " Unsupported in view pipeline : " < < status . reason ( ) ) ; <nl> + / * * <nl> + * Runs a query using the following steps : <nl> + * - - Parsing . <nl> + * - - Acquire locks . <nl> + * - - Plan query , obtaining an executor that can run it . <nl> + * - - Generate the first batch . <nl> + * - - Save state for getMore , transferring ownership of the executor to a ClientCursor . <nl> + * - - Generate response to send to the client . <nl> + * / <nl> + void run ( OperationContext * opCtx , rpc : : ReplyBuilderInterface * result ) { <nl> + / / Although it is a command , a find command gets counted as a query . <nl> + globalOpCounters . gotQuery ( ) ; <nl> + <nl> + / / Parse the command BSON to a QueryRequest . <nl> + const bool isExplain = false ; <nl> + / / Pass parseNs to makeFromFindCommand in case _request . body does not have a UUID . <nl> + auto qr = uassertStatusOK ( QueryRequest : : makeFromFindCommand ( <nl> + NamespaceString ( CommandHelpers : : parseNsFromCommand ( _dbName , _request . body ) ) , <nl> + _request . body , <nl> + isExplain ) ) ; <nl> + <nl> + auto replCoord = repl : : ReplicationCoordinator : : get ( opCtx ) ; <nl> + const auto session = OperationContextSession : : get ( opCtx ) ; <nl> + uassert ( ErrorCodes : : InvalidOptions , <nl> + " It is illegal to open a tailable cursor in a transaction " , <nl> + session = = nullptr | | <nl> + ! ( session - > inMultiDocumentTransaction ( ) & & qr - > isTailable ( ) ) ) ; <nl> + <nl> + / / Validate term before acquiring locks , if provided . <nl> + if ( auto term = qr - > getReplicationTerm ( ) ) { <nl> + / / Note : updateTerm returns ok if term stayed the same . <nl> + uassertStatusOK ( replCoord - > updateTerm ( opCtx , * term ) ) ; <nl> } <nl> - result . resetToEmpty ( ) ; <nl> - result . appendElements ( aggResult ) ; <nl> - return status . isOK ( ) ; <nl> - } <nl> <nl> - Collection * const collection = ctx - > getCollection ( ) ; <nl> + / / Acquire locks . If the query is on a view , we release our locks and convert the query <nl> + / / request into an aggregation command . <nl> + boost : : optional < AutoGetCollectionForReadCommand > ctx ; <nl> + ctx . emplace ( opCtx , <nl> + CommandHelpers : : parseNsOrUUID ( _dbName , _request . body ) , <nl> + AutoGetCollection : : ViewMode : : kViewsPermitted ) ; <nl> + const auto & nss = ctx - > getNss ( ) ; <nl> + <nl> + qr - > refreshNSS ( opCtx ) ; <nl> + <nl> + / / Check whether we are allowed to read from this node after acquiring our locks . <nl> + uassertStatusOK ( replCoord - > checkCanServeReadsFor ( <nl> + opCtx , nss , ReadPreferenceSetting : : get ( opCtx ) . canRunOnSecondary ( ) ) ) ; <nl> + <nl> + / / Fill out curop information . <nl> + / / <nl> + / / We pass negative values for ' ntoreturn ' and ' ntoskip ' to indicate that these values <nl> + / / should be omitted from the log line . Limit and skip information is already present in <nl> + / / the find command parameters , so these fields are redundant . <nl> + const int ntoreturn = - 1 ; <nl> + const int ntoskip = - 1 ; <nl> + beginQueryOp ( opCtx , nss , _request . body , ntoreturn , ntoskip ) ; <nl> + <nl> + / / Finish the parsing step by using the QueryRequest to create a CanonicalQuery . <nl> + const ExtensionsCallbackReal extensionsCallback ( opCtx , & nss ) ; <nl> + const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> + auto cq = uassertStatusOK ( <nl> + CanonicalQuery : : canonicalize ( opCtx , <nl> + std : : move ( qr ) , <nl> + expCtx , <nl> + extensionsCallback , <nl> + MatchExpressionParser : : kAllowAllSpecialFeatures ) ) ; <nl> + <nl> + if ( ctx - > getView ( ) ) { <nl> + / / Relinquish locks . The aggregation command will re - acquire them . <nl> + ctx . reset ( ) ; <nl> + <nl> + / / Convert the find command into an aggregation using $ match ( and other stages , as <nl> + / / necessary ) , if possible . <nl> + const auto & qr = cq - > getQueryRequest ( ) ; <nl> + auto viewAggregationCommand = uassertStatusOK ( qr . asAggregationCommand ( ) ) ; <nl> + <nl> + BSONObj aggResult = CommandHelpers : : runCommandDirectly ( <nl> + opCtx , OpMsgRequest : : fromDBAndBody ( _dbName , std : : move ( viewAggregationCommand ) ) ) ; <nl> + auto status = getStatusFromCommandResult ( aggResult ) ; <nl> + if ( status . code ( ) = = ErrorCodes : : InvalidPipelineOperator ) { <nl> + uasserted ( ErrorCodes : : InvalidPipelineOperator , <nl> + str : : stream ( ) < < " Unsupported in view pipeline : " < < status . reason ( ) ) ; <nl> + } <nl> + uassertStatusOK ( status ) ; <nl> + result - > getBodyBuilder ( ) . appendElements ( aggResult ) ; <nl> + return ; <nl> + } <nl> <nl> - / / Get the execution plan for the query . <nl> - auto statusWithPlanExecutor = getExecutorFind ( opCtx , collection , nss , std : : move ( cq ) ) ; <nl> - uassertStatusOK ( statusWithPlanExecutor . getStatus ( ) ) ; <nl> + Collection * const collection = ctx - > getCollection ( ) ; <nl> <nl> - auto exec = std : : move ( statusWithPlanExecutor . getValue ( ) ) ; <nl> + / / Get the execution plan for the query . <nl> + auto exec = uassertStatusOK ( getExecutorFind ( opCtx , collection , nss , std : : move ( cq ) ) ) ; <nl> <nl> - { <nl> - stdx : : lock_guard < Client > lk ( * opCtx - > getClient ( ) ) ; <nl> - CurOp : : get ( opCtx ) - > setPlanSummary_inlock ( Explain : : getPlanSummary ( exec . get ( ) ) ) ; <nl> - } <nl> + { <nl> + stdx : : lock_guard < Client > lk ( * opCtx - > getClient ( ) ) ; <nl> + CurOp : : get ( opCtx ) - > setPlanSummary_inlock ( Explain : : getPlanSummary ( exec . get ( ) ) ) ; <nl> + } <nl> <nl> - if ( ! collection ) { <nl> - / / No collection . Just fill out curop indicating that there were zero results and <nl> - / / there is no ClientCursor id , and then return . <nl> - const long long numResults = 0 ; <nl> - const CursorId cursorId = 0 ; <nl> - endQueryOp ( opCtx , collection , * exec , numResults , cursorId ) ; <nl> - appendCursorResponseObject ( cursorId , nss . ns ( ) , BSONArray ( ) , & result ) ; <nl> - return true ; <nl> - } <nl> + if ( ! collection ) { <nl> + / / No collection . Just fill out curop indicating that there were zero results and <nl> + / / there is no ClientCursor id , and then return . <nl> + const long long numResults = 0 ; <nl> + const CursorId cursorId = 0 ; <nl> + endQueryOp ( opCtx , collection , * exec , numResults , cursorId ) ; <nl> + auto bodyBuilder = result - > getBodyBuilder ( ) ; <nl> + appendCursorResponseObject ( cursorId , nss . ns ( ) , BSONArray ( ) , & bodyBuilder ) ; <nl> + return ; <nl> + } <nl> <nl> - CurOpFailpointHelpers : : waitWhileFailPointEnabled ( <nl> - & waitInFindBeforeMakingBatch , opCtx , " waitInFindBeforeMakingBatch " ) ; <nl> - <nl> - const QueryRequest & originalQR = exec - > getCanonicalQuery ( ) - > getQueryRequest ( ) ; <nl> - <nl> - / / Stream query results , adding them to a BSONArray as we go . <nl> - CursorResponseBuilder firstBatch ( / * isInitialResponse * / true , & result ) ; <nl> - BSONObj obj ; <nl> - PlanExecutor : : ExecState state = PlanExecutor : : ADVANCED ; <nl> - long long numResults = 0 ; <nl> - while ( ! FindCommon : : enoughForFirstBatch ( originalQR , numResults ) & & <nl> - PlanExecutor : : ADVANCED = = ( state = exec - > getNext ( & obj , NULL ) ) ) { <nl> - / / If we can ' t fit this result inside the current batch , then we stash it for later . <nl> - if ( ! FindCommon : : haveSpaceForNext ( obj , numResults , firstBatch . bytesUsed ( ) ) ) { <nl> - exec - > enqueue ( obj ) ; <nl> - break ; <nl> + CurOpFailpointHelpers : : waitWhileFailPointEnabled ( <nl> + & waitInFindBeforeMakingBatch , opCtx , " waitInFindBeforeMakingBatch " ) ; <nl> + <nl> + const QueryRequest & originalQR = exec - > getCanonicalQuery ( ) - > getQueryRequest ( ) ; <nl> + <nl> + / / Stream query results , adding them to a BSONArray as we go . <nl> + auto bodyBuilder = result - > getBodyBuilder ( ) ; <nl> + CursorResponseBuilder firstBatch ( / * isInitialResponse * / true , & bodyBuilder ) ; <nl> + BSONObj obj ; <nl> + PlanExecutor : : ExecState state = PlanExecutor : : ADVANCED ; <nl> + long long numResults = 0 ; <nl> + while ( ! FindCommon : : enoughForFirstBatch ( originalQR , numResults ) & & <nl> + PlanExecutor : : ADVANCED = = ( state = exec - > getNext ( & obj , nullptr ) ) ) { <nl> + / / If we can ' t fit this result inside the current batch , then we stash it for later . <nl> + if ( ! FindCommon : : haveSpaceForNext ( obj , numResults , firstBatch . bytesUsed ( ) ) ) { <nl> + exec - > enqueue ( obj ) ; <nl> + break ; <nl> + } <nl> + <nl> + / / Add result to output buffer . <nl> + firstBatch . append ( obj ) ; <nl> + numResults + + ; <nl> } <nl> <nl> - / / Add result to output buffer . <nl> - firstBatch . append ( obj ) ; <nl> - numResults + + ; <nl> - } <nl> + / / Throw an assertion if query execution fails for any reason . <nl> + if ( PlanExecutor : : FAILURE = = state | | PlanExecutor : : DEAD = = state ) { <nl> + firstBatch . abandon ( ) ; <nl> + error ( ) < < " Plan executor error during find command : " <nl> + < < PlanExecutor : : statestr ( state ) <nl> + < < " , stats : " < < redact ( Explain : : getWinningPlanStats ( exec . get ( ) ) ) ; <nl> <nl> - / / Throw an assertion if query execution fails for any reason . <nl> - if ( PlanExecutor : : FAILURE = = state | | PlanExecutor : : DEAD = = state ) { <nl> - firstBatch . abandon ( ) ; <nl> - error ( ) < < " Plan executor error during find command : " < < PlanExecutor : : statestr ( state ) <nl> - < < " , stats : " < < redact ( Explain : : getWinningPlanStats ( exec . get ( ) ) ) ; <nl> + uassertStatusOK ( WorkingSetCommon : : getMemberObjectStatus ( obj ) . withContext ( <nl> + " Executor error during find command " ) ) ; <nl> + } <nl> <nl> - uassertStatusOK ( WorkingSetCommon : : getMemberObjectStatus ( obj ) . withContext ( <nl> - " Executor error during find command " ) ) ; <nl> - } <nl> + / / Before saving the cursor , ensure that whatever plan we established happened with the <nl> + / / expected collection version <nl> + auto css = CollectionShardingState : : get ( opCtx , nss ) ; <nl> + css - > checkShardVersionOrThrow ( opCtx ) ; <nl> + <nl> + / / Set up the cursor for getMore . <nl> + CursorId cursorId = 0 ; <nl> + if ( shouldSaveCursor ( opCtx , collection , state , exec . get ( ) ) ) { <nl> + / / Create a ClientCursor containing this plan executor and register it with the <nl> + / / cursor manager . <nl> + ClientCursorPin pinnedCursor = collection - > getCursorManager ( ) - > registerCursor ( <nl> + opCtx , <nl> + { std : : move ( exec ) , <nl> + nss , <nl> + AuthorizationSession : : get ( opCtx - > getClient ( ) ) - > getAuthenticatedUserNames ( ) , <nl> + repl : : ReadConcernArgs : : get ( opCtx ) . getLevel ( ) , <nl> + _request . body } ) ; <nl> + cursorId = pinnedCursor . getCursor ( ) - > cursorid ( ) ; <nl> + <nl> + invariant ( ! exec ) ; <nl> + PlanExecutor * cursorExec = pinnedCursor . getCursor ( ) - > getExecutor ( ) ; <nl> + <nl> + / / State will be restored on getMore . <nl> + cursorExec - > saveState ( ) ; <nl> + cursorExec - > detachFromOperationContext ( ) ; <nl> + <nl> + / / We assume that cursors created through a DBDirectClient are always used from <nl> + / / their original OperationContext , so we do not need to move time to and from the <nl> + / / cursor . <nl> + if ( ! opCtx - > getClient ( ) - > isInDirectClient ( ) ) { <nl> + pinnedCursor . getCursor ( ) - > setLeftoverMaxTimeMicros ( <nl> + opCtx - > getRemainingMaxTimeMicros ( ) ) ; <nl> + } <nl> + pinnedCursor . getCursor ( ) - > setPos ( numResults ) ; <nl> <nl> - / / Before saving the cursor , ensure that whatever plan we established happened with the <nl> - / / expected collection version <nl> - auto css = CollectionShardingState : : get ( opCtx , nss ) ; <nl> - css - > checkShardVersionOrThrow ( opCtx ) ; <nl> - <nl> - / / Set up the cursor for getMore . <nl> - CursorId cursorId = 0 ; <nl> - if ( shouldSaveCursor ( opCtx , collection , state , exec . get ( ) ) ) { <nl> - / / Create a ClientCursor containing this plan executor and register it with the cursor <nl> - / / manager . <nl> - ClientCursorPin pinnedCursor = collection - > getCursorManager ( ) - > registerCursor ( <nl> - opCtx , <nl> - { std : : move ( exec ) , <nl> - nss , <nl> - AuthorizationSession : : get ( opCtx - > getClient ( ) ) - > getAuthenticatedUserNames ( ) , <nl> - repl : : ReadConcernArgs : : get ( opCtx ) . getLevel ( ) , <nl> - cmdObj } ) ; <nl> - cursorId = pinnedCursor . getCursor ( ) - > cursorid ( ) ; <nl> - <nl> - invariant ( ! exec ) ; <nl> - PlanExecutor * cursorExec = pinnedCursor . getCursor ( ) - > getExecutor ( ) ; <nl> - <nl> - / / State will be restored on getMore . <nl> - cursorExec - > saveState ( ) ; <nl> - cursorExec - > detachFromOperationContext ( ) ; <nl> - <nl> - / / We assume that cursors created through a DBDirectClient are always used from their <nl> - / / original OperationContext , so we do not need to move time to and from the cursor . <nl> - if ( ! opCtx - > getClient ( ) - > isInDirectClient ( ) ) { <nl> - pinnedCursor . getCursor ( ) - > setLeftoverMaxTimeMicros ( <nl> - opCtx - > getRemainingMaxTimeMicros ( ) ) ; <nl> + / / Fill out curop based on the results . <nl> + endQueryOp ( opCtx , collection , * cursorExec , numResults , cursorId ) ; <nl> + } else { <nl> + endQueryOp ( opCtx , collection , * exec , numResults , cursorId ) ; <nl> } <nl> - pinnedCursor . getCursor ( ) - > setPos ( numResults ) ; <nl> <nl> - / / Fill out curop based on the results . <nl> - endQueryOp ( opCtx , collection , * cursorExec , numResults , cursorId ) ; <nl> - } else { <nl> - endQueryOp ( opCtx , collection , * exec , numResults , cursorId ) ; <nl> + / / Generate the response object to send to the client . <nl> + firstBatch . done ( cursorId , nss . ns ( ) ) ; <nl> } <nl> <nl> - / / Generate the response object to send to the client . <nl> - firstBatch . done ( cursorId , nss . ns ( ) ) ; <nl> - return true ; <nl> - } <nl> + private : <nl> + const OpMsgRequest & _request ; <nl> + const StringData _dbName ; <nl> + } ; <nl> <nl> } findCmd ; <nl> <nl> mmm a / src / mongo / s / commands / cluster_find_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_find_cmd . cpp <nl> const char kTermField [ ] = " term " ; <nl> / * * <nl> * Implements the find command on mongos . <nl> * / <nl> - class ClusterFindCmd : public BasicCommand { <nl> - MONGO_DISALLOW_COPYING ( ClusterFindCmd ) ; <nl> - <nl> + class ClusterFindCmd final : public Command { <nl> public : <nl> - ClusterFindCmd ( ) : BasicCommand ( " find " ) { } <nl> + ClusterFindCmd ( ) : Command ( " find " ) { } <nl> <nl> - virtual bool supportsWriteConcern ( const BSONObj & cmd ) const override { <nl> - return false ; <nl> + std : : unique_ptr < CommandInvocation > parse ( OperationContext * opCtx , <nl> + const OpMsgRequest & opMsgRequest ) override { <nl> + / / TODO : Parse into a QueryRequest here . <nl> + return std : : make_unique < Invocation > ( this , opMsgRequest , opMsgRequest . getDatabase ( ) ) ; <nl> } <nl> <nl> - AllowedOnSecondary secondaryAllowed ( ServiceContext * ) const override { <nl> + AllowedOnSecondary secondaryAllowed ( ServiceContext * context ) const override { <nl> return AllowedOnSecondary : : kOptIn ; <nl> } <nl> <nl> class ClusterFindCmd : public BasicCommand { <nl> return false ; <nl> } <nl> <nl> - bool supportsReadConcern ( const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - repl : : ReadConcernLevel level ) const final { <nl> - return true ; <nl> - } <nl> - <nl> bool shouldAffectCommandCounter ( ) const final { <nl> return false ; <nl> } <nl> class ClusterFindCmd : public BasicCommand { <nl> return " query for documents " ; <nl> } <nl> <nl> - / * * <nl> - * In order to run the find command , you must be authorized for the " find " action <nl> - * type on the collection . <nl> - * / <nl> - Status checkAuthForCommand ( Client * client , <nl> - const std : : string & dbname , <nl> - const BSONObj & cmdObj ) const final { <nl> - const NamespaceString nss ( parseNs ( dbname , cmdObj ) ) ; <nl> - auto hasTerm = cmdObj . hasField ( kTermField ) ; <nl> - return AuthorizationSession : : get ( client ) - > checkAuthForFind ( nss , hasTerm ) ; <nl> - } <nl> + class Invocation final : public CommandInvocation { <nl> + public : <nl> + Invocation ( const ClusterFindCmd * definition , const OpMsgRequest & request , StringData dbName ) <nl> + : CommandInvocation ( definition ) , _request ( request ) , _dbName ( dbName ) { } <nl> <nl> - Status explain ( OperationContext * opCtx , <nl> - const OpMsgRequest & request , <nl> - ExplainOptions : : Verbosity verbosity , <nl> - BSONObjBuilder * out ) const final { <nl> - std : : string dbname = request . getDatabase ( ) . toString ( ) ; <nl> - const BSONObj & cmdObj = request . body ; <nl> - const NamespaceString nss ( CommandHelpers : : parseNsCollectionRequired ( dbname , cmdObj ) ) ; <nl> - / / Parse the command BSON to a QueryRequest . <nl> - bool isExplain = true ; <nl> - auto swQr = QueryRequest : : makeFromFindCommand ( std : : move ( nss ) , cmdObj , isExplain ) ; <nl> - if ( ! swQr . isOK ( ) ) { <nl> - return swQr . getStatus ( ) ; <nl> + private : <nl> + bool supportsWriteConcern ( ) const override { <nl> + return false ; <nl> } <nl> - auto & qr = * swQr . getValue ( ) ; <nl> - <nl> - try { <nl> - const auto explainCmd = ClusterExplain : : wrapAsExplain ( cmdObj , verbosity ) ; <nl> - <nl> - long long millisElapsed ; <nl> - std : : vector < AsyncRequestsSender : : Response > shardResponses ; <nl> - <nl> - / / We will time how long it takes to run the commands on the shards . <nl> - Timer timer ; <nl> - const auto routingInfo = uassertStatusOK ( <nl> - Grid : : get ( opCtx ) - > catalogCache ( ) - > getCollectionRoutingInfo ( opCtx , qr . nss ( ) ) ) ; <nl> - shardResponses = <nl> - scatterGatherVersionedTargetByRoutingTable ( opCtx , <nl> - qr . nss ( ) . db ( ) , <nl> - qr . nss ( ) , <nl> - routingInfo , <nl> - explainCmd , <nl> - ReadPreferenceSetting : : get ( opCtx ) , <nl> - Shard : : RetryPolicy : : kIdempotent , <nl> - qr . getFilter ( ) , <nl> - qr . getCollation ( ) ) ; <nl> - millisElapsed = timer . millis ( ) ; <nl> - <nl> - const char * mongosStageName = <nl> - ClusterExplain : : getStageNameForReadOp ( shardResponses . size ( ) , cmdObj ) ; <nl> - <nl> - uassertStatusOK ( ClusterExplain : : buildExplainResult ( <nl> - opCtx , <nl> - ClusterExplain : : downconvert ( opCtx , shardResponses ) , <nl> - mongosStageName , <nl> - millisElapsed , <nl> - out ) ) ; <nl> - <nl> - return Status : : OK ( ) ; <nl> - } catch ( const ExceptionFor < ErrorCodes : : CommandOnShardedViewNotSupportedOnMongod > & ex ) { <nl> - out - > resetToEmpty ( ) ; <nl> - <nl> - auto aggCmdOnView = qr . asAggregationCommand ( ) ; <nl> - if ( ! aggCmdOnView . isOK ( ) ) { <nl> - return aggCmdOnView . getStatus ( ) ; <nl> - } <nl> <nl> - auto aggRequestOnView = <nl> - AggregationRequest : : parseFromBSON ( nss , aggCmdOnView . getValue ( ) , verbosity ) ; <nl> - if ( ! aggRequestOnView . isOK ( ) ) { <nl> - return aggRequestOnView . getStatus ( ) ; <nl> - } <nl> + bool supportsReadConcern ( repl : : ReadConcernLevel level ) const final { <nl> + return true ; <nl> + } <nl> <nl> - auto resolvedAggRequest = ex - > asExpandedViewAggregation ( aggRequestOnView . getValue ( ) ) ; <nl> - auto resolvedAggCmd = resolvedAggRequest . serializeToCommandObj ( ) . toBson ( ) ; <nl> + NamespaceString ns ( ) const override { <nl> + / / TODO get the ns from the parsed QueryRequest . <nl> + return NamespaceString ( CommandHelpers : : parseNsFromCommand ( _dbName , _request . body ) ) ; <nl> + } <nl> <nl> - ClusterAggregate : : Namespaces nsStruct ; <nl> - nsStruct . requestedNss = std : : move ( nss ) ; <nl> - nsStruct . executionNss = std : : move ( ex - > getNamespace ( ) ) ; <nl> + / * * <nl> + * In order to run the find command , you must be authorized for the " find " action <nl> + * type on the collection . <nl> + * / <nl> + void doCheckAuthorization ( OperationContext * opCtx ) const final { <nl> + auto hasTerm = _request . body . hasField ( kTermField ) ; <nl> + uassertStatusOK ( <nl> + AuthorizationSession : : get ( opCtx - > getClient ( ) ) - > checkAuthForFind ( ns ( ) , hasTerm ) ) ; <nl> + } <nl> <nl> - auto status = ClusterAggregate : : runAggregate ( <nl> - opCtx , nsStruct , resolvedAggRequest , resolvedAggCmd , out ) ; <nl> - uassertStatusOK ( status ) ; <nl> - return status ; <nl> + void explain ( OperationContext * opCtx , <nl> + ExplainOptions : : Verbosity verbosity , <nl> + BSONObjBuilder * result ) override { <nl> + / / Parse the command BSON to a QueryRequest . <nl> + bool isExplain = true ; <nl> + auto qr = <nl> + uassertStatusOK ( QueryRequest : : makeFromFindCommand ( ns ( ) , _request . body , isExplain ) ) ; <nl> + <nl> + try { <nl> + const auto explainCmd = ClusterExplain : : wrapAsExplain ( _request . body , verbosity ) ; <nl> + <nl> + long long millisElapsed ; <nl> + std : : vector < AsyncRequestsSender : : Response > shardResponses ; <nl> + <nl> + / / We will time how long it takes to run the commands on the shards . <nl> + Timer timer ; <nl> + const auto routingInfo = uassertStatusOK ( <nl> + Grid : : get ( opCtx ) - > catalogCache ( ) - > getCollectionRoutingInfo ( opCtx , qr - > nss ( ) ) ) ; <nl> + shardResponses = <nl> + scatterGatherVersionedTargetByRoutingTable ( opCtx , <nl> + qr - > nss ( ) . db ( ) , <nl> + qr - > nss ( ) , <nl> + routingInfo , <nl> + explainCmd , <nl> + ReadPreferenceSetting : : get ( opCtx ) , <nl> + Shard : : RetryPolicy : : kIdempotent , <nl> + qr - > getFilter ( ) , <nl> + qr - > getCollation ( ) ) ; <nl> + millisElapsed = timer . millis ( ) ; <nl> + <nl> + const char * mongosStageName = <nl> + ClusterExplain : : getStageNameForReadOp ( shardResponses . size ( ) , _request . body ) ; <nl> + <nl> + uassertStatusOK ( ClusterExplain : : buildExplainResult ( <nl> + opCtx , <nl> + ClusterExplain : : downconvert ( opCtx , shardResponses ) , <nl> + mongosStageName , <nl> + millisElapsed , <nl> + result ) ) ; <nl> + <nl> + } catch ( const ExceptionFor < ErrorCodes : : CommandOnShardedViewNotSupportedOnMongod > & ex ) { <nl> + result - > resetToEmpty ( ) ; <nl> + <nl> + auto aggCmdOnView = uassertStatusOK ( qr - > asAggregationCommand ( ) ) ; <nl> + <nl> + auto aggRequestOnView = uassertStatusOK ( <nl> + AggregationRequest : : parseFromBSON ( ns ( ) , aggCmdOnView , verbosity ) ) ; <nl> + <nl> + auto resolvedAggRequest = ex - > asExpandedViewAggregation ( aggRequestOnView ) ; <nl> + auto resolvedAggCmd = resolvedAggRequest . serializeToCommandObj ( ) . toBson ( ) ; <nl> + <nl> + ClusterAggregate : : Namespaces nsStruct ; <nl> + nsStruct . requestedNss = ns ( ) ; <nl> + nsStruct . executionNss = std : : move ( ex - > getNamespace ( ) ) ; <nl> + <nl> + uassertStatusOK ( ClusterAggregate : : runAggregate ( <nl> + opCtx , nsStruct , resolvedAggRequest , resolvedAggCmd , result ) ) ; <nl> + } <nl> } <nl> - } <nl> <nl> - bool run ( OperationContext * opCtx , <nl> - const std : : string & dbname , <nl> - const BSONObj & cmdObj , <nl> - BSONObjBuilder & result ) final { <nl> - / / We count find command as a query op . <nl> - globalOpCounters . gotQuery ( ) ; <nl> - <nl> - const NamespaceString nss ( CommandHelpers : : parseNsCollectionRequired ( dbname , cmdObj ) ) ; <nl> - <nl> - const bool isExplain = false ; <nl> - auto qr = QueryRequest : : makeFromFindCommand ( nss , cmdObj , isExplain ) ; <nl> - uassertStatusOK ( qr . getStatus ( ) ) ; <nl> - <nl> - const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> - auto cq = CanonicalQuery : : canonicalize ( opCtx , <nl> - std : : move ( qr . getValue ( ) ) , <nl> - expCtx , <nl> - ExtensionsCallbackNoop ( ) , <nl> - MatchExpressionParser : : kAllowAllSpecialFeatures ) ; <nl> - uassertStatusOK ( cq . getStatus ( ) ) ; <nl> - <nl> - try { <nl> - / / Do the work to generate the first batch of results . This blocks waiting to get <nl> - / / responses from the shard ( s ) . <nl> - std : : vector < BSONObj > batch ; <nl> - auto cursorId = ClusterFind : : runQuery ( <nl> - opCtx , * cq . getValue ( ) , ReadPreferenceSetting : : get ( opCtx ) , & batch ) ; <nl> - / / Build the response document . <nl> - CursorResponseBuilder firstBatch ( / * firstBatch * / true , & result ) ; <nl> - for ( const auto & obj : batch ) { <nl> - firstBatch . append ( obj ) ; <nl> + void run ( OperationContext * opCtx , rpc : : ReplyBuilderInterface * result ) { <nl> + / / We count find command as a query op . <nl> + globalOpCounters . gotQuery ( ) ; <nl> + <nl> + const bool isExplain = false ; <nl> + auto qr = <nl> + uassertStatusOK ( QueryRequest : : makeFromFindCommand ( ns ( ) , _request . body , isExplain ) ) ; <nl> + <nl> + const boost : : intrusive_ptr < ExpressionContext > expCtx ; <nl> + auto cq = uassertStatusOK ( <nl> + CanonicalQuery : : canonicalize ( opCtx , <nl> + std : : move ( qr ) , <nl> + expCtx , <nl> + ExtensionsCallbackNoop ( ) , <nl> + MatchExpressionParser : : kAllowAllSpecialFeatures ) ) ; <nl> + <nl> + try { <nl> + / / Do the work to generate the first batch of results . This blocks waiting to get <nl> + / / responses from the shard ( s ) . <nl> + std : : vector < BSONObj > batch ; <nl> + auto cursorId = <nl> + ClusterFind : : runQuery ( opCtx , * cq , ReadPreferenceSetting : : get ( opCtx ) , & batch ) ; <nl> + auto bodyBuilder = result - > getBodyBuilder ( ) ; <nl> + / / Build the response document . <nl> + CursorResponseBuilder firstBatch ( / * firstBatch * / true , & bodyBuilder ) ; <nl> + for ( const auto & obj : batch ) { <nl> + firstBatch . append ( obj ) ; <nl> + } <nl> + firstBatch . done ( cursorId , cq - > ns ( ) ) ; <nl> + } catch ( const ExceptionFor < ErrorCodes : : CommandOnShardedViewNotSupportedOnMongod > & ex ) { <nl> + result - > reset ( ) ; <nl> + <nl> + auto aggCmdOnView = uassertStatusOK ( cq - > getQueryRequest ( ) . asAggregationCommand ( ) ) ; <nl> + <nl> + auto aggRequestOnView = <nl> + uassertStatusOK ( AggregationRequest : : parseFromBSON ( ns ( ) , aggCmdOnView ) ) ; <nl> + <nl> + auto resolvedAggRequest = ex - > asExpandedViewAggregation ( aggRequestOnView ) ; <nl> + auto resolvedAggCmd = resolvedAggRequest . serializeToCommandObj ( ) . toBson ( ) ; <nl> + <nl> + / / We pass both the underlying collection namespace and the view namespace here . The <nl> + / / underlying collection namespace is used to execute the aggregation on mongoD . Any <nl> + / / cursor returned will be registered under the view namespace so that subsequent <nl> + / / getMore and killCursors calls against the view have access . <nl> + ClusterAggregate : : Namespaces nsStruct ; <nl> + nsStruct . requestedNss = ns ( ) ; <nl> + nsStruct . executionNss = std : : move ( ex - > getNamespace ( ) ) ; <nl> + <nl> + auto bodyBuilder = result - > getBodyBuilder ( ) ; <nl> + uassertStatusOK ( ClusterAggregate : : runAggregate ( <nl> + opCtx , nsStruct , resolvedAggRequest , resolvedAggCmd , & bodyBuilder ) ) ; <nl> } <nl> - firstBatch . done ( cursorId , nss . ns ( ) ) ; <nl> - return true ; <nl> - } catch ( const ExceptionFor < ErrorCodes : : CommandOnShardedViewNotSupportedOnMongod > & ex ) { <nl> - auto aggCmdOnView = cq . getValue ( ) - > getQueryRequest ( ) . asAggregationCommand ( ) ; <nl> - uassertStatusOK ( aggCmdOnView . getStatus ( ) ) ; <nl> - <nl> - auto aggRequestOnView = AggregationRequest : : parseFromBSON ( nss , aggCmdOnView . getValue ( ) ) ; <nl> - uassertStatusOK ( aggRequestOnView . getStatus ( ) ) ; <nl> - <nl> - auto resolvedAggRequest = ex - > asExpandedViewAggregation ( aggRequestOnView . getValue ( ) ) ; <nl> - auto resolvedAggCmd = resolvedAggRequest . serializeToCommandObj ( ) . toBson ( ) ; <nl> - <nl> - / / We pass both the underlying collection namespace and the view namespace here . The <nl> - / / underlying collection namespace is used to execute the aggregation on mongoD . Any <nl> - / / cursor returned will be registered under the view namespace so that subsequent <nl> - / / getMore and killCursors calls against the view have access . <nl> - ClusterAggregate : : Namespaces nsStruct ; <nl> - nsStruct . requestedNss = std : : move ( nss ) ; <nl> - nsStruct . executionNss = std : : move ( ex - > getNamespace ( ) ) ; <nl> - <nl> - auto status = ClusterAggregate : : runAggregate ( <nl> - opCtx , nsStruct , resolvedAggRequest , resolvedAggCmd , & result ) ; <nl> - uassertStatusOK ( status ) ; <nl> - return true ; <nl> } <nl> - } <nl> + <nl> + private : <nl> + const OpMsgRequest & _request ; <nl> + const StringData _dbName ; <nl> + } ; <nl> <nl> } cmdFindCluster ; <nl> <nl> | SERVER - 35910 Upgrade FindCmd and ClusterFindCmd to use TypedCommand | mongodb/mongo | 1868c56cf7466793b1bbee553d9325d5d68f5ba2 | 2018-07-10T13:56:55Z |
mmm a / src / heap / heap - inl . h <nl> ppp b / src / heap / heap - inl . h <nl> AllocationResult Heap : : AllocateRaw ( int size_in_bytes , AllocationSpace space , <nl> old_gen_exhausted_ = true ; <nl> } <nl> <nl> + if ( ! old_gen_exhausted_ & & incremental_marking ( ) - > black_allocation ( ) & & <nl> + space ! = OLD_SPACE ) { <nl> + Marking : : MarkBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ; <nl> + MemoryChunk : : IncrementLiveBytesFromGC ( object , size_in_bytes ) ; <nl> + } <nl> return allocation ; <nl> } <nl> <nl> mmm a / src / heap / heap . cc <nl> ppp b / src / heap / heap . cc <nl> void Heap : : CreateFillerObjectAt ( Address addr , int size , <nl> if ( mode = = ClearRecordedSlots : : kYes ) { <nl> ClearRecordedSlotRange ( addr , addr + size ) ; <nl> } <nl> - <nl> - / / If the location where the filler is created is within a black area we have <nl> - / / to clear the mark bits of the filler space . <nl> - if ( incremental_marking ( ) - > black_allocation ( ) & & <nl> - Marking : : IsBlackOrGrey ( ObjectMarking : : MarkBitFrom ( addr ) ) ) { <nl> - Page * page = Page : : FromAddress ( addr ) ; <nl> - page - > markbits ( ) - > ClearRange ( page - > AddressToMarkbitIndex ( addr ) , <nl> - page - > AddressToMarkbitIndex ( addr + size ) ) ; <nl> - } <nl> - <nl> / / At this point , we may be deserializing the heap from a snapshot , and <nl> / / none of the maps have been created yet and are NULL . <nl> DCHECK ( ( filler - > map ( ) = = NULL & & ! deserialization_complete_ ) | | <nl> FixedArrayBase * Heap : : LeftTrimFixedArray ( FixedArrayBase * object , <nl> / / Calculate location of new array start . <nl> Address new_start = object - > address ( ) + bytes_to_trim ; <nl> <nl> - / / Transfer the mark bits to their new location . <nl> - IncrementalMarking : : TransferMark ( this , object - > address ( ) , new_start ) ; <nl> - <nl> / / Technically in new space this write might be omitted ( except for <nl> / / debug mode which iterates through the heap ) , but to play safer <nl> / / we still do it . <nl> FixedArrayBase * Heap : : LeftTrimFixedArray ( FixedArrayBase * object , <nl> int new_start_index = elements_to_trim * ( element_size / kPointerSize ) ; <nl> former_start [ new_start_index ] = map ; <nl> former_start [ new_start_index + 1 ] = Smi : : FromInt ( len - elements_to_trim ) ; <nl> - <nl> FixedArrayBase * new_object = <nl> FixedArrayBase : : cast ( HeapObject : : FromAddress ( new_start ) ) ; <nl> <nl> - / / Maintain consistency of live bytes during incremental marking <nl> - AdjustLiveBytes ( new_object , - bytes_to_trim , Heap : : CONCURRENT_TO_SWEEPER ) ; <nl> - <nl> / / Remove recorded slots for the new map and length offset . <nl> ClearRecordedSlot ( new_object , HeapObject : : RawField ( new_object , 0 ) ) ; <nl> ClearRecordedSlot ( new_object , HeapObject : : RawField ( <nl> new_object , FixedArrayBase : : kLengthOffset ) ) ; <nl> <nl> + / / Maintain consistency of live bytes during incremental marking <nl> + IncrementalMarking : : TransferMark ( this , object - > address ( ) , new_start ) ; <nl> + AdjustLiveBytes ( new_object , - bytes_to_trim , Heap : : CONCURRENT_TO_SWEEPER ) ; <nl> + <nl> / / Notify the heap profiler of change in object layout . <nl> OnMoveEvent ( new_object , object , new_object - > Size ( ) ) ; <nl> return new_object ; <nl> void Heap : : RegisterReservationsForBlackAllocation ( Reservation * reservations ) { <nl> / / Hence we have to color all objects of the reservation first black to avoid <nl> / / unnecessary marking deque load . <nl> if ( incremental_marking ( ) - > black_allocation ( ) ) { <nl> - for ( int i = OLD_SPACE ; i < Serializer : : kNumberOfSpaces ; i + + ) { <nl> + for ( int i = CODE_SPACE ; i < Serializer : : kNumberOfSpaces ; i + + ) { <nl> const Heap : : Reservation & res = reservations [ i ] ; <nl> for ( auto & chunk : res ) { <nl> Address addr = chunk . start ; <nl> while ( addr < chunk . end ) { <nl> HeapObject * obj = HeapObject : : FromAddress ( addr ) ; <nl> Marking : : MarkBlack ( ObjectMarking : : MarkBitFrom ( obj ) ) ; <nl> + MemoryChunk : : IncrementLiveBytesFromGC ( obj , obj - > Size ( ) ) ; <nl> addr + = obj - > Size ( ) ; <nl> } <nl> } <nl> mmm a / src / heap / incremental - marking . cc <nl> ppp b / src / heap / incremental - marking . cc <nl> void IncrementalMarking : : TransferMark ( Heap * heap , Address old_start , <nl> DCHECK ( MemoryChunk : : FromAddress ( old_start ) = = <nl> MemoryChunk : : FromAddress ( new_start ) ) ; <nl> <nl> - if ( ! heap - > incremental_marking ( ) - > IsMarking ( ) ) return ; <nl> + if ( ! heap - > incremental_marking ( ) - > IsMarking ( ) | | <nl> + Page : : FromAddress ( old_start ) - > IsFlagSet ( Page : : BLACK_PAGE ) ) <nl> + return ; <nl> <nl> / / If the mark doesn ' t move , we don ' t check the color of the object . <nl> / / It doesn ' t matter whether the object is black , since it hasn ' t changed <nl> void IncrementalMarking : : StartBlackAllocation ( ) { <nl> DCHECK ( FLAG_black_allocation ) ; <nl> DCHECK ( IsMarking ( ) ) ; <nl> black_allocation_ = true ; <nl> - heap ( ) - > old_space ( ) - > MarkAllocationInfoBlack ( ) ; <nl> - heap ( ) - > map_space ( ) - > MarkAllocationInfoBlack ( ) ; <nl> - heap ( ) - > code_space ( ) - > MarkAllocationInfoBlack ( ) ; <nl> + OldSpace * old_space = heap ( ) - > old_space ( ) ; <nl> + old_space - > EmptyAllocationInfo ( ) ; <nl> + old_space - > free_list ( ) - > Reset ( ) ; <nl> if ( FLAG_trace_incremental_marking ) { <nl> PrintF ( " [ IncrementalMarking ] Black allocation started \ n " ) ; <nl> } <nl> void IncrementalMarking : : UpdateMarkingDequeAfterScavenge ( ) { <nl> / / them . <nl> if ( map_word . IsForwardingAddress ( ) ) { <nl> HeapObject * dest = map_word . ToForwardingAddress ( ) ; <nl> - if ( Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( dest - > address ( ) ) ) ) <nl> + if ( Page : : FromAddress ( dest - > address ( ) ) - > IsFlagSet ( Page : : BLACK_PAGE ) ) <nl> continue ; <nl> array [ new_top ] = dest ; <nl> new_top = ( ( new_top + 1 ) & mask ) ; <nl> mmm a / src / heap / incremental - marking . h <nl> ppp b / src / heap / incremental - marking . h <nl> class IncrementalMarking { <nl> <nl> static void TransferMark ( Heap * heap , Address old_start , Address new_start ) ; <nl> <nl> - / / Returns true if the color transfer requires live bytes updating . <nl> - INLINE ( static bool TransferColor ( HeapObject * from , HeapObject * to , <nl> - int size ) ) { <nl> + / / Returns true if the transferred color is black . <nl> + INLINE ( static bool TransferColor ( HeapObject * from , HeapObject * to ) ) { <nl> + if ( Page : : FromAddress ( to - > address ( ) ) - > IsFlagSet ( Page : : BLACK_PAGE ) ) <nl> + return true ; <nl> MarkBit from_mark_bit = ObjectMarking : : MarkBitFrom ( from ) ; <nl> MarkBit to_mark_bit = ObjectMarking : : MarkBitFrom ( to ) ; <nl> - <nl> - if ( Marking : : IsBlack ( to_mark_bit ) ) { <nl> - DCHECK ( to - > GetHeap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) ; <nl> - return false ; <nl> - } <nl> - <nl> DCHECK ( Marking : : IsWhite ( to_mark_bit ) ) ; <nl> if ( from_mark_bit . Get ( ) ) { <nl> to_mark_bit . Set ( ) ; <nl> mmm a / src / heap / mark - compact - inl . h <nl> ppp b / src / heap / mark - compact - inl . h <nl> HeapObject * LiveObjectIterator < T > : : Next ( ) { <nl> cell_base_ = it_ . CurrentCellBase ( ) ; <nl> current_cell_ = * it_ . CurrentCell ( ) ; <nl> } <nl> - <nl> - if ( current_cell_ & second_bit_index ) { <nl> - / / We found a black object . If the black object is within a black area , <nl> - / / make sure that we skip all set bits in the black area until the <nl> - / / object ends . <nl> - HeapObject * black_object = HeapObject : : FromAddress ( addr ) ; <nl> - Address end = addr + black_object - > Size ( ) - kPointerSize ; <nl> - DCHECK_EQ ( chunk_ , MemoryChunk : : FromAddress ( end ) ) ; <nl> - uint32_t end_mark_bit_index = chunk_ - > AddressToMarkbitIndex ( end ) ; <nl> - unsigned int end_cell_index = <nl> - end_mark_bit_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType end_index_mask = <nl> - 1u < < Bitmap : : IndexInCell ( end_mark_bit_index ) ; <nl> - if ( it_ . Advance ( end_cell_index ) ) { <nl> - cell_base_ = it_ . CurrentCellBase ( ) ; <nl> - current_cell_ = * it_ . CurrentCell ( ) ; <nl> - } <nl> - <nl> - / / Clear all bits in current_cell , including the end index . <nl> - current_cell_ & = ~ ( end_index_mask + end_index_mask - 1 ) ; <nl> - <nl> - if ( T = = kBlackObjects | | T = = kAllLiveObjects ) { <nl> - object = black_object ; <nl> - } <nl> - } else if ( ( T = = kGreyObjects | | T = = kAllLiveObjects ) ) { <nl> + if ( T = = kBlackObjects & & ( current_cell_ & second_bit_index ) ) { <nl> + object = HeapObject : : FromAddress ( addr ) ; <nl> + } else if ( T = = kGreyObjects & & ! ( current_cell_ & second_bit_index ) ) { <nl> + object = HeapObject : : FromAddress ( addr ) ; <nl> + } else if ( T = = kAllLiveObjects ) { <nl> object = HeapObject : : FromAddress ( addr ) ; <nl> } <nl> <nl> + / / Clear the second bit of the found object . <nl> + current_cell_ & = ~ second_bit_index ; <nl> + <nl> / / We found a live object . <nl> if ( object ! = nullptr ) break ; <nl> } <nl> - <nl> if ( current_cell_ = = 0 ) { <nl> if ( ! it_ . Done ( ) ) { <nl> it_ . Advance ( ) ; <nl> mmm a / src / heap / mark - compact . cc <nl> ppp b / src / heap / mark - compact . cc <nl> static void VerifyMarking ( Heap * heap , Address bottom , Address top ) { <nl> VerifyMarkingVisitor visitor ( heap ) ; <nl> HeapObject * object ; <nl> Address next_object_must_be_here_or_later = bottom ; <nl> - for ( Address current = bottom ; current < top ; ) { <nl> + <nl> + for ( Address current = bottom ; current < top ; current + = kPointerSize ) { <nl> object = HeapObject : : FromAddress ( current ) ; <nl> if ( MarkCompactCollector : : IsMarked ( object ) ) { <nl> CHECK ( Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ) ; <nl> CHECK ( current > = next_object_must_be_here_or_later ) ; <nl> object - > Iterate ( & visitor ) ; <nl> next_object_must_be_here_or_later = current + object - > Size ( ) ; <nl> - / / The object is either part of a black area of black allocation or a <nl> - / / regular black object <nl> - Page * page = Page : : FromAddress ( current ) ; <nl> - CHECK ( <nl> - page - > markbits ( ) - > AllBitsSetInRange ( <nl> - page - > AddressToMarkbitIndex ( current ) , <nl> - page - > AddressToMarkbitIndex ( next_object_must_be_here_or_later ) ) | | <nl> - page - > markbits ( ) - > AllBitsClearInRange ( <nl> - page - > AddressToMarkbitIndex ( current + kPointerSize * 2 ) , <nl> - page - > AddressToMarkbitIndex ( next_object_must_be_here_or_later ) ) ) ; <nl> - current = next_object_must_be_here_or_later ; <nl> - } else { <nl> + / / The next word for sure belongs to the current object , jump over it . <nl> current + = kPointerSize ; <nl> } <nl> } <nl> } <nl> <nl> + static void VerifyMarkingBlackPage ( Heap * heap , Page * page ) { <nl> + CHECK ( page - > IsFlagSet ( Page : : BLACK_PAGE ) ) ; <nl> + VerifyMarkingVisitor visitor ( heap ) ; <nl> + HeapObjectIterator it ( page ) ; <nl> + for ( HeapObject * object = it . Next ( ) ; object ! = NULL ; object = it . Next ( ) ) { <nl> + CHECK ( Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ) ; <nl> + object - > Iterate ( & visitor ) ; <nl> + } <nl> + } <nl> + <nl> static void VerifyMarking ( NewSpace * space ) { <nl> Address end = space - > top ( ) ; <nl> / / The bottom position is at the start of its page . Allows us to use <nl> static void VerifyMarking ( NewSpace * space ) { <nl> <nl> static void VerifyMarking ( PagedSpace * space ) { <nl> for ( Page * p : * space ) { <nl> - VerifyMarking ( space - > heap ( ) , p - > area_start ( ) , p - > area_end ( ) ) ; <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + VerifyMarkingBlackPage ( space - > heap ( ) , p ) ; <nl> + } else { <nl> + VerifyMarking ( space - > heap ( ) , p - > area_start ( ) , p - > area_end ( ) ) ; <nl> + } <nl> } <nl> } <nl> <nl> void MarkCompactCollector : : VerifyOmittedMapChecks ( ) { <nl> static void ClearMarkbitsInPagedSpace ( PagedSpace * space ) { <nl> for ( Page * p : * space ) { <nl> p - > ClearLiveness ( ) ; <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + p - > ClearFlag ( Page : : BLACK_PAGE ) ; <nl> + } <nl> } <nl> } <nl> <nl> void MarkCompactCollector : : ClearMarkbits ( ) { <nl> MemoryChunk * chunk = MemoryChunk : : FromAddress ( obj - > address ( ) ) ; <nl> chunk - > ResetProgressBar ( ) ; <nl> chunk - > ResetLiveBytes ( ) ; <nl> + if ( chunk - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + chunk - > ClearFlag ( Page : : BLACK_PAGE ) ; <nl> + } <nl> } <nl> } <nl> <nl> void MarkCompactCollector : : CollectEvacuationCandidates ( PagedSpace * space ) { <nl> <nl> for ( Page * p : * space ) { <nl> if ( p - > NeverEvacuate ( ) ) continue ; <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) continue ; <nl> / / Invariant : Evacuation candidates are just created when marking is <nl> / / started . This means that sweeping has finished . Furthermore , at the end <nl> / / of a GC all evacuation candidates are cleared and their slot buffers are <nl> class MarkCompactCollector : : EvacuateRecordOnlyVisitor final <nl> <nl> void MarkCompactCollector : : DiscoverGreyObjectsInSpace ( PagedSpace * space ) { <nl> for ( Page * p : * space ) { <nl> - DiscoverGreyObjectsOnPage ( p ) ; <nl> + if ( ! p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + DiscoverGreyObjectsOnPage ( p ) ; <nl> + } <nl> if ( marking_deque ( ) - > IsFull ( ) ) return ; <nl> } <nl> } <nl> bool MarkCompactCollector : : IsSlotInBlackObject ( MemoryChunk * p , Address slot ) { <nl> DCHECK ( owner ! = heap_ - > lo_space ( ) & & owner ! = nullptr ) ; <nl> USE ( owner ) ; <nl> <nl> - / / We may be part of a black area . <nl> - if ( Marking : : IsBlackOrGrey ( ObjectMarking : : MarkBitFrom ( slot ) ) ) { <nl> + / / If we are on a black page , we cannot find the actual object start <nl> + / / easiliy . We just return true but do not set the out_object . <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> return true ; <nl> } <nl> <nl> HeapObject * MarkCompactCollector : : FindBlackObjectBySlotSlow ( Address slot ) { <nl> return nullptr ; <nl> } <nl> <nl> - LiveObjectIterator < kBlackObjects > it ( p ) ; <nl> - HeapObject * object = nullptr ; <nl> - while ( ( object = it . Next ( ) ) ! = nullptr ) { <nl> - int size = object - > Size ( ) ; <nl> - if ( object - > address ( ) > slot ) return nullptr ; <nl> - if ( object - > address ( ) < = slot & & slot < ( object - > address ( ) + size ) ) { <nl> - return object ; <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + HeapObjectIterator it ( p ) ; <nl> + HeapObject * object = nullptr ; <nl> + while ( ( object = it . Next ( ) ) ! = nullptr ) { <nl> + int size = object - > Size ( ) ; <nl> + if ( object - > address ( ) > slot ) return nullptr ; <nl> + if ( object - > address ( ) < = slot & & slot < ( object - > address ( ) + size ) ) { <nl> + return object ; <nl> + } <nl> + } <nl> + } else { <nl> + LiveObjectIterator < kBlackObjects > it ( p ) ; <nl> + HeapObject * object = nullptr ; <nl> + while ( ( object = it . Next ( ) ) ! = nullptr ) { <nl> + int size = object - > Size ( ) ; <nl> + if ( object - > address ( ) > slot ) return nullptr ; <nl> + if ( object - > address ( ) < = slot & & slot < ( object - > address ( ) + size ) ) { <nl> + return object ; <nl> + } <nl> } <nl> } <nl> - <nl> return nullptr ; <nl> } <nl> <nl> int MarkCompactCollector : : Sweeper : : RawSweep ( <nl> DCHECK ( free_list_mode = = IGNORE_FREE_LIST | | space - > identity ( ) = = OLD_SPACE | | <nl> space - > identity ( ) = = CODE_SPACE | | space - > identity ( ) = = MAP_SPACE ) ; <nl> DCHECK ( ! p - > IsEvacuationCandidate ( ) & & ! p - > SweepingDone ( ) ) ; <nl> + DCHECK ( ! p - > IsFlagSet ( Page : : BLACK_PAGE ) ) ; <nl> <nl> / / Before we sweep objects on the page , we free dead array buffers which <nl> / / requires valid mark bits . <nl> void MarkCompactCollector : : Sweeper : : AddSweepingPageSafe ( AllocationSpace space , <nl> } <nl> <nl> void MarkCompactCollector : : StartSweepSpace ( PagedSpace * space ) { <nl> + Address space_top = space - > top ( ) ; <nl> space - > ClearStats ( ) ; <nl> <nl> int will_be_swept = 0 ; <nl> void MarkCompactCollector : : StartSweepSpace ( PagedSpace * space ) { <nl> continue ; <nl> } <nl> <nl> + / / We can not sweep black pages , since all mark bits are set for these <nl> + / / pages . <nl> + if ( p - > IsFlagSet ( Page : : BLACK_PAGE ) ) { <nl> + p - > ClearLiveness ( ) ; <nl> + p - > concurrent_sweeping_state ( ) . SetValue ( Page : : kSweepingDone ) ; <nl> + p - > ClearFlag ( Page : : BLACK_PAGE ) ; <nl> + / / Area above the high watermark is free . <nl> + Address free_start = p - > HighWaterMark ( ) ; <nl> + / / Check if the space top was in this page , which means that the <nl> + / / high watermark is not up - to - date . <nl> + if ( free_start < space_top & & space_top < = p - > area_end ( ) ) { <nl> + free_start = space_top ; <nl> + } <nl> + int size = static_cast < int > ( p - > area_end ( ) - free_start ) ; <nl> + space - > Free ( free_start , size ) ; <nl> + continue ; <nl> + } <nl> + <nl> if ( p - > IsFlagSet ( Page : : NEVER_ALLOCATE_ON_PAGE ) ) { <nl> / / We need to sweep the page to get it into an iterable state again . Note <nl> / / that this adds unusable memory into the free list that is later on <nl> mmm a / src / heap / mark - compact . h <nl> ppp b / src / heap / mark - compact . h <nl> class MarkBitCellIterator BASE_EMBEDDED { <nl> <nl> inline void Advance ( ) { <nl> cell_index_ + + ; <nl> - cell_base_ + = Bitmap : : kBitsPerCell * kPointerSize ; <nl> - } <nl> - <nl> - inline bool Advance ( unsigned int new_cell_index ) { <nl> - if ( new_cell_index ! = cell_index_ ) { <nl> - DCHECK_GT ( new_cell_index , cell_index_ ) ; <nl> - DCHECK_LE ( new_cell_index , last_cell_index_ ) ; <nl> - unsigned int diff = new_cell_index - cell_index_ ; <nl> - cell_index_ = new_cell_index ; <nl> - cell_base_ + = diff * ( Bitmap : : kBitsPerCell * kPointerSize ) ; <nl> - return true ; <nl> - } <nl> - return false ; <nl> + cell_base_ + = 32 * kPointerSize ; <nl> } <nl> <nl> / / Return the next mark bit cell . If there is no next it returns 0 ; <nl> class LiveObjectIterator BASE_EMBEDDED { <nl> it_ ( chunk_ ) , <nl> cell_base_ ( it_ . CurrentCellBase ( ) ) , <nl> current_cell_ ( * it_ . CurrentCell ( ) ) { <nl> + / / Black pages can not be iterated . <nl> + DCHECK ( ! chunk - > IsFlagSet ( Page : : BLACK_PAGE ) ) ; <nl> } <nl> <nl> HeapObject * Next ( ) ; <nl> mmm a / src / heap / marking . h <nl> ppp b / src / heap / marking . h <nl> class Bitmap { <nl> for ( int i = 0 ; i < CellsCount ( ) ; i + + ) cells ( ) [ i ] = 0 ; <nl> } <nl> <nl> - / / Sets all bits in the range [ start_index , end_index ) . <nl> - void SetRange ( uint32_t start_index , uint32_t end_index ) { <nl> - unsigned int start_cell_index = start_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType start_index_mask = 1u < < Bitmap : : IndexInCell ( start_index ) ; <nl> - <nl> - unsigned int end_cell_index = end_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType end_index_mask = 1u < < Bitmap : : IndexInCell ( end_index ) ; <nl> - <nl> - if ( start_cell_index ! = end_cell_index ) { <nl> - / / Firstly , fill all bits from the start address to the end of the first <nl> - / / cell with 1s . <nl> - cells ( ) [ start_cell_index ] | = ~ ( start_index_mask - 1 ) ; <nl> - / / Then fill all in between cells with 1s . <nl> - for ( unsigned int i = start_cell_index + 1 ; i < end_cell_index ; i + + ) { <nl> - cells ( ) [ i ] = ~ 0u ; <nl> - } <nl> - / / Finally , fill all bits until the end address in the last cell with 1s . <nl> - cells ( ) [ end_cell_index ] | = ( end_index_mask - 1 ) ; <nl> - } else { <nl> - cells ( ) [ start_cell_index ] | = end_index_mask - start_index_mask ; <nl> - } <nl> - } <nl> - <nl> - / / Clears all bits in the range [ start_index , end_index ) . <nl> - void ClearRange ( uint32_t start_index , uint32_t end_index ) { <nl> - unsigned int start_cell_index = start_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType start_index_mask = 1u < < Bitmap : : IndexInCell ( start_index ) ; <nl> - <nl> - unsigned int end_cell_index = end_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType end_index_mask = 1u < < Bitmap : : IndexInCell ( end_index ) ; <nl> - <nl> - if ( start_cell_index ! = end_cell_index ) { <nl> - / / Firstly , fill all bits from the start address to the end of the first <nl> - / / cell with 0s . <nl> - cells ( ) [ start_cell_index ] & = ( start_index_mask - 1 ) ; <nl> - / / Then fill all in between cells with 0s . <nl> - for ( unsigned int i = start_cell_index + 1 ; i < end_cell_index ; i + + ) { <nl> - cells ( ) [ i ] = 0 ; <nl> - } <nl> - / / Finally , set all bits until the end address in the last cell with 0s . <nl> - cells ( ) [ end_cell_index ] & = ~ ( end_index_mask - 1 ) ; <nl> - } else { <nl> - cells ( ) [ start_cell_index ] & = ~ ( end_index_mask - start_index_mask ) ; <nl> - } <nl> - } <nl> - <nl> - / / Returns true if all bits in the range [ start_index , end_index ) are set . <nl> - bool AllBitsSetInRange ( uint32_t start_index , uint32_t end_index ) { <nl> - unsigned int start_cell_index = start_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType start_index_mask = 1u < < Bitmap : : IndexInCell ( start_index ) ; <nl> - <nl> - unsigned int end_cell_index = end_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType end_index_mask = 1u < < Bitmap : : IndexInCell ( end_index ) ; <nl> - <nl> - MarkBit : : CellType matching_mask ; <nl> - if ( start_cell_index ! = end_cell_index ) { <nl> - matching_mask = ~ ( start_index_mask - 1 ) ; <nl> - if ( ( cells ( ) [ start_cell_index ] & matching_mask ) ! = matching_mask ) { <nl> - return false ; <nl> - } <nl> - for ( unsigned int i = start_cell_index + 1 ; i < end_cell_index ; i + + ) { <nl> - if ( cells ( ) [ i ] ! = ~ 0u ) return false ; <nl> - } <nl> - matching_mask = ( end_index_mask - 1 ) ; <nl> - return ( ( cells ( ) [ end_cell_index ] & matching_mask ) = = matching_mask ) ; <nl> - } else { <nl> - matching_mask = end_index_mask - start_index_mask ; <nl> - return ( cells ( ) [ end_cell_index ] & matching_mask ) = = matching_mask ; <nl> - } <nl> - } <nl> - <nl> - / / Returns true if all bits in the range [ start_index , end_index ) are cleared . <nl> - bool AllBitsClearInRange ( uint32_t start_index , uint32_t end_index ) { <nl> - unsigned int start_cell_index = start_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType start_index_mask = 1u < < Bitmap : : IndexInCell ( start_index ) ; <nl> - <nl> - unsigned int end_cell_index = end_index > > Bitmap : : kBitsPerCellLog2 ; <nl> - MarkBit : : CellType end_index_mask = 1u < < Bitmap : : IndexInCell ( end_index ) ; <nl> - <nl> - MarkBit : : CellType matching_mask ; <nl> - if ( start_cell_index ! = end_cell_index ) { <nl> - matching_mask = ~ ( start_index_mask - 1 ) ; <nl> - if ( ( cells ( ) [ start_cell_index ] & matching_mask ) ) return false ; <nl> - for ( unsigned int i = start_cell_index + 1 ; i < end_cell_index ; i + + ) { <nl> - if ( cells ( ) [ i ] ) return false ; <nl> - } <nl> - matching_mask = ( end_index_mask - 1 ) ; <nl> - return ! ( cells ( ) [ end_cell_index ] & matching_mask ) ; <nl> - } else { <nl> - matching_mask = end_index_mask - start_index_mask ; <nl> - return ! ( cells ( ) [ end_cell_index ] & matching_mask ) ; <nl> - } <nl> + void SetAllBits ( ) { <nl> + for ( int i = 0 ; i < CellsCount ( ) ; i + + ) cells ( ) [ i ] = 0xffffffff ; <nl> } <nl> <nl> static void PrintWord ( uint32_t word , uint32_t himask = 0 ) { <nl> class Bitmap { <nl> } <nl> return true ; <nl> } <nl> + <nl> + / / Clears all bits starting from { cell_base_index } up to and excluding <nl> + / / { index } . Note that { cell_base_index } is required to be cell aligned . <nl> + void ClearRange ( uint32_t cell_base_index , uint32_t index ) { <nl> + DCHECK_EQ ( IndexInCell ( cell_base_index ) , 0u ) ; <nl> + DCHECK_GE ( index , cell_base_index ) ; <nl> + uint32_t start_cell_index = IndexToCell ( cell_base_index ) ; <nl> + uint32_t end_cell_index = IndexToCell ( index ) ; <nl> + DCHECK_GE ( end_cell_index , start_cell_index ) ; <nl> + / / Clear all cells till the cell containing the last index . <nl> + for ( uint32_t i = start_cell_index ; i < end_cell_index ; i + + ) { <nl> + cells ( ) [ i ] = 0 ; <nl> + } <nl> + / / Clear all bits in the last cell till the last bit before index . <nl> + uint32_t clear_mask = ~ ( ( 1u < < IndexInCell ( index ) ) - 1 ) ; <nl> + cells ( ) [ end_cell_index ] & = clear_mask ; <nl> + } <nl> } ; <nl> <nl> class Marking : public AllStatic { <nl> mmm a / src / heap / scavenger . cc <nl> ppp b / src / heap / scavenger . cc <nl> class ScavengingVisitor : public StaticVisitorBase { <nl> } <nl> <nl> if ( marks_handling = = TRANSFER_MARKS ) { <nl> - if ( IncrementalMarking : : TransferColor ( source , target , size ) ) { <nl> + if ( IncrementalMarking : : TransferColor ( source , target ) ) { <nl> MemoryChunk : : IncrementLiveBytesFromGC ( target , size ) ; <nl> } <nl> } <nl> mmm a / src / heap / spaces - inl . h <nl> ppp b / src / heap / spaces - inl . h <nl> NewSpacePageRange : : NewSpacePageRange ( Address start , Address limit ) <nl> SemiSpace : : AssertValidRange ( start , limit ) ; <nl> } <nl> <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> / / SemiSpaceIterator <nl> <nl> void MemoryChunk : : ResetLiveBytes ( ) { <nl> } <nl> <nl> void MemoryChunk : : IncrementLiveBytes ( int by ) { <nl> + if ( IsFlagSet ( BLACK_PAGE ) ) return ; <nl> if ( FLAG_trace_live_bytes ) { <nl> PrintIsolate ( <nl> heap ( ) - > isolate ( ) , " live - bytes : update page = % p delta = % d % d - > % d \ n " , <nl> AllocationResult PagedSpace : : AllocateRawUnaligned ( <nl> if ( object = = NULL ) { <nl> object = SlowAllocateRaw ( size_in_bytes ) ; <nl> } <nl> - if ( object ! = NULL ) { <nl> - if ( heap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) { <nl> - Marking : : MarkBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ; <nl> - MemoryChunk : : IncrementLiveBytesFromGC ( object , size_in_bytes ) ; <nl> - } <nl> - } <nl> } <nl> <nl> if ( object ! = NULL ) { <nl> mmm a / src / heap / spaces . cc <nl> ppp b / src / heap / spaces . cc <nl> bool PagedSpace : : Expand ( ) { <nl> / / Pages created during bootstrapping may contain immortal immovable objects . <nl> if ( ! heap ( ) - > deserialization_complete ( ) ) p - > MarkNeverEvacuate ( ) ; <nl> <nl> + / / When incremental marking was activated , old space pages are allocated <nl> + / / black . <nl> + if ( heap ( ) - > incremental_marking ( ) - > black_allocation ( ) & & <nl> + identity ( ) = = OLD_SPACE ) { <nl> + p - > markbits ( ) - > SetAllBits ( ) ; <nl> + p - > SetFlag ( Page : : BLACK_PAGE ) ; <nl> + if ( FLAG_trace_incremental_marking ) { <nl> + PrintIsolate ( heap ( ) - > isolate ( ) , " Added black page % p \ n " , <nl> + static_cast < void * > ( p ) ) ; <nl> + } <nl> + } <nl> + <nl> DCHECK ( Capacity ( ) < = heap ( ) - > MaxOldGenerationSize ( ) ) ; <nl> <nl> p - > InsertAfter ( anchor_ . prev_page ( ) ) ; <nl> void PagedSpace : : ResetFreeListStatistics ( ) { <nl> } <nl> } <nl> <nl> - void PagedSpace : : SetAllocationInfo ( Address top , Address limit ) { <nl> - SetTopAndLimit ( top , limit ) ; <nl> - if ( top ! = nullptr & & top ! = limit & & <nl> - heap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) { <nl> - Page * page = Page : : FromAddress ( top ) ; <nl> - page - > markbits ( ) - > SetRange ( page - > AddressToMarkbitIndex ( top ) , <nl> - page - > AddressToMarkbitIndex ( limit ) ) ; <nl> - page - > IncrementLiveBytes ( static_cast < int > ( limit - top ) ) ; <nl> - } <nl> - } <nl> - <nl> - void PagedSpace : : MarkAllocationInfoBlack ( ) { <nl> - DCHECK ( heap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) ; <nl> - Address current_top = top ( ) ; <nl> - Address current_limit = limit ( ) ; <nl> - if ( current_top ! = nullptr & & current_top ! = current_limit ) { <nl> - Page * page = Page : : FromAddress ( current_top ) ; <nl> - page - > markbits ( ) - > SetRange ( page - > AddressToMarkbitIndex ( current_top ) , <nl> - page - > AddressToMarkbitIndex ( current_limit ) ) ; <nl> - page - > IncrementLiveBytes ( static_cast < int > ( current_limit - current_top ) ) ; <nl> - } <nl> - } <nl> - <nl> - / / Empty space allocation info , returning unused area to free list . <nl> - void PagedSpace : : EmptyAllocationInfo ( ) { <nl> - / / Mark the old linear allocation area with a free space map so it can be <nl> - / / skipped when scanning the heap . <nl> - Address current_top = top ( ) ; <nl> - Address current_limit = limit ( ) ; <nl> - if ( current_top = = nullptr ) { <nl> - DCHECK ( current_limit = = nullptr ) ; <nl> - return ; <nl> - } <nl> - int old_linear_size = static_cast < int > ( current_limit - current_top ) ; <nl> - SetTopAndLimit ( NULL , NULL ) ; <nl> - if ( current_top ! = current_limit & & <nl> - heap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) { <nl> - Page * page = Page : : FromAddress ( current_top ) ; <nl> - page - > markbits ( ) - > ClearRange ( page - > AddressToMarkbitIndex ( current_top ) , <nl> - page - > AddressToMarkbitIndex ( current_limit ) ) ; <nl> - page - > IncrementLiveBytes ( - static_cast < int > ( current_limit - current_top ) ) ; <nl> - } <nl> - Free ( current_top , old_linear_size ) ; <nl> - } <nl> <nl> void PagedSpace : : IncreaseCapacity ( int size ) { <nl> accounting_stats_ . ExpandSpace ( size ) ; <nl> void PagedSpace : : Verify ( ObjectVisitor * visitor ) { <nl> / / All the interior pointers should be contained in the heap . <nl> int size = object - > Size ( ) ; <nl> object - > IterateBody ( map - > instance_type ( ) , size , visitor ) ; <nl> - if ( Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ) { <nl> + if ( ! page - > IsFlagSet ( Page : : BLACK_PAGE ) & & <nl> + Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ) { <nl> black_size + = size ; <nl> } <nl> <nl> HeapObject * FreeList : : Allocate ( int size_in_bytes ) { <nl> / / Mark the old linear allocation area with a free space map so it can be <nl> / / skipped when scanning the heap . This also puts it back in the free list <nl> / / if it is big enough . <nl> - owner_ - > EmptyAllocationInfo ( ) ; <nl> + owner_ - > Free ( owner_ - > top ( ) , old_linear_size ) ; <nl> + owner_ - > SetTopAndLimit ( nullptr , nullptr ) ; <nl> <nl> owner_ - > heap ( ) - > incremental_marking ( ) - > OldSpaceStep ( size_in_bytes - <nl> old_linear_size ) ; <nl> HeapObject * FreeList : : Allocate ( int size_in_bytes ) { <nl> / / Keep the linear allocation area empty if requested to do so , just <nl> / / return area back to the free list instead . <nl> owner_ - > Free ( new_node - > address ( ) + size_in_bytes , bytes_left ) ; <nl> - owner_ - > SetAllocationInfo ( new_node - > address ( ) + size_in_bytes , <nl> - new_node - > address ( ) + size_in_bytes ) ; <nl> + owner_ - > SetTopAndLimit ( new_node - > address ( ) + size_in_bytes , <nl> + new_node - > address ( ) + size_in_bytes ) ; <nl> } else if ( bytes_left > kThreshold & & <nl> owner_ - > heap ( ) - > incremental_marking ( ) - > IsMarkingIncomplete ( ) & & <nl> FLAG_incremental_marking ) { <nl> HeapObject * FreeList : : Allocate ( int size_in_bytes ) { <nl> / / we want to do another increment until the linear area is used up . <nl> owner_ - > Free ( new_node - > address ( ) + size_in_bytes + linear_size , <nl> new_node_size - size_in_bytes - linear_size ) ; <nl> - owner_ - > SetAllocationInfo ( <nl> - new_node - > address ( ) + size_in_bytes , <nl> - new_node - > address ( ) + size_in_bytes + linear_size ) ; <nl> + owner_ - > SetTopAndLimit ( new_node - > address ( ) + size_in_bytes , <nl> + new_node - > address ( ) + size_in_bytes + linear_size ) ; <nl> } else { <nl> DCHECK ( bytes_left > = 0 ) ; <nl> / / Normally we give the rest of the node to the allocator as its new <nl> / / linear allocation area . <nl> - owner_ - > SetAllocationInfo ( new_node - > address ( ) + size_in_bytes , <nl> - new_node - > address ( ) + new_node_size ) ; <nl> + owner_ - > SetTopAndLimit ( new_node - > address ( ) + size_in_bytes , <nl> + new_node - > address ( ) + new_node_size ) ; <nl> } <nl> <nl> owner_ - > AllocationStep ( new_node - > address ( ) , size_in_bytes ) ; <nl> AllocationResult LargeObjectSpace : : AllocateRaw ( int object_size , <nl> <nl> heap ( ) - > incremental_marking ( ) - > OldSpaceStep ( object_size ) ; <nl> AllocationStep ( object - > address ( ) , object_size ) ; <nl> - <nl> - if ( heap ( ) - > incremental_marking ( ) - > black_allocation ( ) ) { <nl> - Marking : : MarkBlack ( ObjectMarking : : MarkBitFrom ( object ) ) ; <nl> - MemoryChunk : : IncrementLiveBytesFromGC ( object , object_size ) ; <nl> - } <nl> return object ; <nl> } <nl> <nl> mmm a / src / heap / spaces . h <nl> ppp b / src / heap / spaces . h <nl> class MemoryChunk { <nl> / / within the new space during evacuation . <nl> PAGE_NEW_NEW_PROMOTION , <nl> <nl> + / / A black page has all mark bits set to 1 ( black ) . A black page currently <nl> + / / cannot be iterated because it is not swept . Moreover live bytes are also <nl> + / / not updated . <nl> + BLACK_PAGE , <nl> + <nl> / / This flag is intended to be used for testing . Works only when both <nl> / / FLAG_stress_compaction and FLAG_manual_evacuation_candidates_selection <nl> / / are set . It forces the page to become an evacuation candidate at next <nl> class MemoryChunk { <nl> <nl> int LiveBytes ( ) { <nl> DCHECK_LE ( static_cast < unsigned > ( live_byte_count_ ) , size_ ) ; <nl> + DCHECK ( ! IsFlagSet ( BLACK_PAGE ) | | live_byte_count_ = = 0 ) ; <nl> return live_byte_count_ ; <nl> } <nl> <nl> void SetLiveBytes ( int live_bytes ) { <nl> + if ( IsFlagSet ( BLACK_PAGE ) ) return ; <nl> DCHECK_GE ( live_bytes , 0 ) ; <nl> DCHECK_LE ( static_cast < size_t > ( live_bytes ) , size_ ) ; <nl> live_byte_count_ = live_bytes ; <nl> class PagedSpace : public Space { <nl> allocation_info_ . Reset ( top , limit ) ; <nl> } <nl> <nl> - void SetAllocationInfo ( Address top , Address limit ) ; <nl> - <nl> / / Empty space allocation info , returning unused area to free list . <nl> - void EmptyAllocationInfo ( ) ; <nl> - <nl> - void MarkAllocationInfoBlack ( ) ; <nl> + void EmptyAllocationInfo ( ) { <nl> + / / Mark the old linear allocation area with a free space map so it can be <nl> + / / skipped when scanning the heap . <nl> + int old_linear_size = static_cast < int > ( limit ( ) - top ( ) ) ; <nl> + Free ( top ( ) , old_linear_size ) ; <nl> + SetTopAndLimit ( NULL , NULL ) ; <nl> + } <nl> <nl> void Allocate ( int bytes ) { accounting_stats_ . AllocateBytes ( bytes ) ; } <nl> <nl> mmm a / src / ia32 / assembler - ia32 - inl . h <nl> ppp b / src / ia32 / assembler - ia32 - inl . h <nl> void RelocInfo : : set_target_object ( Object * target , <nl> host ( ) ! = NULL & & <nl> target - > IsHeapObject ( ) ) { <nl> host ( ) - > GetHeap ( ) - > RecordWriteIntoCode ( host ( ) , this , target ) ; <nl> - host ( ) - > GetHeap ( ) - > incremental_marking ( ) - > RecordWriteIntoCode ( <nl> - host ( ) , this , HeapObject : : cast ( target ) ) ; <nl> } <nl> } <nl> <nl> mmm a / src / objects - inl . h <nl> ppp b / src / objects - inl . h <nl> void WeakCell : : initialize ( HeapObject * val ) { <nl> / / We just have to execute the generational barrier here because we never <nl> / / mark through a weak cell and collect evacuation candidates when we process <nl> / / all weak cells . <nl> - WriteBarrierMode mode = Marking : : IsBlack ( ObjectMarking : : MarkBitFrom ( this ) ) <nl> - ? UPDATE_WRITE_BARRIER <nl> - : UPDATE_WEAK_WRITE_BARRIER ; <nl> + WriteBarrierMode mode = <nl> + Page : : FromAddress ( this - > address ( ) ) - > IsFlagSet ( Page : : BLACK_PAGE ) <nl> + ? UPDATE_WRITE_BARRIER <nl> + : UPDATE_WEAK_WRITE_BARRIER ; <nl> CONDITIONAL_WRITE_BARRIER ( GetHeap ( ) , this , kValueOffset , val , mode ) ; <nl> } <nl> <nl> mmm a / test / unittests / heap / marking - unittest . cc <nl> ppp b / test / unittests / heap / marking - unittest . cc <nl> TEST ( Marking , TransitionWhiteGreyBlackGrey ) { <nl> free ( bitmap ) ; <nl> } <nl> <nl> - TEST ( Marking , SetAndClearRange ) { <nl> - Bitmap * bitmap = reinterpret_cast < Bitmap * > ( <nl> - calloc ( Bitmap : : kSize / kPointerSize , kPointerSize ) ) ; <nl> - for ( int i = 0 ; i < 3 ; i + + ) { <nl> - bitmap - > SetRange ( i , Bitmap : : kBitsPerCell + i ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 0 ] , 0xffffffff < < i ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 1 ] , ( 1 < < i ) - 1 ) ; <nl> - bitmap - > ClearRange ( i , Bitmap : : kBitsPerCell + i ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 0 ] , 0x0 ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 1 ] , 0x0 ) ; <nl> - } <nl> - free ( bitmap ) ; <nl> - } <nl> - <nl> - TEST ( Marking , ClearMultipleRanges ) { <nl> - Bitmap * bitmap = reinterpret_cast < Bitmap * > ( <nl> - calloc ( Bitmap : : kSize / kPointerSize , kPointerSize ) ) ; <nl> - CHECK ( bitmap - > AllBitsClearInRange ( 0 , Bitmap : : kBitsPerCell * 3 ) ) ; <nl> - bitmap - > SetRange ( 0 , Bitmap : : kBitsPerCell * 3 ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 0 ] , 0xffffffff ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 1 ] , 0xffffffff ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 2 ] , 0xffffffff ) ; <nl> - CHECK ( bitmap - > AllBitsSetInRange ( 0 , Bitmap : : kBitsPerCell * 3 ) ) ; <nl> - bitmap - > ClearRange ( Bitmap : : kBitsPerCell / 2 , Bitmap : : kBitsPerCell ) ; <nl> - bitmap - > ClearRange ( Bitmap : : kBitsPerCell , <nl> - Bitmap : : kBitsPerCell + Bitmap : : kBitsPerCell / 2 ) ; <nl> - bitmap - > ClearRange ( Bitmap : : kBitsPerCell * 2 + 8 , <nl> - Bitmap : : kBitsPerCell * 2 + 16 ) ; <nl> - bitmap - > ClearRange ( Bitmap : : kBitsPerCell * 2 + 24 , Bitmap : : kBitsPerCell * 3 ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 0 ] , 0xffff ) ; <nl> - CHECK ( bitmap - > AllBitsSetInRange ( 0 , Bitmap : : kBitsPerCell / 2 ) ) ; <nl> - CHECK ( bitmap - > AllBitsClearInRange ( Bitmap : : kBitsPerCell / 2 , <nl> - Bitmap : : kBitsPerCell ) ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 1 ] , 0xffff0000 ) ; <nl> - CHECK ( <nl> - bitmap - > AllBitsSetInRange ( Bitmap : : kBitsPerCell + Bitmap : : kBitsPerCell / 2 , <nl> - 2 * Bitmap : : kBitsPerCell ) ) ; <nl> - CHECK ( bitmap - > AllBitsClearInRange ( <nl> - Bitmap : : kBitsPerCell , Bitmap : : kBitsPerCell + Bitmap : : kBitsPerCell / 2 ) ) ; <nl> - CHECK_EQ ( reinterpret_cast < uint32_t * > ( bitmap ) [ 2 ] , 0xff00ff ) ; <nl> - CHECK ( bitmap - > AllBitsSetInRange ( 2 * Bitmap : : kBitsPerCell , <nl> - 2 * Bitmap : : kBitsPerCell + 8 ) ) ; <nl> - CHECK ( bitmap - > AllBitsClearInRange ( 2 * Bitmap : : kBitsPerCell + 24 , <nl> - Bitmap : : kBitsPerCell * 3 ) ) ; <nl> - free ( bitmap ) ; <nl> - } <nl> } / / namespace internal <nl> } / / namespace v8 <nl> | Revert of [ heap ] Remove black pages and use black areas instead . ( patchset id : 100001 of https : / / codereview . chromium . org / 2160613002 / ) | v8/v8 | 5cbe34bb46141ca30780a61b207d160ac88ecbcd | 2016-07-25T10:17:40Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.